context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; public class SimMap { public const int GRID_SIZE = 2; public string id; public SimMapType mapType; public SimBox box; public ISimMapListener mapListener = new SimMapListenerNull(); private int[] values; public int sizeX; public int sizeY; private SimRuleContext context = new SimRuleContext(); private int ticks; private SimMapRandomCoordinates randomCoordinates = new SimMapRandomCoordinates(); private SimMapCoordinatesInsideRadius coordinatesInsideRadius = new SimMapCoordinatesInsideRadius(); public void Init(SimMapType mapType, SimBox box, int sizeX, int sizeY) { this.id = mapType.id; this.mapType = mapType; this.box = box; values = new int[sizeX * sizeY]; this.sizeX = sizeX; this.sizeY = sizeY; context.box = box; context.mapPositionRadius = 0; } public void SetValue(int x, int y, int val) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (val < 0) val = 0; else if (val > mapType.capacity) val = mapType.capacity; if (val != values[y * sizeX + x]) { values[y * sizeX + x] = val; mapListener.OnMapModified(this, x, y, val); } } public int Get(int x, int y) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); return values[y * sizeX + x]; } public int Get(int x, int y, int radius) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (radius < 0) throw new ArgumentOutOfRangeException("radius", radius, "radius can't be a negative value"); coordinatesInsideRadius.Init(radius, x, y, 0, sizeX, 0, sizeY, false); int totalInsideRadius = 0; while(coordinatesInsideRadius.GetNextCoordinate(out x, out y)) totalInsideRadius += values[y * sizeX + x]; return totalInsideRadius; } public int Capacity(int x, int y) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); return mapType.capacity; } public int Capacity(int x, int y, int radius) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (radius < 0) throw new ArgumentOutOfRangeException("radius", radius, "radius can't be a negative value"); coordinatesInsideRadius.Init(radius, x, y, 0, sizeX, 0, sizeY, false); int capacityInsideRadius = 0; while(coordinatesInsideRadius.GetNextCoordinate(out x, out y)) capacityInsideRadius += mapType.capacity; return capacityInsideRadius; } public void Add(int x, int y, int toAdd) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (toAdd < 0) throw new ArgumentOutOfRangeException("toAdd", toAdd, "toAdd can't be a negative value"); int val = values[y * sizeX + x]; toAdd = Math.Min(mapType.capacity - val, toAdd); if (toAdd > 0) { val += toAdd; values[y * sizeX + x] = val; mapListener.OnMapModified(this, x, y, val); } } public void Add(int x, int y, int radius, int toAdd) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (radius < 0) throw new ArgumentOutOfRangeException("radius", radius, "radius can't be a negative value"); if (toAdd < 0) throw new ArgumentOutOfRangeException("toAdd", toAdd, "toAdd can't be a negative value"); coordinatesInsideRadius.Init(radius, x, y, 0, sizeX, 0, sizeY, true); int remainingToAdd = toAdd; while(remainingToAdd > 0 && coordinatesInsideRadius.GetNextCoordinate(out x, out y)) { int val = values[y * sizeX + x]; toAdd = Math.Min(mapType.capacity - val, remainingToAdd); if (toAdd > 0) { val += toAdd; remainingToAdd -= toAdd; values[y * sizeX + x] = val; mapListener.OnMapModified(this, x, y, val); } } } public void Remove(int x, int y, int toRemove) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (toRemove < 0) throw new ArgumentOutOfRangeException("toRemove", toRemove, "toRemove can't be a negative value"); int val = values[y * sizeX + x]; toRemove = Math.Min(val, toRemove); if (toRemove > 0) { val -= toRemove; values[y * sizeX + x] = val; mapListener.OnMapModified(this, x, y, val); } } public void Remove(int x, int y, int radius, int toRemove) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); if (radius < 0) throw new ArgumentOutOfRangeException("radius", radius, "radius can't be a negative value"); if (toRemove < 0) throw new ArgumentOutOfRangeException("toRemove", toRemove, "toRemove can't be a negative value"); coordinatesInsideRadius.Init(radius, x, y, 0, sizeX, 0, sizeY, true); int remainingToRemove = toRemove; while(remainingToRemove > 0 && coordinatesInsideRadius.GetNextCoordinate(out x, out y)) { int val = values[y * sizeX + x]; toRemove = Math.Min(val, remainingToRemove); if (toRemove > 0) { val -= toRemove; remainingToRemove -= toRemove; values[y * sizeX + x] = val; mapListener.OnMapModified(this, x, y, val); } } } public SimVector3 GetWorldPosition(int x, int y) { if (x < 0 || x >= sizeX) throw new ArgumentOutOfRangeException("x", x, "Invalid X Position"); if (y < 0 || y >= sizeY) throw new ArgumentOutOfRangeException("y", y, "Invalid Y Position"); return new SimVector3(x * GRID_SIZE, 0, y * GRID_SIZE); } public void ExecuteRules() { ticks++; SimRuleMap[] rules = mapType.rules; for (int i = 0; i < rules.Length; i++) { SimRuleMap rule = rules[i]; if (ticks % rule.rate == 0) { if (rule.randomTiles) { int tilesAmount = (rule.randomTilesPercent * sizeX * sizeY) / 100; randomCoordinates.Init(sizeX, sizeY); for (int j = 0; j < tilesAmount; j++) if (randomCoordinates.GetNextCoordinate(out context.mapPositionX, out context.mapPositionY)) rule.Execute(context); } else { for (int x = 0; x < sizeX; x++) { context.mapPositionX = x; for (int y = 0; y < sizeY; y++) { context.mapPositionY = y; rule.Execute(context); } } } } } } }
/* From http://xmlunit.sourceforge.net/ Moved here because the original library is for testing, and * it is tied to nunit, which we don't want to ship in production */ namespace Palaso.Lift.Merging.XmlDiff { using System; using System.IO; using System.Xml; ///<summary></summary> public class XmlDiff { private readonly XmlReader _controlReader; private readonly XmlReader _testReader; private readonly DiffConfiguration _diffConfiguration; private DiffResult _diffResult; ///<summary> /// Constructor. ///</summary> public XmlDiff(XmlInput control, XmlInput test, DiffConfiguration diffConfiguration) { _diffConfiguration = diffConfiguration; _controlReader = CreateXmlReader(control); if (control.Equals(test)) { _testReader = _controlReader; } else { _testReader = CreateXmlReader(test); } } ///<summary> /// Constructor. ///</summary> public XmlDiff(XmlInput control, XmlInput test) : this(control, test, new DiffConfiguration()) { } ///<summary> /// Constructor. ///</summary> public XmlDiff(TextReader control, TextReader test) : this(new XmlInput(control), new XmlInput(test)) { } ///<summary> /// Constructor. ///</summary> public XmlDiff(string control, string test) : this(new XmlInput(control), new XmlInput(test)) { } private XmlReader CreateXmlReader(XmlInput forInput) { XmlReader xmlReader = forInput.CreateXmlReader(); if (xmlReader is XmlTextReader) { ((XmlTextReader)xmlReader).WhitespaceHandling = _diffConfiguration.WhitespaceHandling; } if (_diffConfiguration.UseValidatingParser) { #pragma warning disable 612,618 XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); #pragma warning restore 612,618 return validatingReader; } return xmlReader; } ///<summary></summary> public DiffResult Compare() { if (_diffResult == null) { _diffResult = new DiffResult(); if (!_controlReader.Equals(_testReader)) { Compare(_diffResult); } } return _diffResult; } private void Compare(DiffResult result) { bool controlRead, testRead; try { do { controlRead = _controlReader.Read(); testRead = _testReader.Read(); Compare(result, ref controlRead, ref testRead); } while (controlRead && testRead); } catch (FlowControlException e) { Console.Out.WriteLine(e.Message); } } private void Compare(DiffResult result, ref bool controlRead, ref bool testRead) { if (controlRead) { if (testRead) { CompareNodes(result); CheckEmptyOrAtEndElement(result, ref controlRead, ref testRead); } else { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } //jh added this; under a condition I haven't got into an xdiff test yet, the // 'test' guy still had more children, and this fact was being missed by the above code if (controlRead != testRead) { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } private void CompareNodes(DiffResult result) { XmlNodeType controlNodeType = _controlReader.NodeType; XmlNodeType testNodeType = _testReader.NodeType; if (!controlNodeType.Equals(testNodeType)) { CheckNodeTypes(controlNodeType, testNodeType, result); } else if (controlNodeType == XmlNodeType.Element) { CompareElements(result); } else if (controlNodeType == XmlNodeType.Text) { CompareText(result); } } private void CheckNodeTypes(XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result) { XmlReader readerToAdvance = null; if (controlNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = _controlReader; } else if (testNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = _testReader; } if (readerToAdvance != null) { DifferenceFound(DifferenceType.HAS_XML_DECLARATION_PREFIX_ID, controlNodeType, testNodeType, result); readerToAdvance.Read(); CompareNodes(result); } else { DifferenceFound(DifferenceType.NODE_TYPE_ID, controlNodeType, testNodeType, result); } } private void CompareElements(DiffResult result) { string controlTagName = _controlReader.Name; string testTagName = _testReader.Name; if (!String.Equals(controlTagName, testTagName)) { DifferenceFound(DifferenceType.ELEMENT_TAG_NAME_ID, result); } else { int controlAttributeCount = _controlReader.AttributeCount; int testAttributeCount = _testReader.AttributeCount; if (controlAttributeCount != testAttributeCount) { DifferenceFound(DifferenceType.ELEMENT_NUM_ATTRIBUTES_ID, result); } else { CompareAttributes(result, controlAttributeCount); } } } private void CompareAttributes(DiffResult result, int controlAttributeCount) { string controlAttrValue, controlAttrName; string testAttrValue, testAttrName; _controlReader.MoveToFirstAttribute(); _testReader.MoveToFirstAttribute(); for (int i = 0; i < controlAttributeCount; ++i) { controlAttrName = _controlReader.Name; testAttrName = _testReader.Name; controlAttrValue = _controlReader.Value; testAttrValue = _testReader.Value; if (!String.Equals(controlAttrName, testAttrName)) { DifferenceFound(DifferenceType.ATTR_SEQUENCE_ID, result); if (!_testReader.MoveToAttribute(controlAttrName)) { DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID, result); } testAttrValue = _testReader.Value; } if (!String.Equals(controlAttrValue, testAttrValue)) { DifferenceFound(DifferenceType.ATTR_VALUE_ID, result); } _controlReader.MoveToNextAttribute(); _testReader.MoveToNextAttribute(); } } private void CompareText(DiffResult result) { string controlText = _controlReader.Value; string testText = _testReader.Value; if (!String.Equals(controlText, testText)) { DifferenceFound(DifferenceType.TEXT_VALUE_ID, result); } } private void DifferenceFound(DifferenceType differenceType, DiffResult result) { DifferenceFound(new Difference(differenceType), result); } private void DifferenceFound(Difference difference, DiffResult result) { result.DifferenceFound(this, difference); if (!ContinueComparison(difference)) { throw new FlowControlException(difference); } } private void DifferenceFound(DifferenceType differenceType, XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result) { DifferenceFound(new Difference(differenceType, controlNodeType, testNodeType), result); } private bool ContinueComparison(Difference afterDifference) { return !afterDifference.HasMajorDifference; } private void CheckEmptyOrAtEndElement(DiffResult result, ref bool controlRead, ref bool testRead) { if (_controlReader.IsEmptyElement) { if (!_testReader.IsEmptyElement) { CheckEndElement(_testReader, ref testRead, result); } } else { if (_testReader.IsEmptyElement) { CheckEndElement(_controlReader, ref controlRead, result); } } } private void CheckEndElement(XmlReader reader, ref bool readResult, DiffResult result) { readResult = reader.Read(); if (!readResult || reader.NodeType != XmlNodeType.EndElement) { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } private class FlowControlException : ApplicationException { public FlowControlException(Difference cause) : base(cause.ToString()) { } } ///<summary></summary> public string OptionalDescription { get { return _diffConfiguration.Description; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using RentalNinja.Models; namespace RentalNinja.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { public override void BuildModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("RentalNinja.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
// // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; namespace Mono.Data.SqlExpressions { internal class Numeric { internal static bool IsNumeric (object o) { if (o is IConvertible) { TypeCode tc = ((IConvertible)o).GetTypeCode(); if(TypeCode.Char <= tc && tc <= TypeCode.Decimal) return true; } return false; } //extends to Int32/Int64/Decimal/Double internal static IConvertible Unify (IConvertible o) { switch (o.GetTypeCode()) { case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: return (IConvertible)Convert.ChangeType (o, TypeCode.Int32); case TypeCode.UInt32: return (IConvertible)Convert.ChangeType (o, TypeCode.Int64); case TypeCode.UInt64: return (IConvertible)Convert.ChangeType (o, TypeCode.Decimal); case TypeCode.Single: return (IConvertible)Convert.ChangeType (o, TypeCode.Double); default: return o; } } //(note: o1 and o2 must both be of type Int32/Int64/Decimal/Double) internal static TypeCode ToSameType (ref IConvertible o1, ref IConvertible o2) { TypeCode tc1 = o1.GetTypeCode(); TypeCode tc2 = o2.GetTypeCode(); if (tc1 == tc2) return tc1; if (tc1 == TypeCode.DBNull || tc2 == TypeCode.DBNull) return TypeCode.DBNull; // is it ok to make such assumptions about the order of an enum? if (tc1 < tc2) { o1 = (IConvertible)Convert.ChangeType (o1, tc2); return tc2; } else { o2 = (IConvertible)Convert.ChangeType (o2, tc1); return tc1; } } internal static IConvertible Add (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return (long)((int)o1 + (int)o2); case TypeCode.Int64: return (long)o1 + (long)o2; case TypeCode.Double: return (double)o1 + (double)o2; case TypeCode.Decimal: return (decimal)o1 + (decimal)o2; default: return DBNull.Value; } } internal static IConvertible Subtract (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return (int)o1 - (int)o2; case TypeCode.Int64: return (long)o1 - (long)o2; case TypeCode.Double: return (double)o1 - (double)o2; case TypeCode.Decimal: return (decimal)o1 - (decimal)o2; default: return DBNull.Value; } } internal static IConvertible Multiply (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return (int)o1 * (int)o2; case TypeCode.Int64: return (long)o1 * (long)o2; case TypeCode.Double: return (double)o1 * (double)o2; case TypeCode.Decimal: return (decimal)o1 * (decimal)o2; default: return DBNull.Value; } } internal static IConvertible Divide (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return (int)o1 / (int)o2; case TypeCode.Int64: return (long)o1 / (long)o2; case TypeCode.Double: return (double)o1 / (double)o2; case TypeCode.Decimal: return (decimal)o1 / (decimal)o2; default: return DBNull.Value; } } internal static IConvertible Modulo (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return (int)o1 % (int)o2; case TypeCode.Int64: return (long)o1 % (long)o2; case TypeCode.Double: return (double)o1 % (double)o2; case TypeCode.Decimal: return (decimal)o1 % (decimal)o2; default: return DBNull.Value; } } internal static IConvertible Negative (IConvertible o) { switch (o.GetTypeCode()) { case TypeCode.Int32: return -((int)o); case TypeCode.Int64: return -((long)o); case TypeCode.Double: return -((double)o); case TypeCode.Decimal: return -((decimal)o); default: return DBNull.Value; } } internal static IConvertible Min (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return System.Math.Min ((int)o1, (int)o2); case TypeCode.Int64: return System.Math.Min ((long)o1, (long)o2); case TypeCode.Double: return System.Math.Min ((double)o1, (double)o2); case TypeCode.Decimal: return System.Math.Min ((decimal)o1, (decimal)o2); default: return DBNull.Value; } } internal static IConvertible Max (IConvertible o1, IConvertible o2) { switch (ToSameType (ref o1, ref o2)) { case TypeCode.Int32: return System.Math.Max ((int)o1, (int)o2); case TypeCode.Int64: return System.Math.Max ((long)o1, (long)o2); case TypeCode.Double: return System.Math.Max ((double)o1, (double)o2); case TypeCode.Decimal: return System.Math.Max ((decimal)o1, (decimal)o2); default: return DBNull.Value; } } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * APIs Discovery Service Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/discovery/'>APIs Discovery Service</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>snapshot (0) * <tr><th>API Docs * <td><a href='https://developers.google.com/discovery/'> * https://developers.google.com/discovery/</a> * <tr><th>Discovery Name<td>discovery * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using APIs Discovery Service can be found at * <a href='https://developers.google.com/discovery/'>https://developers.google.com/discovery/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Discovery.v1 { /// <summary>The Discovery Service.</summary> public class DiscoveryService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public DiscoveryService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public DiscoveryService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { apis = new ApisResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "discovery"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/discovery/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "discovery/v1/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif private readonly ApisResource apis; /// <summary>Gets the Apis resource.</summary> public virtual ApisResource Apis { get { return apis; } } } ///<summary>A base abstract class for Discovery requests.</summary> public abstract class DiscoveryBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new DiscoveryBaseServiceRequest instance.</summary> protected DiscoveryBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Discovery parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "apis" collection of methods.</summary> public class ApisResource { private const string Resource = "apis"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ApisResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Retrieve the description of a particular version of an api.</summary> /// <param name="api">The name of the API.</param> /// <param name="version">The version of the API.</param> public virtual GetRestRequest GetRest(string api, string version) { return new GetRestRequest(service, api, version); } /// <summary>Retrieve the description of a particular version of an api.</summary> public class GetRestRequest : DiscoveryBaseServiceRequest<Google.Apis.Discovery.v1.Data.RestDescription> { /// <summary>Constructs a new GetRest request.</summary> public GetRestRequest(Google.Apis.Services.IClientService service, string api, string version) : base(service) { Api = api; Version = version; InitParameters(); } /// <summary>The name of the API.</summary> [Google.Apis.Util.RequestParameterAttribute("api", Google.Apis.Util.RequestParameterType.Path)] public virtual string Api { get; private set; } /// <summary>The version of the API.</summary> [Google.Apis.Util.RequestParameterAttribute("version", Google.Apis.Util.RequestParameterType.Path)] public virtual string Version { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "getRest"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "apis/{api}/{version}/rest"; } } /// <summary>Initializes GetRest parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "api", new Google.Apis.Discovery.Parameter { Name = "api", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "version", new Google.Apis.Discovery.Parameter { Name = "version", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Retrieve the list of APIs supported at this endpoint.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Retrieve the list of APIs supported at this endpoint.</summary> public class ListRequest : DiscoveryBaseServiceRequest<Google.Apis.Discovery.v1.Data.DirectoryList> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Only include APIs with the given name.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Query)] public virtual string Name { get; set; } /// <summary>Return only the preferred version of an API.</summary> /// [default: false] [Google.Apis.Util.RequestParameterAttribute("preferred", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Preferred { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "apis"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "preferred", new Google.Apis.Discovery.Parameter { Name = "preferred", IsRequired = false, ParameterType = "query", DefaultValue = "false", Pattern = null, }); } } } } namespace Google.Apis.Discovery.v1.Data { public class DirectoryList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Indicate the version of the Discovery API used to generate this doc.</summary> [Newtonsoft.Json.JsonPropertyAttribute("discoveryVersion")] public virtual string DiscoveryVersion { get; set; } /// <summary>The individual directory entries. One entry per api/version pair.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<DirectoryList.ItemsData> Items { get; set; } /// <summary>The kind for this response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class ItemsData { /// <summary>The description of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>A link to the discovery document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("discoveryLink")] public virtual string DiscoveryLink { get; set; } /// <summary>The URL for the discovery REST document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("discoveryRestUrl")] public virtual string DiscoveryRestUrl { get; set; } /// <summary>A link to human readable documentation for the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("documentationLink")] public virtual string DocumentationLink { get; set; } /// <summary>Links to 16x16 and 32x32 icons representing the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("icons")] public virtual ItemsData.IconsData Icons { get; set; } /// <summary>The id of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind for this response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Labels for the status of this API, such as labs or deprecated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IList<string> Labels { get; set; } /// <summary>The name of the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>True if this version is the preferred version to use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("preferred")] public virtual System.Nullable<bool> Preferred { get; set; } /// <summary>The title of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The version of the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual string Version { get; set; } /// <summary>Links to 16x16 and 32x32 icons representing the API.</summary> public class IconsData { /// <summary>The URL of the 16x16 icon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("x16")] public virtual string X16 { get; set; } /// <summary>The URL of the 32x32 icon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("x32")] public virtual string X32 { get; set; } } } } public class JsonSchema : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A reference to another schema. The value of this property is the "id" of another schema.</summary> [Newtonsoft.Json.JsonPropertyAttribute("$ref")] public virtual string Ref__ { get; set; } /// <summary>If this is a schema for an object, this property is the schema for any additional properties with /// dynamic keys on this object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("additionalProperties")] public virtual JsonSchema AdditionalProperties { get; set; } /// <summary>Additional information about this property.</summary> [Newtonsoft.Json.JsonPropertyAttribute("annotations")] public virtual JsonSchema.AnnotationsData Annotations { get; set; } /// <summary>The default value of this property (if one exists).</summary> [Newtonsoft.Json.JsonPropertyAttribute("default")] public virtual string Default__ { get; set; } /// <summary>A description of this object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Values this parameter may take (if it is an enum).</summary> [Newtonsoft.Json.JsonPropertyAttribute("enum")] public virtual System.Collections.Generic.IList<string> Enum__ { get; set; } /// <summary>The descriptions for the enums. Each position maps to the corresponding value in the "enum" /// array.</summary> [Newtonsoft.Json.JsonPropertyAttribute("enumDescriptions")] public virtual System.Collections.Generic.IList<string> EnumDescriptions { get; set; } /// <summary>An additional regular expression or key that helps constrain the value. For more details see: /// http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>Unique identifier for this schema.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>If this is a schema for an array, this property is the schema for each element in the /// array.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual JsonSchema Items { get; set; } /// <summary>Whether this parameter goes in the query or the path for REST requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary>The maximum value of this parameter.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maximum")] public virtual string Maximum { get; set; } /// <summary>The minimum value of this parameter.</summary> [Newtonsoft.Json.JsonPropertyAttribute("minimum")] public virtual string Minimum { get; set; } /// <summary>The regular expression this parameter must conform to. Uses Java 6 regex format: /// http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html</summary> [Newtonsoft.Json.JsonPropertyAttribute("pattern")] public virtual string Pattern { get; set; } /// <summary>If this is a schema for an object, list the schema for each property of this object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("properties")] public virtual System.Collections.Generic.IDictionary<string,JsonSchema> Properties { get; set; } /// <summary>The value is read-only, generated by the service. The value cannot be modified by the client. If /// the value is included in a POST, PUT, or PATCH request, it is ignored by the service.</summary> [Newtonsoft.Json.JsonPropertyAttribute("readOnly")] public virtual System.Nullable<bool> ReadOnly__ { get; set; } /// <summary>Whether this parameter may appear multiple times.</summary> [Newtonsoft.Json.JsonPropertyAttribute("repeated")] public virtual System.Nullable<bool> Repeated { get; set; } /// <summary>Whether the parameter is required.</summary> [Newtonsoft.Json.JsonPropertyAttribute("required")] public virtual System.Nullable<bool> Required { get; set; } /// <summary>The value type for this schema. A list of values can be found here: http://tools.ietf.org/html /// /draft-zyp-json-schema-03#section-5.1</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>In a variant data type, the value of one property is used to determine how to interpret the entire /// entity. Its value must exist in a map of descriminant values to schema names.</summary> [Newtonsoft.Json.JsonPropertyAttribute("variant")] public virtual JsonSchema.VariantData Variant { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Additional information about this property.</summary> public class AnnotationsData { /// <summary>A list of methods for which this property is required on requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("required")] public virtual System.Collections.Generic.IList<string> Required { get; set; } } /// <summary>In a variant data type, the value of one property is used to determine how to interpret the entire /// entity. Its value must exist in a map of descriminant values to schema names.</summary> public class VariantData { /// <summary>The name of the type discriminant property.</summary> [Newtonsoft.Json.JsonPropertyAttribute("discriminant")] public virtual string Discriminant { get; set; } /// <summary>The map of discriminant value to schema to use for parsing..</summary> [Newtonsoft.Json.JsonPropertyAttribute("map")] public virtual System.Collections.Generic.IList<VariantData.MapData> Map { get; set; } public class MapData { [Newtonsoft.Json.JsonPropertyAttribute("$ref")] public virtual string Ref__ { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("type_value")] public virtual string TypeValue { get; set; } } } } public class RestDescription : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Authentication information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auth")] public virtual RestDescription.AuthData Auth { get; set; } /// <summary>[DEPRECATED] The base path for REST requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("basePath")] public virtual string BasePath { get; set; } /// <summary>[DEPRECATED] The base URL for REST requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("baseUrl")] public virtual string BaseUrl { get; set; } /// <summary>The path for REST batch requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("batchPath")] public virtual string BatchPath { get; set; } /// <summary>Indicates how the API name should be capitalized and split into various parts. Useful for /// generating pretty class names.</summary> [Newtonsoft.Json.JsonPropertyAttribute("canonicalName")] public virtual string CanonicalName { get; set; } /// <summary>The description of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Indicate the version of the Discovery API used to generate this doc.</summary> [Newtonsoft.Json.JsonPropertyAttribute("discoveryVersion")] public virtual string DiscoveryVersion { get; set; } /// <summary>A link to human readable documentation for the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("documentationLink")] public virtual string DocumentationLink { get; set; } /// <summary>The ETag for this response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary>Enable exponential backoff for suitable methods in the generated clients.</summary> [Newtonsoft.Json.JsonPropertyAttribute("exponentialBackoffDefault")] public virtual System.Nullable<bool> ExponentialBackoffDefault { get; set; } /// <summary>A list of supported features for this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("features")] public virtual System.Collections.Generic.IList<string> Features { get; set; } /// <summary>Links to 16x16 and 32x32 icons representing the API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("icons")] public virtual RestDescription.IconsData Icons { get; set; } /// <summary>The ID of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind for this response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Labels for the status of this API, such as labs or deprecated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IList<string> Labels { get; set; } /// <summary>API-level methods for this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("methods")] public virtual System.Collections.Generic.IDictionary<string,RestMethod> Methods { get; set; } /// <summary>The name of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The domain of the owner of this API. Together with the ownerName and a packagePath values, this can /// be used to generate a library for this API which would have a unique fully qualified name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ownerDomain")] public virtual string OwnerDomain { get; set; } /// <summary>The name of the owner of this API. See ownerDomain.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ownerName")] public virtual string OwnerName { get; set; } /// <summary>The package of the owner of this API. See ownerDomain.</summary> [Newtonsoft.Json.JsonPropertyAttribute("packagePath")] public virtual string PackagePath { get; set; } /// <summary>Common parameters that apply across all apis.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameters")] public virtual System.Collections.Generic.IDictionary<string,JsonSchema> Parameters { get; set; } /// <summary>The protocol described by this document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("protocol")] public virtual string Protocol { get; set; } /// <summary>The resources in this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resources")] public virtual System.Collections.Generic.IDictionary<string,RestResource> Resources { get; set; } /// <summary>The version of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("revision")] public virtual string Revision { get; set; } /// <summary>The root URL under which all API services live.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rootUrl")] public virtual string RootUrl { get; set; } /// <summary>The schemas for this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("schemas")] public virtual System.Collections.Generic.IDictionary<string,JsonSchema> Schemas { get; set; } /// <summary>The base path for all REST requests.</summary> [Newtonsoft.Json.JsonPropertyAttribute("servicePath")] public virtual string ServicePath { get; set; } /// <summary>The title of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The version of this API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual string Version { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("version_module")] public virtual System.Nullable<bool> VersionModule { get; set; } /// <summary>Authentication information.</summary> public class AuthData { /// <summary>OAuth 2.0 authentication information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("oauth2")] public virtual AuthData.Oauth2Data Oauth2 { get; set; } /// <summary>OAuth 2.0 authentication information.</summary> public class Oauth2Data { /// <summary>Available OAuth 2.0 scopes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scopes")] public virtual System.Collections.Generic.IDictionary<string,Oauth2Data.ScopesDataElement> Scopes { get; set; } /// <summary>The scope value.</summary> public class ScopesDataElement { /// <summary>Description of scope.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } } } } /// <summary>Links to 16x16 and 32x32 icons representing the API.</summary> public class IconsData { /// <summary>The URL of the 16x16 icon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("x16")] public virtual string X16 { get; set; } /// <summary>The URL of the 32x32 icon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("x32")] public virtual string X32 { get; set; } } } public class RestMethod : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Description of this method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Whether this method requires an ETag to be specified. The ETag is sent as an HTTP If-Match or If- /// None-Match header.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etagRequired")] public virtual System.Nullable<bool> EtagRequired { get; set; } /// <summary>HTTP method used by this method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("httpMethod")] public virtual string HttpMethod { get; set; } /// <summary>A unique ID for this method. This property can be used to match methods between different versions /// of Discovery.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Media upload parameters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mediaUpload")] public virtual RestMethod.MediaUploadData MediaUpload { get; set; } /// <summary>Ordered list of required parameters, serves as a hint to clients on how to structure their method /// signatures. The array is ordered such that the "most-significant" parameter appears first.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameterOrder")] public virtual System.Collections.Generic.IList<string> ParameterOrder { get; set; } /// <summary>Details for all parameters in this method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameters")] public virtual System.Collections.Generic.IDictionary<string,JsonSchema> Parameters { get; set; } /// <summary>The URI path of this REST method. Should be used in conjunction with the basePath property at the /// api-level.</summary> [Newtonsoft.Json.JsonPropertyAttribute("path")] public virtual string Path { get; set; } /// <summary>The schema for the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("request")] public virtual RestMethod.RequestData Request { get; set; } /// <summary>The schema for the response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual RestMethod.ResponseData Response { get; set; } /// <summary>OAuth 2.0 scopes applicable to this method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scopes")] public virtual System.Collections.Generic.IList<string> Scopes { get; set; } /// <summary>Whether this method supports media downloads.</summary> [Newtonsoft.Json.JsonPropertyAttribute("supportsMediaDownload")] public virtual System.Nullable<bool> SupportsMediaDownload { get; set; } /// <summary>Whether this method supports media uploads.</summary> [Newtonsoft.Json.JsonPropertyAttribute("supportsMediaUpload")] public virtual System.Nullable<bool> SupportsMediaUpload { get; set; } /// <summary>Whether this method supports subscriptions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("supportsSubscription")] public virtual System.Nullable<bool> SupportsSubscription { get; set; } /// <summary>Indicates that downloads from this method should use the download service URL (i.e. "/download"). /// Only applies if the method supports media download.</summary> [Newtonsoft.Json.JsonPropertyAttribute("useMediaDownloadService")] public virtual System.Nullable<bool> UseMediaDownloadService { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Media upload parameters.</summary> public class MediaUploadData { /// <summary>MIME Media Ranges for acceptable media uploads to this method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accept")] public virtual System.Collections.Generic.IList<string> Accept { get; set; } /// <summary>Maximum size of a media upload, such as "1MB", "2GB" or "3TB".</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxSize")] public virtual string MaxSize { get; set; } /// <summary>Supported upload protocols.</summary> [Newtonsoft.Json.JsonPropertyAttribute("protocols")] public virtual MediaUploadData.ProtocolsData Protocols { get; set; } /// <summary>Supported upload protocols.</summary> public class ProtocolsData { /// <summary>Supports the Resumable Media Upload protocol.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resumable")] public virtual ProtocolsData.ResumableData Resumable { get; set; } /// <summary>Supports uploading as a single HTTP request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("simple")] public virtual ProtocolsData.SimpleData Simple { get; set; } /// <summary>Supports the Resumable Media Upload protocol.</summary> public class ResumableData { /// <summary>True if this endpoint supports uploading multipart media.</summary> [Newtonsoft.Json.JsonPropertyAttribute("multipart")] public virtual System.Nullable<bool> Multipart { get; set; } /// <summary>The URI path to be used for upload. Should be used in conjunction with the basePath /// property at the api-level.</summary> [Newtonsoft.Json.JsonPropertyAttribute("path")] public virtual string Path { get; set; } } /// <summary>Supports uploading as a single HTTP request.</summary> public class SimpleData { /// <summary>True if this endpoint supports upload multipart media.</summary> [Newtonsoft.Json.JsonPropertyAttribute("multipart")] public virtual System.Nullable<bool> Multipart { get; set; } /// <summary>The URI path to be used for upload. Should be used in conjunction with the basePath /// property at the api-level.</summary> [Newtonsoft.Json.JsonPropertyAttribute("path")] public virtual string Path { get; set; } } } } /// <summary>The schema for the request.</summary> public class RequestData { /// <summary>Schema ID for the request schema.</summary> [Newtonsoft.Json.JsonPropertyAttribute("$ref")] public virtual string Ref__ { get; set; } /// <summary>parameter name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameterName")] public virtual string ParameterName { get; set; } } /// <summary>The schema for the response.</summary> public class ResponseData { /// <summary>Schema ID for the response schema.</summary> [Newtonsoft.Json.JsonPropertyAttribute("$ref")] public virtual string Ref__ { get; set; } } } public class RestResource : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Methods on this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("methods")] public virtual System.Collections.Generic.IDictionary<string,RestMethod> Methods { get; set; } /// <summary>Sub-resources on this resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resources")] public virtual System.Collections.Generic.IDictionary<string,RestResource> Resources { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
#region Copyright Information // Sentience Lab Unity Framework // (C) Sentience Lab (sentiencelab@aut.ac.nz), Auckland University of Technology, Auckland, New Zealand #endregion Copyright Information using SentienceLab.Data; using SentienceLab.Input; using UnityEngine; namespace SentienceLab { /// <summary> /// Component for controlling a laser-like ray to point at objects in the scene. /// This component can be queried as to what it is pointing at. /// </summary> /// [RequireComponent(typeof(LineRenderer))] public class PointerRay : MonoBehaviour { [Tooltip("Enable or disable the ray")] public bool rayEnabled = true; [Tooltip("Maximum range of the ray")] public float rayRange = 100.0f; [Tooltip("List of tags that the pointer reacts to (e.g., 'floor')")] public string[] tagList = { }; [Tooltip("List of colliders to check for inside-out collisions")] public Collider[] checkInsideColliders = { }; [Tooltip("Object to render at the point where the ray meets another game object (optional)")] public Transform activeEndPoint = null; [Tooltip("(Optional) Action to activate the ray")] public string activationAction = ""; [Tooltip("(Optional) Parameter that activates the ray")] public Parameter_Boolean activationParameter = null; [Tooltip("(Optional) Parameter for relative ray direction")] public Parameter_Vector3 rayDirection = null; /// <summary> /// Interface to implement for objects that need to react to the pointer ray entering/exiting their colliders. /// </summary> /// public interface IPointerRayTarget { void OnPointerEnter(PointerRay _ray); void OnPointerExit(PointerRay _ray); } void Start() { line = GetComponent<LineRenderer>(); line.positionCount = 2; line.useWorldSpace = true; overrideTarget = false; activeTarget = null; if (activationAction.Trim().Length > 0) { handlerActivate = InputHandler.Find(activationAction); rayEnabled = false; } } void LateUpdate() { // assume nothing is hit at first rayTarget.distance = 0; if (handlerActivate != null) { rayEnabled = handlerActivate.IsActive(); } if (activationParameter != null) { rayEnabled = activationParameter.Value; } // change in enabled flag if (line.enabled != rayEnabled) { line.enabled = rayEnabled; if ((activeEndPoint != null) && !rayEnabled) { activeEndPoint.gameObject.SetActive(false); } } if (rayEnabled) { bool hit = false; // construct ray Vector3 forward = (rayDirection == null) ? Vector3.forward : rayDirection.Value; forward = transform.TransformDirection(forward); // relative forward to "world forward" Ray ray = new Ray(transform.position, forward); Vector3 end = ray.origin + ray.direction * rayRange; line.SetPosition(0, ray.origin); Debug.DrawLine(ray.origin, end, Color.red); if (!overrideTarget) { // do raycast hit = Physics.Raycast(ray, out rayTarget, rayRange); // test tags if (hit && (tagList.Length > 0)) { hit = false; foreach (string tag in tagList) { if (rayTarget.transform.tag.CompareTo(tag) == 0) { hit = true; break; } } if (!hit) { // tag test negative > reset raycast structure Physics.Raycast(ray, out rayTarget, 0); } } // are there collides to check for inside-collisions? if (checkInsideColliders.Length > 0) { // checking inside collides: reverse ray Ray reverse = new Ray(ray.origin + ray.direction * rayRange, -ray.direction); float minDistance = hit ? rayTarget.distance : rayRange; foreach (Collider c in checkInsideColliders) { RaycastHit hitReverse; if (c.Raycast(reverse, out hitReverse, rayRange)) { if (rayRange - hitReverse.distance < minDistance) { rayTarget = hitReverse; minDistance = rayRange - hitReverse.distance; hit = true; } } } } } else { Physics.Raycast(ray, out rayTarget, 0); // reset structure rayTarget.point = overridePoint; // override point hit = true; } if (hit) { // hit something > draw ray to there and render end point object line.SetPosition(1, rayTarget.point); if (activeEndPoint != null) { activeEndPoint.position = rayTarget.point; activeEndPoint.gameObject.SetActive(true); } } else { // hit nothing > draw ray to end and disable end point object line.SetPosition(1, end); if (activeEndPoint != null) { activeEndPoint.gameObject.SetActive(false); } } } HandleEvents(); } /// <summary> /// Handles events like OnEnter/OnExit if the object that the ray points at /// has implemented the IPointerRayTarget interface /// </summary> /// private void HandleEvents() { IPointerRayTarget currentTarget = null; if (rayTarget.distance > 0 && (rayTarget.transform != null)) { currentTarget = rayTarget.collider.gameObject.GetComponent<IPointerRayTarget>(); } if (currentTarget != activeTarget) { if (activeTarget != null) activeTarget.OnPointerExit(this); activeTarget = currentTarget; if (activeTarget != null) activeTarget.OnPointerEnter(this); } } /// <summary> /// Returns the current target of the ray. /// </summary> /// <returns>the last raycastHit result</returns> /// public RaycastHit GetRayTarget() { return rayTarget; } /// <summary> /// Checks whether the ray is enabled or not. /// </summary> /// <returns><c>true</c> when the ray is enabled</returns> /// public bool IsEnabled() { return rayEnabled; } /// <summary> /// Sets the current target of the ray. /// </summary> /// public void OverrideRayTarget(Vector3 pos) { if (pos.Equals(Vector3.zero)) { overrideTarget = false; } else { overrideTarget = true; overridePoint = pos; } } private LineRenderer line; private RaycastHit rayTarget; private bool overrideTarget; private Vector3 overridePoint; private InputHandler handlerActivate; private IPointerRayTarget activeTarget; } }
#region License /* Copyright (c) 2016 VulkaNet Project - Daniil Rodin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Linq; namespace VulkaNet { public interface IVkInstance : IVkHandledObject, IDisposable { VkInstance.HandleType Handle { get; } VkInstance.DirectFunctions Direct { get; } IReadOnlyList<IVkPhysicalDevice> PhysicalDevices { get; } VkObjectResult<IVkSurfaceKHR> CreateAndroidSurfaceKHR(VkAndroidSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateMirSurfaceKHR(VkMirSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateWaylandSurfaceKHR(VkWaylandSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateWin32SurfaceKHR(VkWin32SurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateXcbSurfaceKHR(VkXcbSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateXlibSurfaceKHR(VkXlibSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkSurfaceKHR> CreateDisplayPlaneSurfaceKHR(VkDisplaySurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator); VkObjectResult<IVkDebugReportCallbackEXT> CreateDebugReportCallbackEXT(VkDebugReportCallbackCreateInfoEXT createInfo, IVkAllocationCallbacks allocator); void DebugReportMessageEXT(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, ulong obj, IntPtr location, int messageCode, string layerPrefix, string message); } public unsafe class VkInstance : IVkInstance { public HandleType Handle { get; } private VkAllocationCallbacks Allocator { get; } public DirectFunctions Direct { get; } public IReadOnlyList<IVkPhysicalDevice> PhysicalDevices { get; } public IntPtr RawHandle => Handle.InternalHandle; public VkInstance(HandleType handle, VkAllocationCallbacks allocator) { Handle = handle; Allocator = allocator; Direct = new DirectFunctions(this); PhysicalDevices = EnumeratePhysicalDevices(); } public struct HandleType { public readonly IntPtr InternalHandle; public HandleType(IntPtr internalHandle) { InternalHandle = internalHandle; } public override string ToString() => InternalHandle.ToString(); public static int SizeInBytes { get; } = IntPtr.Size; public static HandleType Null => new HandleType(default(IntPtr)); } public class DirectFunctions { public DestroyInstanceDelegate DestroyInstance { get; } public delegate void DestroyInstanceDelegate( HandleType instance, VkAllocationCallbacks.Raw* pAllocator); public EnumeratePhysicalDevicesDelegate EnumeratePhysicalDevices { get; } public delegate VkResult EnumeratePhysicalDevicesDelegate( HandleType instance, int* pPhysicalDeviceCount, IntPtr* pPhysicalDevices); public CreateAndroidSurfaceKHRDelegate CreateAndroidSurfaceKHR { get; } public delegate VkResult CreateAndroidSurfaceKHRDelegate( HandleType instance, VkAndroidSurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateMirSurfaceKHRDelegate CreateMirSurfaceKHR { get; } public delegate VkResult CreateMirSurfaceKHRDelegate( HandleType instance, VkMirSurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateWaylandSurfaceKHRDelegate CreateWaylandSurfaceKHR { get; } public delegate VkResult CreateWaylandSurfaceKHRDelegate( HandleType instance, VkWaylandSurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateWin32SurfaceKHRDelegate CreateWin32SurfaceKHR { get; } public delegate VkResult CreateWin32SurfaceKHRDelegate( HandleType instance, VkWin32SurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateXcbSurfaceKHRDelegate CreateXcbSurfaceKHR { get; } public delegate VkResult CreateXcbSurfaceKHRDelegate( HandleType instance, VkXcbSurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateXlibSurfaceKHRDelegate CreateXlibSurfaceKHR { get; } public delegate VkResult CreateXlibSurfaceKHRDelegate( HandleType instance, VkXlibSurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public DestroySurfaceKHRDelegate DestroySurfaceKHR { get; } public delegate VkResult DestroySurfaceKHRDelegate( HandleType instance, VkSurfaceKHR.HandleType surface, VkAllocationCallbacks.Raw* pAllocator); public CreateDisplayPlaneSurfaceKHRDelegate CreateDisplayPlaneSurfaceKHR { get; } public delegate VkResult CreateDisplayPlaneSurfaceKHRDelegate( HandleType instance, VkDisplaySurfaceCreateInfoKHR.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkSurfaceKHR.HandleType* pSurface); public CreateDebugReportCallbackEXTDelegate CreateDebugReportCallbackEXT { get; } public delegate VkResult CreateDebugReportCallbackEXTDelegate( HandleType instance, VkDebugReportCallbackCreateInfoEXT.Raw* pCreateInfo, VkAllocationCallbacks.Raw* pAllocator, VkDebugReportCallbackEXT.HandleType* pCallback); public DebugReportMessageEXTDelegate DebugReportMessageEXT { get; } public delegate void DebugReportMessageEXTDelegate( HandleType instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, ulong obj, IntPtr location, int messageCode, byte* pLayerPrefix, byte* pMessage); public DestroyDebugReportCallbackEXTDelegate DestroyDebugReportCallbackEXT { get; } public delegate void DestroyDebugReportCallbackEXTDelegate( HandleType instance, VkDebugReportCallbackEXT.HandleType callback, VkAllocationCallbacks.Raw* pAllocator); public DirectFunctions(IVkInstance instance) { DestroyInstance = VkHelpers.GetInstanceDelegate<DestroyInstanceDelegate>(instance, "vkDestroyInstance"); EnumeratePhysicalDevices = VkHelpers.GetInstanceDelegate<EnumeratePhysicalDevicesDelegate>(instance, "vkEnumeratePhysicalDevices"); CreateAndroidSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateAndroidSurfaceKHRDelegate>(instance, "vkCreateAndroidSurfaceKHR"); CreateMirSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateMirSurfaceKHRDelegate>(instance, "vkCreateMirSurfaceKHR"); CreateWaylandSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateWaylandSurfaceKHRDelegate>(instance, "vkCreateWaylandSurfaceKHR"); CreateWin32SurfaceKHR = VkHelpers.GetInstanceDelegate<CreateWin32SurfaceKHRDelegate>(instance, "vkCreateWin32SurfaceKHR"); CreateXcbSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateXcbSurfaceKHRDelegate>(instance, "vkCreateXcbSurfaceKHR"); CreateXlibSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateXlibSurfaceKHRDelegate>(instance, "vkCreateXlibSurfaceKHR"); DestroySurfaceKHR = VkHelpers.GetInstanceDelegate<DestroySurfaceKHRDelegate>(instance, "vkDestroySurfaceKHR"); CreateDisplayPlaneSurfaceKHR = VkHelpers.GetInstanceDelegate<CreateDisplayPlaneSurfaceKHRDelegate>(instance, "vkCreateDisplayPlaneSurfaceKHR"); CreateDebugReportCallbackEXT = VkHelpers.GetInstanceDelegate<CreateDebugReportCallbackEXTDelegate>(instance, "vkCreateDebugReportCallbackEXT"); DebugReportMessageEXT = VkHelpers.GetInstanceDelegate<DebugReportMessageEXTDelegate>(instance, "vkDebugReportMessageEXT"); DestroyDebugReportCallbackEXT = VkHelpers.GetInstanceDelegate<DestroyDebugReportCallbackEXTDelegate>(instance, "vkDestroyDebugReportCallbackEXT"); } } public void Dispose() { var size = Allocator.SizeOfMarshalIndirect(); VkHelpers.RunWithUnamangedData(size, DisposeInternal); } private void DisposeInternal(IntPtr data) { var unmanaged = (byte*)data; var pAllocator = Allocator.MarshalIndirect(ref unmanaged); Direct.DestroyInstance(Handle, pAllocator); } private IReadOnlyList<IVkPhysicalDevice> EnumeratePhysicalDevices() { int count; Direct.EnumeratePhysicalDevices(Handle, &count, (IntPtr*)0).CheckSuccess(); var rawArray = new IntPtr[count]; fixed (IntPtr* pRawArray = rawArray) { Direct.EnumeratePhysicalDevices(Handle, &count, pRawArray).CheckSuccess(); } return rawArray.Select(x => new VkPhysicalDevice(this, x)).ToArray(); } public VkObjectResult<IVkSurfaceKHR> CreateAndroidSurfaceKHR(VkAndroidSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateAndroidSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateMirSurfaceKHR(VkMirSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateMirSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateWaylandSurfaceKHR(VkWaylandSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateWaylandSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateWin32SurfaceKHR(VkWin32SurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateWin32SurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateXcbSurfaceKHR(VkXcbSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateXcbSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateXlibSurfaceKHR(VkXlibSurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateXlibSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkSurfaceKHR> CreateDisplayPlaneSurfaceKHR(VkDisplaySurfaceCreateInfoKHR createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkSurfaceKHR.HandleType surfaceHandle; var result = Direct.CreateDisplayPlaneSurfaceKHR(Handle, pCreateInfo, pAllocator, &surfaceHandle); var instance = result == VkResult.Success ? new VkSurfaceKHR(this, surfaceHandle, allocator) : null; return new VkObjectResult<IVkSurfaceKHR>(result, instance); } } public VkObjectResult<IVkDebugReportCallbackEXT> CreateDebugReportCallbackEXT(VkDebugReportCallbackCreateInfoEXT createInfo, IVkAllocationCallbacks allocator) { var unmanagedSize = createInfo.SizeOfMarshalIndirect() + allocator.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pCreateInfo = createInfo.MarshalIndirect(ref unmanaged); var pAllocator = allocator.MarshalIndirect(ref unmanaged); VkDebugReportCallbackEXT.HandleType callbackHandle; var result = Direct.CreateDebugReportCallbackEXT(Handle, pCreateInfo, pAllocator, &callbackHandle); var instance = result == VkResult.Success ? new VkDebugReportCallbackEXT(this, callbackHandle, allocator) : null; return new VkObjectResult<IVkDebugReportCallbackEXT>(result, instance); } } public void DebugReportMessageEXT(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, ulong obj, IntPtr location, int messageCode, string layerPrefix, string message) { var unmanagedSize = layerPrefix.SizeOfMarshalIndirect() + message.SizeOfMarshalIndirect(); var unmanagedArray = new byte[unmanagedSize]; fixed (byte* unmanagedStart = unmanagedArray) { var unmanaged = unmanagedStart; var pLayerPrefix = layerPrefix.MarshalIndirect(ref unmanaged); var pMessage = message.MarshalIndirect(ref unmanaged); Direct.DebugReportMessageEXT(Handle, flags, objectType, obj, location, messageCode, pLayerPrefix, pMessage); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using Mercurial.Attributes; namespace Mercurial { /// <summary> /// This class implements the "hg incoming" command (<see href="http://www.selenic.com/mercurial/hg.1.html#incoming"/>): /// show new changesets found in source. /// </summary> public sealed class IncomingCommand : MercurialCommandBase<IncomingCommand>, IMercurialCommand<IEnumerable<Changeset>> { /// <summary> /// This is the backing field for the <see cref="Branches"/> property. /// </summary> private readonly List<string> _Branches = new List<string>(); /// <summary> /// This is the backing field for the <see cref="Revisions"/> property. /// </summary> private readonly List<RevSpec> _Revisions = new List<RevSpec>(); /// <summary> /// This is the backing field for the <see cref="BundleFileName"/> property. /// </summary> private string _BundleFileName = string.Empty; /// <summary> /// This is the backing field for the <see cref="Source"/> property. /// </summary> private string _Source = string.Empty; /// <summary> /// This is the backing field for the <see cref="SshCommand"/> property. /// </summary> private string _SshCommand = string.Empty; /// <summary> /// This is the backing field for the <see cref="RemoteCommand"/> property. /// </summary> private string _RemoteCommand = string.Empty; /// <summary> /// This is the backing field for the <see cref="VerifyServerCertificate"/> property. /// </summary> private bool _VerifyServerCertificate = true; /// <summary> /// This is the backing field for the <see cref="RecurseSubRepositories"/> property. /// </summary> private bool _RecurseSubRepositories; /// <summary> /// Initializes a new instance of the <see cref="IncomingCommand"/> class. /// </summary> public IncomingCommand() : base("incoming") { } /// <summary> /// Gets or sets a value indicating whether to verify the server certificate. If set to <c>false</c>, will ignore web.cacerts configuration. /// Default value is <c>true</c>. /// </summary> [BooleanArgument(FalseOption = "--insecure")] [DefaultValue(true)] public bool VerifyServerCertificate { get { return _VerifyServerCertificate; } set { RequiresVersion(new Version(1, 7, 5), "VerifyServerCertificate property of the IncomingCommand class"); _VerifyServerCertificate = value; } } /// <summary> /// Sets the <see cref="VerifyServerCertificate"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="VerifyServerCertificate"/> property. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithVerifyServerCertificate(bool value) { VerifyServerCertificate = value; return this; } /// <summary> /// Gets or sets the source to get new changesets from. If <see cref="string.Empty"/>, get them from the /// default source. Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument] [DefaultValue("")] public string Source { get { return _Source; } set { _Source = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets a value indicating whether to force execution even if the /// source repository is unrelated. /// </summary> [BooleanArgument(TrueOption = "--force")] [DefaultValue(false)] public bool Force { get; set; } /// <summary> /// Gets the collection of branches to include in the changesets. If empty, include all branches. /// Default is empty. /// </summary> [RepeatableArgument(Option = "--branch")] public Collection<string> Branches { get { return new Collection<string>(_Branches); } } /// <summary> /// Gets the collection of revisions to include from the <see cref="Source"/>. /// If empty, include all changes. Default is empty. /// </summary> [RepeatableArgument(Option = "--rev")] public Collection<RevSpec> Revisions { get { return new Collection<RevSpec>(_Revisions); } } /// <summary> /// Gets or sets a value indicating whether to recurse into subrepositories. /// Default is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--subrepos")] [DefaultValue(false)] public bool RecurseSubRepositories { get { return _RecurseSubRepositories; } set { RequiresVersion(new Version(1, 7), "RecurseSubRepositories property of the IncomingCommand class"); _RecurseSubRepositories = value; } } /// <summary> /// Gets or sets the full path to and name of the file to store the bundles into. If you intend to pull from the same source with /// the same parameters after executing "incoming", you should store the bundle locally to avoid the network download twice. /// </summary> [NullableArgument(NonNullOption = "--bundle")] [DefaultValue("")] public string BundleFileName { get { return _BundleFileName; } set { _BundleFileName = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the ssh command to use when cloning. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--ssh")] [DefaultValue("")] public string SshCommand { get { return _SshCommand; } set { _SshCommand = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the hg command to run on the remote side. /// Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--remotecmd")] [DefaultValue("")] public string RemoteCommand { get { return _RemoteCommand; } set { _RemoteCommand = (value ?? string.Empty).Trim(); } } #region IMercurialCommand<IEnumerable<Changeset>> Members /// <summary> /// Gets all the arguments to the <see cref="CommandBase{T}.Command"/>, or an /// empty array if there are none. /// </summary> /// <value></value> public override IEnumerable<string> Arguments { get { var arguments = new[] { "--style=xml", "--quiet" }; return arguments.Concat(base.Arguments).ToArray(); } } /// <summary> /// Gets the result of executing the command as a collection of <see cref="Changeset"/> objects. /// </summary> public IEnumerable<Changeset> Result { get; private set; } #endregion /// <summary> /// Sets the <see cref="Force"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Force"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithForce(bool value = true) { Force = value; return this; } /// <summary> /// Sets the <see cref="BundleFileName"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="BundleFileName"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithBundleFileName(string value) { BundleFileName = value; return this; } /// <summary> /// Sets the <see cref="SshCommand"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="SshCommand"/> property. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithSshCommand(string value) { SshCommand = value; return this; } /// <summary> /// Sets the <see cref="RemoteCommand"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="RemoteCommand"/> property. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithRemoteCommand(string value) { RemoteCommand = value; return this; } /// <summary> /// Adds the value to the <see cref="Branches"/> collection property and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="Branches"/> collection property. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithBranch(string value) { Branches.Add(value); return this; } /// <summary> /// Adds the value to the <see cref="Revisions"/> collection property and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="Revisions"/> collection property. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithRevision(RevSpec value) { Revisions.Add(value); return this; } /// <summary> /// Sets the <see cref="RecurseSubRepositories"/> property to the specified value and /// returns this <see cref="IncomingCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="RecurseSubRepositories"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="IncomingCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public IncomingCommand WithRecurseSubRepositories(bool value) { RecurseSubRepositories = value; return this; } /// <summary> /// This method should parse and store the appropriate execution result output /// according to the type of data the command line client would return for /// the command. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardOutput"> /// The standard output from executing the command line client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> protected override void ParseStandardOutputForResults(int exitCode, string standardOutput) { Result = ChangesetXmlParser.Parse(standardOutput); } /// <summary> /// This method should throw the appropriate exception depending on the contents of /// the <paramref name="exitCode"/> and <paramref name="standardErrorOutput"/> /// parameters, or simply return if the execution is considered successful. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardErrorOutput"> /// The standard error output from executing the command client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. The default behavior is to throw a <see cref="MercurialExecutionException"/> /// if <paramref name="exitCode"/> is not zero. If you require different behavior, don't call the base /// method. /// </remarks> protected override void ThrowOnUnsuccessfulExecution(int exitCode, string standardErrorOutput) { switch (exitCode) { case 0: case 1: break; default: base.ThrowOnUnsuccessfulExecution(exitCode, standardErrorOutput); break; } } /// <summary> /// Validates the command configuration. This method should throw the necessary /// exceptions to signal missing or incorrect configuration (like attempting to /// add files to the repository without specifying which files to add.) /// </summary> /// <exception cref="InvalidOperationException"> /// <para>The <see cref="VerifyServerCertificate"/> command was used with Mercurial 1.7.4 or older.</para> /// </exception> public override void Validate() { base.Validate(); if (!VerifyServerCertificate && ClientExecutable.CurrentVersion < new Version(1, 7, 5)) throw new InvalidOperationException("The 'VerifyServerCertificate' property is only available in Mercurial 1.7.5 and newer"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Reflection; using System.Globalization; using System.Runtime.Versioning; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace System { [Serializable] // Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of. internal class UnitySerializationHolder : ISerializable, IObjectReference { #region Internal Constants internal const int EmptyUnity = 0x0001; internal const int NullUnity = 0x0002; internal const int MissingUnity = 0x0003; internal const int RuntimeTypeUnity = 0x0004; internal const int ModuleUnity = 0x0005; internal const int AssemblyUnity = 0x0006; internal const int GenericParameterTypeUnity = 0x0007; internal const int PartialInstantiationTypeUnity = 0x0008; internal const int Pointer = 0x0001; internal const int Array = 0x0002; internal const int SzArray = 0x0003; internal const int ByRef = 0x0004; #endregion #region Internal Static Members internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing) { info.SetType(typeof(UnitySerializationHolder)); info.AddValue("UnityType", MissingUnity); } internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type) { List<int> elementTypes = new List<int>(); while(type.HasElementType) { if (type.IsSzArray) { elementTypes.Add(SzArray); } else if (type.IsArray) { elementTypes.Add(type.GetArrayRank()); elementTypes.Add(Array); } else if (type.IsPointer) { elementTypes.Add(Pointer); } else if (type.IsByRef) { elementTypes.Add(ByRef); } type = (RuntimeType)type.GetElementType(); } info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[])); return type; } internal Type MakeElementTypes(Type type) { for (int i = m_elementTypes.Length - 1; i >= 0; i --) { if (m_elementTypes[i] == SzArray) { type = type.MakeArrayType(); } else if (m_elementTypes[i] == Array) { type = type.MakeArrayType(m_elementTypes[--i]); } else if ((m_elementTypes[i] == Pointer)) { type = type.MakePointerType(); } else if ((m_elementTypes[i] == ByRef)) { type = type.MakeByRefType(); } } return type; } internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type) { if (type.GetRootElementType().IsGenericParameter) { type = AddElementTypes(info, type); info.SetType(typeof(UnitySerializationHolder)); info.AddValue("UnityType", GenericParameterTypeUnity); info.AddValue("GenericParameterPosition", type.GenericParameterPosition); info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase)); info.AddValue("DeclaringType", type.DeclaringType, typeof(Type)); return; } int unityType = RuntimeTypeUnity; if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters) { // Partial instantiation unityType = PartialInstantiationTypeUnity; type = AddElementTypes(info, type); info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[])); type = (RuntimeType)type.GetGenericTypeDefinition(); } GetUnitySerializationInfo(info, unityType, type.FullName, type.GetRuntimeAssembly()); } internal static void GetUnitySerializationInfo( SerializationInfo info, int unityType, String data, RuntimeAssembly assembly) { // A helper method that returns the SerializationInfo that a class utilizing // UnitySerializationHelper should return from a call to GetObjectData. It contains // the unityType (defined above) and any optional data (used only for the reflection // types.) info.SetType(typeof(UnitySerializationHolder)); info.AddValue("Data", data, typeof(String)); info.AddValue("UnityType", unityType); String assemName; if (assembly == null) { assemName = String.Empty; } else { assemName = assembly.FullName; } info.AddValue("AssemblyName", assemName); } #endregion #region Private Data Members private Type[] m_instantiation; private int[] m_elementTypes; private int m_genericParameterPosition; private Type m_declaringType; private MethodBase m_declaringMethod; private String m_data; private String m_assemblyName; private int m_unityType; #endregion #region Constructor internal UnitySerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); m_unityType = info.GetInt32("UnityType"); if (m_unityType == MissingUnity) return; if (m_unityType == GenericParameterTypeUnity) { m_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase; m_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type; m_genericParameterPosition = info.GetInt32("GenericParameterPosition"); m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[]; return; } if (m_unityType == PartialInstantiationTypeUnity) { m_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[]; m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[]; } m_data = info.GetString("Data"); m_assemblyName = info.GetString("AssemblyName"); } #endregion #region Private Methods private void ThrowInsufficientInformation(string field) { throw new SerializationException( Environment.GetResourceString("Serialization_InsufficientDeserializationState", field)); } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder")); } #endregion #region IObjectReference [System.Security.SecurityCritical] // auto-generated public virtual Object GetRealObject(StreamingContext context) { // GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct // object to return. We have specific code here to handle the different types which we support. // The reflection types (Assembly, Module, and Type) have to be looked up through their static // accessors by name. Assembly assembly; switch (m_unityType) { case EmptyUnity: { return Empty.Value; } case NullUnity: { return DBNull.Value; } case MissingUnity: { return Missing.Value; } case PartialInstantiationTypeUnity: { m_unityType = RuntimeTypeUnity; Type definition = GetRealObject(context) as Type; m_unityType = PartialInstantiationTypeUnity; if (m_instantiation[0] == null) return null; return MakeElementTypes(definition.MakeGenericType(m_instantiation)); } case GenericParameterTypeUnity: { if (m_declaringMethod == null && m_declaringType == null) ThrowInsufficientInformation("DeclaringMember"); if (m_declaringMethod != null) return m_declaringMethod.GetGenericArguments()[m_genericParameterPosition]; return MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]); } case RuntimeTypeUnity: { if (m_data == null || m_data.Length == 0) ThrowInsufficientInformation("Data"); if (m_assemblyName == null) ThrowInsufficientInformation("AssemblyName"); if (m_assemblyName.Length == 0) return Type.GetType(m_data, true, false); assembly = Assembly.Load(m_assemblyName); Type t = assembly.GetType(m_data, true, false); return t; } case ModuleUnity: { if (m_data == null || m_data.Length == 0) ThrowInsufficientInformation("Data"); if (m_assemblyName == null) ThrowInsufficientInformation("AssemblyName"); assembly = Assembly.Load(m_assemblyName); Module namedModule = assembly.GetModule(m_data); if (namedModule == null) throw new SerializationException( Environment.GetResourceString("Serialization_UnableToFindModule", m_data, m_assemblyName)); return namedModule; } case AssemblyUnity: { if (m_data == null || m_data.Length == 0) ThrowInsufficientInformation("Data"); if (m_assemblyName == null) ThrowInsufficientInformation("AssemblyName"); assembly = Assembly.Load(m_assemblyName); return assembly; } default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity")); } } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Dmg { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using DiscUtils.Compression; internal class UdifBuffer : DiscUtils.Buffer { private Stream _stream; private ResourceFork _resources; private long _sectorCount; private List<CompressedBlock> _blocks; private byte[] _decompBuffer; private CompressedRun _activeRun; private long _activeRunOffset; public UdifBuffer(Stream stream, ResourceFork resources, long sectorCount) { _stream = stream; _resources = resources; _sectorCount = sectorCount; _blocks = new List<CompressedBlock>(); foreach (var resource in _resources.GetAllResources("blkx")) { _blocks.Add(((BlkxResource)resource).Block); } } public List<CompressedBlock> Blocks { get { return this._blocks; } } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override long Capacity { get { return _sectorCount * Sizes.Sector; } } public override int Read(long pos, byte[] buffer, int offset, int count) { int totalCopied = 0; long currentPos = pos; while (totalCopied < count && currentPos < Capacity) { LoadRun(currentPos); int bufferOffset = (int)(currentPos - (_activeRunOffset + (_activeRun.SectorStart * Sizes.Sector))); int toCopy = (int)Math.Min((_activeRun.SectorCount * Sizes.Sector) - bufferOffset, count - totalCopied); switch (_activeRun.Type) { case RunType.Zeros: Array.Clear(buffer, offset + totalCopied, toCopy); break; case RunType.Raw: _stream.Position = _activeRun.CompOffset + bufferOffset; Utilities.ReadFully(_stream, buffer, offset + totalCopied, toCopy); break; case RunType.AdcCompressed: case RunType.ZlibCompressed: case RunType.BZlibCompressed: Array.Copy(_decompBuffer, bufferOffset, buffer, offset + totalCopied, toCopy); break; default: throw new NotImplementedException("Reading from run of type " + _activeRun.Type); } currentPos += toCopy; totalCopied += toCopy; } return totalCopied; } public override void Write(long pos, byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void SetCapacity(long value) { throw new NotSupportedException(); } public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { StreamExtent lastRun = null; foreach (var block in _blocks) { if ((block.FirstSector + block.SectorCount) * Sizes.Sector < start) { // Skip blocks before start of range continue; } if (block.FirstSector * Sizes.Sector > start + count) { // Skip blocks after end of range continue; } foreach (var run in block.Runs) { if (run.SectorCount > 0 && run.Type != RunType.Zeros) { long thisRunStart = (block.FirstSector + run.SectorStart) * Sizes.Sector; long thisRunEnd = thisRunStart + (run.SectorCount * Sizes.Sector); thisRunStart = Math.Max(thisRunStart, start); thisRunEnd = Math.Min(thisRunEnd, start + count); long thisRunLength = thisRunEnd - thisRunStart; if (thisRunLength > 0) { if (lastRun != null && lastRun.Start + lastRun.Length == thisRunStart) { lastRun = new StreamExtent(lastRun.Start, lastRun.Length + thisRunLength); } else { if (lastRun != null) { yield return lastRun; } lastRun = new StreamExtent(thisRunStart, thisRunLength); } } } } } if (lastRun != null) { yield return lastRun; } } private static int ADCDecompress(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { int consumed = 0; int written = 0; while (consumed < inputCount) { byte focusByte = inputBuffer[inputOffset + consumed]; if ((focusByte & 0x80) != 0) { // Data Run int chunkSize = (focusByte & 0x7F) + 1; Array.Copy(inputBuffer, inputOffset + consumed + 1, outputBuffer, outputOffset + written, chunkSize); consumed += chunkSize + 1; written += chunkSize; } else if ((focusByte & 0x40) != 0) { // 3 byte code int chunkSize = (focusByte & 0x3F) + 4; int offset = Utilities.ToUInt16BigEndian(inputBuffer, inputOffset + consumed + 1); for (int i = 0; i < chunkSize; ++i) { outputBuffer[outputOffset + written + i] = outputBuffer[(outputOffset + written + i - offset) - 1]; } consumed += 3; written += chunkSize; } else { // 2 byte code int chunkSize = ((focusByte & 0x3F) >> 2) + 3; int offset = ((focusByte & 0x3) << 8) + (inputBuffer[inputOffset + consumed + 1] & 0xFF); for (int i = 0; i < chunkSize; ++i) { outputBuffer[outputOffset + written + i] = outputBuffer[(outputOffset + written + i - offset) - 1]; } consumed += 2; written += chunkSize; } } return written; } private void LoadRun(long pos) { if (_activeRun != null && pos >= _activeRunOffset + (_activeRun.SectorStart * Sizes.Sector) && pos < _activeRunOffset + ((_activeRun.SectorStart + _activeRun.SectorCount) * Sizes.Sector)) { return; } long findSector = pos / 512; foreach (var block in _blocks) { if (block.FirstSector <= findSector && (block.FirstSector + block.SectorCount) > findSector) { // Make sure the decompression buffer is big enough if (_decompBuffer == null || _decompBuffer.Length < block.DecompressBufferRequested * Sizes.Sector) { _decompBuffer = new byte[block.DecompressBufferRequested * Sizes.Sector]; } foreach (var run in block.Runs) { if ((block.FirstSector + run.SectorStart) <= findSector && ((block.FirstSector + run.SectorStart) + run.SectorCount) > findSector) { LoadRun(run); _activeRunOffset = block.FirstSector * Sizes.Sector; return; } } throw new IOException("No run for sector " + findSector + " in block starting at " + block.FirstSector); } } throw new IOException("No block for sector " + findSector); } private void LoadRun(CompressedRun run) { int toCopy = (int)(run.SectorCount * Sizes.Sector); switch (run.Type) { case RunType.ZlibCompressed: _stream.Position = run.CompOffset + 2; // 2 byte zlib header using (DeflateStream ds = new DeflateStream(_stream, CompressionMode.Decompress, true)) { Utilities.ReadFully(ds, _decompBuffer, 0, toCopy); } break; case RunType.AdcCompressed: _stream.Position = run.CompOffset; byte[] compressed = Utilities.ReadFully(_stream, (int)run.CompLength); if (ADCDecompress(compressed, 0, compressed.Length, _decompBuffer, 0) != toCopy) { throw new InvalidDataException("Run too short when decompressed"); } break; case RunType.BZlibCompressed: using (BZip2DecoderStream ds = new BZip2DecoderStream(new SubStream(_stream, run.CompOffset, run.CompLength), Ownership.None)) { Utilities.ReadFully(ds, _decompBuffer, 0, toCopy); } break; case RunType.Zeros: case RunType.Raw: break; default: throw new NotImplementedException("Unrecognized run type " + run.Type); } _activeRun = run; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainController.cs" company="None"> // None // </copyright> // <summary> // Defines the MainController type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace TfsWorkbench.ProjectSetupUI { using System; using System.Threading; using System.Windows.Input; using System.Windows.Threading; using Core.EventArgObjects; using Core.Interfaces; using DataObjects; using Helpers; using Properties; using TfsWorkbench.Core.Services; using UIElements; /// <summary> /// Initializes instance of MainController /// </summary> internal class MainController { /// <summary> /// The project setup control. /// </summary> private readonly DisplayMode displayMode; /// <summary> /// The project data service. /// </summary> private readonly IProjectDataService projectDataService; /// <summary> /// The cloase dialog callback. /// </summary> private SendOrPostCallback closeDialogCallBack; /// <summary> /// The refresh all callback. /// </summary> private SendOrPostCallback refreshAllCallBack; /// <summary> /// Initializes a new instance of the <see cref="MainController"/> class. /// </summary> /// <param name="displayMode">The project setup control.</param> public MainController(DisplayMode displayMode) : this(displayMode, ServiceManager.Instance.GetService<IProjectDataService>()) { } /// <summary> /// Initializes a new instance of the <see cref="MainController"/> class. /// </summary> /// <param name="displayMode">The project setup control.</param> /// <param name="projectDataService">The project data service.</param> public MainController(DisplayMode displayMode, IProjectDataService projectDataService) { if (projectDataService == null) { throw new ArgumentNullException("projectDataService"); } this.displayMode = displayMode; this.projectDataService = projectDataService; this.SetupCommandBindings(); this.projectDataService.ProjectDataChanged += this.OnProjectDataChanged; } /// <summary> /// Shows the advanced setup dialog. /// </summary> /// <typeparam name="T">The setup dialog type.</typeparam> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param> private void ShowSetupDialog<T>(object sender, ExecutedRoutedEventArgs e) where T : SetupDialogBase, new() { IDataProvider dataProvider; IProjectData projectData; if (!this.TryGetGlobalElelements(out dataProvider, out projectData)) { return; } var projectSetup = new ProjectSetup(projectData.ProjectName) { ProjectNode = projectData.ProjectNodes[Core.Properties.Settings.Default.IterationPathFieldName], StartDate = DateTime.Now.Date, EndDate = DateTime.Now.Date.AddDays(6 * Settings.Default.DefaultWorkStreamCadance) }; projectSetup = SetupControllerHelper.AddRelease(projectSetup); projectSetup = SetupControllerHelper.AddWorkStream(projectSetup); projectSetup = SetupControllerHelper.AddTeam(projectSetup); var setupDialog = new T { ProjectSetup = projectSetup }; setupDialog.ApplySetup += this.OnApplySetup; CommandLibrary.ShowDialogCommand.Execute(setupDialog, this.displayMode); } /// <summary> /// Determines whether this instance [can execute setup] the specified sender. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Windows.Input.CanExecuteRoutedEventArgs"/> instance containing the event data.</param> private void CanExecuteSetup(object sender, CanExecuteRoutedEventArgs e) { var projectData = this.projectDataService.CurrentProjectData; e.CanExecute = SetupControllerHelper.IsValidScrumProject(projectData) && SetupControllerHelper.HasRootPathLoaded(projectData); } /// <summary> /// Sets up the command bindings. /// </summary> private void SetupCommandBindings() { this.displayMode.CommandBindings.Add( new CommandBinding( LocalCommandLibrary.ShowAdvancedSetupCommand, this.ShowSetupDialog<AdvancedSetupControl>, this.CanExecuteSetup)); this.displayMode.CommandBindings.Add( new CommandBinding( LocalCommandLibrary.ShowQuickSetupCommand, this.ShowSetupDialog<QuickStartControl>, this.CanExecuteSetup)); } /// <summary> /// Tries the get global elelements. /// </summary> /// <param name="dataProvider">The data provider.</param> /// <param name="projectData">The project data.</param> /// <returns><c>True</c> if the elements are populated; otherwise <c>false</c>.l</returns> private bool TryGetGlobalElelements(out IDataProvider dataProvider, out IProjectData projectData) { dataProvider = null; projectData = null; if (this.displayMode == null) { return false; } projectData = this.projectDataService.CurrentProjectData; dataProvider = this.projectDataService.CurrentDataProvider; return projectData != null && dataProvider != null; } /// <summary> /// Called when [project data changed]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="TfsWorkbench.Core.EventArgObjects.ProjectDataChangedEventArgs"/> instance containing the event data.</param> private void OnProjectDataChanged(object sender, ProjectDataChangedEventArgs e) { this.displayMode.ProjectVisualiser.ProjectData = e.NewValue; this.refreshAllCallBack = delegate { }; this.closeDialogCallBack = delegate { }; } /// <summary> /// Called when [apply advanced setup]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void OnApplySetup(object sender, ProjectSetupEventArgs e) { IDataProvider dataProvider; IProjectData projectData; if (!this.TryGetGlobalElelements(out dataProvider, out projectData)) { CommandLibrary.ApplicationExceptionCommand.Execute( new Exception("Apply setup method has failed. Unable to find global elements"), this.displayMode); return; } var setupDialog = sender as SetupDialogBase; if (setupDialog == null) { return; } var projectSetup = e.ProjectSetup; // Build the new work item structure var releases = SetupControllerHelper.CreateProjectStructure(projectSetup); try { // Commit the new paths to the data store. // This invalidates any loaded work items that reference altered paths. dataProvider.SaveProjectNodes(projectData); } catch (Exception ex) { if (CommandLibrary.ApplicationExceptionCommand.CanExecute(ex, this.displayMode)) { CommandLibrary.ApplicationExceptionCommand.Execute(ex, this.displayMode); setupDialog.IsEnabled = true; return; } throw; } // Clear the existing work item data SetupControllerHelper.ClearExistingItems(projectData); this.refreshAllCallBack = delegate { dataProvider.BeginRefreshAllProjectData(projectData); }; this.closeDialogCallBack = delegate { SetupControllerHelper.AddNewStructureItems(releases, dataProvider, projectData); foreach (var viewMap in projectData.ViewMaps) { viewMap.OnLayoutUpdated(); } this.displayMode.ProjectVisualiser.ProjectData = null; this.displayMode.ProjectVisualiser.ProjectData = projectData; dataProvider.ElementDataLoadError -= this.OnDataLoadError; dataProvider.ElementSaveComplete -= this.OnSaveComplete; dataProvider.ElementDataLoaded -= this.OnDataLoaded; dataProvider.ElementSaveError -= this.OnSaveError; setupDialog.ApplySetup -= this.OnApplySetup; CommandLibrary.CloseDialogCommand.Execute(setupDialog, setupDialog); }; dataProvider.ElementDataLoadError += this.OnDataLoadError; dataProvider.ElementSaveComplete += this.OnSaveComplete; dataProvider.ElementDataLoaded += this.OnDataLoaded; dataProvider.ElementSaveError += this.OnSaveError; // Begin the async save process dataProvider.BeginSaveProjectData(projectData); } /// <summary> /// Called when [save error]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="WorkbenchItemSaveFailedEventArgs"/> instance containing the event data.</param> private void OnSaveError(object sender, WorkbenchItemSaveFailedEventArgs e) { this.DispatchMethod(this.closeDialogCallBack); } /// <summary> /// Called when [data loaded]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="ProjectDataEventArgs"/> instance containing the event data.</param> private void OnDataLoaded(object sender, EventArgs e) { this.DispatchMethod(this.closeDialogCallBack); } /// <summary> /// Called when [save complete]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void OnSaveComplete(object sender, EventArgs e) { this.DispatchMethod(this.refreshAllCallBack); } /// <summary> /// Called when [data load error]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="ExceptionEventArgs"/> instance containing the event data.</param> private void OnDataLoadError(object sender, ExceptionEventArgs e) { this.DispatchMethod(this.closeDialogCallBack); } /// <summary> /// Dispatches the method. /// </summary> /// <param name="callback">The callback.</param> private void DispatchMethod(SendOrPostCallback callback) { this.displayMode.Dispatcher.BeginInvoke(DispatcherPriority.Background, callback, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Data.Common; using System.Drawing; using System.Globalization; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OpenQA.Selenium; using Wasm.Authentication.Server; using Wasm.Authentication.Server.Data; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Components.E2ETest.Tests { public class WebAssemblyAuthenticationTests : ServerTestBase<AspNetSiteServerFixture> { private static readonly SqliteConnection _connection; // We create a conection here and open it as the in memory Db will delete the database // as soon as there are no open connections to it. static WebAssemblyAuthenticationTests() { _connection = new SqliteConnection($"DataSource=:memory:"); _connection.Open(); } public WebAssemblyAuthenticationTests( BrowserFixture browserFixture, AspNetSiteServerFixture serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { _serverFixture.ApplicationAssembly = typeof(Program).Assembly; _serverFixture.AdditionalArguments.Clear(); _serverFixture.BuildWebHostMethod = args => Program.CreateHostBuilder(args) .ConfigureServices(services => SetupTestDatabase<ApplicationDbContext>(services, _connection)) .Build(); } public override Task InitializeAsync() => base.InitializeAsync(Guid.NewGuid().ToString()); protected override void InitializeAsyncCore() { Navigate("/", noReload: true); Browser.Manage().Window.Size = new Size(1024, 800); EnsureDatabaseCreated(_serverFixture.Host.Services); WaitUntilLoaded(); } [Fact] public void WasmAuthentication_Loads() { Browser.Equal("Wasm.Authentication.Client", () => Browser.Title); } [Fact] public void AnonymousUser_GetsRedirectedToLogin_AndBackToOriginalProtectedResource() { var link = By.PartialLinkText("Fetch data"); var page = "/Identity/Account/Login"; ClickAndNavigate(link, page); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; FirstTimeRegister(userName, password); ValidateFetchData(); } [Fact] public void CanPreserveApplicationState_DuringLogIn() { var originalAppState = Browser.Exists(By.Id("app-state")).Text; var link = By.PartialLinkText("Fetch data"); var page = "/Identity/Account/Login"; ClickAndNavigate(link, page); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; FirstTimeRegister(userName, password); ValidateFetchData(); var homeLink = By.PartialLinkText("Home"); var homePage = "/"; ClickAndNavigate(homeLink, homePage); var restoredAppState = Browser.Exists(By.Id("app-state")).Text; Assert.Equal(originalAppState, restoredAppState); } [Fact] public void CanShareUserRolesBetweenClientAndServer() { ClickAndNavigate(By.PartialLinkText("Log in"), "/Identity/Account/Login"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; FirstTimeRegister(userName, password); ClickAndNavigate(By.PartialLinkText("Make admin"), "/new-admin"); ClickAndNavigate(By.PartialLinkText("Settings"), "/admin-settings"); Browser.Exists(By.Id("admin-action")).Click(); Browser.Exists(By.Id("admin-success")); } private void ClickAndNavigate(By link, string page) { Browser.Exists(link).Click(); Browser.Contains(page, () => Browser.Url); } [Fact] public void AnonymousUser_CanRegister_AndGetLoggedIn() { ClickAndNavigate(By.PartialLinkText("Register"), "/Identity/Account/Register"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; RegisterCore(userName, password); CompleteProfileDetails(); // Need to navigate to fetch page Browser.Exists(By.PartialLinkText("Fetch data")).Click(); // Can navigate to the 'fetch data' page ValidateFetchData(); } [Fact] public void AuthenticatedUser_ProfileIncludesDetails_And_AccessToken() { ClickAndNavigate(By.PartialLinkText("User"), "/Identity/Account/Login"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; FirstTimeRegister(userName, password); Browser.Contains("user", () => Browser.Url); Browser.Equal($"Welcome {userName}", () => Browser.Exists(By.TagName("h1")).Text); var claims = Browser.FindElements(By.CssSelector("p.claim")) .Select(e => { var pair = e.Text.Split(":"); return (pair[0].Trim(), pair[1].Trim()); }) .Where(c => !new[] { "s_hash", "auth_time", "sid", "sub" }.Contains(c.Item1)) .OrderBy(o => o.Item1) .ToArray(); Assert.Equal(5, claims.Length); Assert.Equal(new[] { ("amr", "pwd"), ("idp", "local"), ("name", userName), ("NewUser", "true"), ("preferred_username", userName) }, claims); var token = Browser.Exists(By.Id("access-token")).Text; Assert.NotNull(token); var payload = JsonSerializer.Deserialize<JwtPayload>(Base64UrlTextEncoder.Decode(token.Split(".")[1])); Assert.StartsWith("http://127.0.0.1", payload.Issuer); Assert.StartsWith("Wasm.Authentication.ServerAPI", payload.Audience); Assert.StartsWith("Wasm.Authentication.Client", payload.ClientId); Assert.Equal(new[] { "openid", "profile", "Wasm.Authentication.ServerAPI" }, payload.Scopes.OrderBy(id => id)); // The browser formats the text using the current language, so the following parsing relies on // the server being set to an equivalent culture. This should be true in our test scenarios. var currentTime = DateTimeOffset.Parse(Browser.Exists(By.Id("current-time")).Text, CultureInfo.CurrentCulture); var tokenExpiration = DateTimeOffset.Parse(Browser.Exists(By.Id("access-token-expires")).Text, CultureInfo.CurrentCulture); Assert.True(currentTime.AddMinutes(50) < tokenExpiration); Assert.True(currentTime.AddMinutes(60) >= tokenExpiration); } [Fact] public void AuthenticatedUser_CanGoToProfile() { ClickAndNavigate(By.PartialLinkText("Register"), "/Identity/Account/Register"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; RegisterCore(userName, password); CompleteProfileDetails(); ClickAndNavigate(By.PartialLinkText($"Hello, {userName}!"), "/Identity/Account/Manage"); Browser.Navigate().Back(); Browser.Equal("/", () => new Uri(Browser.Url).PathAndQuery); } [Fact] public void RegisterAndBack_DoesNotCause_RedirectLoop() { Browser.Exists(By.PartialLinkText("Register")).Click(); // We will be redirected to the identity UI Browser.Contains("/Identity/Account/Register", () => Browser.Url); Browser.Navigate().Back(); Browser.Equal("/", () => new Uri(Browser.Url).PathAndQuery); } [Fact] public void LoginAndBack_DoesNotCause_RedirectLoop() { Browser.Exists(By.PartialLinkText("Log in")).Click(); // We will be redirected to the identity UI Browser.Contains("/Identity/Account/Login", () => Browser.Url); Browser.Navigate().Back(); Browser.Equal("/", () => new Uri(Browser.Url).PathAndQuery); } [Fact] public void NewlyRegisteredUser_CanLogOut() { ClickAndNavigate(By.PartialLinkText("Register"), "/Identity/Account/Register"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; RegisterCore(userName, password); CompleteProfileDetails(); ValidateLogout(); } [Fact] public void AlreadyRegisteredUser_CanLogOut() { ClickAndNavigate(By.PartialLinkText("Register"), "/Identity/Account/Register"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; RegisterCore(userName, password); CompleteProfileDetails(); ValidateLogout(); Browser.Navigate().GoToUrl("data:"); Navigate("/"); WaitUntilLoaded(); ClickAndNavigate(By.PartialLinkText("Log in"), "/Identity/Account/Login"); // Now we can login LoginCore(userName, password); ValidateLoggedIn(userName); ValidateLogout(); } [Fact] public void LoggedInUser_OnTheIdP_CanLogInSilently() { ClickAndNavigate(By.PartialLinkText("Register"), "/Identity/Account/Register"); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; RegisterCore(userName, password); CompleteProfileDetails(); ValidateLoggedIn(userName); // Clear the existing storage on the page and refresh Browser.Exists(By.Id("test-clear-storage")).Click(); Browser.Exists(By.Id("test-refresh-page")).Click(); ValidateLoggedIn(userName); } [Fact] public void CanNotRedirect_To_External_ReturnUrl() { Browser.Navigate().GoToUrl(new Uri(new Uri(Browser.Url), "/authentication/login?returnUrl=https%3A%2F%2Fwww.bing.com").AbsoluteUri); WaitUntilLoaded(skipHeader: true); Browser.Exists(By.CssSelector("[style=\"display: block;\"]")); Assert.NotEmpty(Browser.GetBrowserLogs(LogLevel.Severe)); } [Fact] public async Task CanNotTrigger_Logout_WithNavigation() { Browser.Navigate().GoToUrl(new Uri(new Uri(Browser.Url), "/authentication/logout").AbsoluteUri); WaitUntilLoaded(skipHeader: true); Browser.Contains("/authentication/logout-failed", () => Browser.Url); await Task.Delay(3000); Browser.Contains("/authentication/logout-failed", () => Browser.Url); } private void ValidateLoggedIn(string userName) { Browser.Exists(By.CssSelector("button.nav-link.btn.btn-link")); Browser.Exists(By.PartialLinkText($"Hello, {userName}!")); } private void LoginCore(string userName, string password) { Browser.Exists(By.PartialLinkText("Login")).Click(); Browser.Exists(By.Name("Input.Email")); Browser.Exists(By.Name("Input.Email")).SendKeys(userName); Browser.Exists(By.Name("Input.Password")).SendKeys(password); Browser.Exists(By.Id("login-submit")).Click(); } private void ValidateLogout() { Browser.Exists(By.CssSelector("button.nav-link.btn.btn-link")); // Click logout button Browser.Exists(By.CssSelector("button.nav-link.btn.btn-link")).Click(); Browser.Contains("/authentication/logged-out", () => Browser.Url); Browser.True(() => Browser.FindElements(By.TagName("p")).Any(e => e.Text == "You are logged out.")); } private void ValidateFetchData() { // Can navigate to the 'fetch data' page Browser.Contains("fetchdata", () => Browser.Url); Browser.Equal("Weather forecast", () => Browser.Exists(By.TagName("h1")).Text); // Asynchronously loads and displays the table of weather forecasts Browser.Exists(By.CssSelector("table>tbody>tr")); Browser.Equal(5, () => Browser.FindElements(By.CssSelector("p+table>tbody>tr")).Count); } private void FirstTimeRegister(string userName, string password) { Browser.Exists(By.PartialLinkText("Register as a new user")).Click(); RegisterCore(userName, password); CompleteProfileDetails(); } private void CompleteProfileDetails() { Browser.Exists(By.PartialLinkText("Home")); Browser.Contains("/preferences", () => Browser.Url); Browser.Exists(By.Id("color-preference")).SendKeys("Red"); Browser.Exists(By.Id("submit-preference")).Click(); } private void RegisterCore(string userName, string password) { Browser.Exists(By.Name("Input.Email")); Browser.Exists(By.Name("Input.Email")).SendKeys(userName); Browser.Exists(By.Name("Input.Password")).SendKeys(password); Browser.Exists(By.Name("Input.ConfirmPassword")).SendKeys(password); Browser.Click(By.Id("registerSubmit")); // We will be redirected to the RegisterConfirmation Browser.Contains("/Identity/Account/RegisterConfirmation", () => Browser.Url); try { // For some reason the test sometimes get stuck here. Given that this is not something we are testing, to avoid // this we'll retry once to minify the chances it happens on CI runs. ClickAndNavigate(By.PartialLinkText("Click here to confirm your account"), "/Identity/Account/ConfirmEmail"); } catch { ClickAndNavigate(By.PartialLinkText("Click here to confirm your account"), "/Identity/Account/ConfirmEmail"); } // Now we can login Browser.Exists(By.PartialLinkText("Login")).Click(); Browser.Exists(By.Name("Input.Email")); Browser.Exists(By.Name("Input.Email")).SendKeys(userName); Browser.Exists(By.Name("Input.Password")).SendKeys(password); Browser.Exists(By.Id("login-submit")).Click(); } private void WaitUntilLoaded(bool skipHeader = false) { Browser.Exists(By.TagName("app")); Browser.True(() => Browser.Exists(By.TagName("app")).Text != "Loading..."); if (!skipHeader) { // All pages in the text contain an h1 element. This helps us wait until the router has intercepted links as that // happens before rendering the underlying page. Browser.Exists(By.TagName("h1")); } } public static IServiceCollection SetupTestDatabase<TContext>(IServiceCollection services, DbConnection connection) where TContext : DbContext { var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<TContext>)); if (descriptor != null) { services.Remove(descriptor); } services.AddScoped(p => DbContextOptionsFactory<TContext>( p, (sp, options) => options .ConfigureWarnings(b => b.Log(CoreEventId.ManyServiceProvidersCreatedWarning)) .UseSqlite(connection))); return services; } private static DbContextOptions<TContext> DbContextOptionsFactory<TContext>( IServiceProvider applicationServiceProvider, Action<IServiceProvider, DbContextOptionsBuilder> optionsAction) where TContext : DbContext { var builder = new DbContextOptionsBuilder<TContext>( new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>())); builder.UseApplicationServiceProvider(applicationServiceProvider); optionsAction?.Invoke(applicationServiceProvider, builder); return builder.Options; } private void EnsureDatabaseCreated(IServiceProvider services) { using var scope = services.CreateScope(); var applicationDbContext = scope.ServiceProvider.GetService<ApplicationDbContext>(); if (applicationDbContext?.Database?.GetPendingMigrations()?.Any() == true) { applicationDbContext?.Database?.Migrate(); } } private class JwtPayload { [JsonPropertyName("iss")] public string Issuer { get; set; } [JsonPropertyName("aud")] public string Audience { get; set; } [JsonPropertyName("client_id")] public string ClientId { get; set; } [JsonPropertyName("sub")] public string Subject { get; set; } [JsonPropertyName("idp")] public string IdentityProvider { get; set; } [JsonPropertyName("scope")] public string[] Scopes { get; set; } } } }
/** * @brief Same throttleing mechanism as the baseline global_round_robin scheme. However * this controller puts high apps into a cluster with batching. The number of clusters is * no longer static. Each cluster is batched with an average MPKI value. Therefore the number * of clusters depends on the number of high apps and their average MPKI value. * * TODO: can go into throttle mode with only 2 nodes, and none of them has high enough MPKI to throttle. * * Trigger metric: netutil. * High app metric: MPKI. * Batch metric: MPKI. **/ //#define DEBUG_NETUTIL //#define DEBUG //#define DEBUG_CLUSTER //#define DEBUG_CLUSTER2 //#define DEBUG_CLUSTER_RATE using System; using System.Collections.Generic; namespace ICSimulator { public class Controller_Global_Batch: Controller_Global_round_robin { public static double lastNetUtil; //a pool of clusters for throttle mode public static BatchClusterPool cluster_pool; public Controller_Global_Batch() { isThrottling = false; for (int i = 0; i < Config.N; i++) { MPKI[i]=0.0; num_ins_last_epoch[i]=0; m_isThrottled[i]=false; L1misses[i]=0; lastNetUtil = 0; } cluster_pool=new BatchClusterPool(Config.cluster_MPKI_threshold); } public override void doThrottling() { //Unthrottle all nodes b/c could have nodes being throttled //in last sample period, but not supposed to be throttle in //this period. for(int i=0;i<Config.N;i++) { setThrottleRate(i,false); m_nodeStates[i] = NodeState.Low; } //Throttle all the high nodes int [] high_nodes=cluster_pool.allNodes(); foreach (int node in high_nodes) { setThrottleRate(node,true); m_nodeStates[node] = NodeState.HighOther; } #if DEBUG_CLUSTER2 Console.Write("\nLow nodes *NOT* throttled: "); for(int i=0;i<Config.N;i++) if(!m_isThrottled[i]) Console.Write("{0} ",i); #endif //Unthrottle all the nodes in the cluster int [] nodes=cluster_pool.nodesInNextCluster(); #if DEBUG_CLUSTER2 Console.Write("\nUnthrottling cluster nodes: "); #endif if(nodes.Length>0) { foreach (int node in nodes) { setThrottleRate(node,false); m_nodeStates[node] = NodeState.HighGolden; Simulator.stats.throttle_time_bysrc[node].Add(); #if DEBUG_CLUSTER2 Console.Write("{0} ",node); #endif } } #if DEBUG_CLUSTER2 Console.Write("\nThrottled nodes: "); for(int i=0;i<Config.N;i++) if(m_isThrottled[i]) Console.Write("{0} ",i); Console.Write("\n*NOT* Throttled nodes: "); for(int i=0;i<Config.N;i++) if(!m_isThrottled[i]) Console.Write("{0} ",i); Console.Write("\n"); #endif } public override void doStep() { //sampling period: Examine the network state and determine whether to throttle or not if (Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) { setThrottling(); lastNetUtil = Simulator.stats.netutil.Total; resetStat(); } //once throttle mode is turned on. Let each cluster run for a certain time interval //to ensure fairness. Otherwise it's throttled most of the time. if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) { doThrottling(); } } /** * @brief Determines whether the network is congested or not **/ public override bool thresholdTrigger() { double netutil=((double)(Simulator.stats.netutil.Total -lastNetUtil)/ (double)Config.throttle_sampling_period); #if DEBUG_NETUTIL Console.WriteLine("avg netUtil = {0} thres at {1}",netutil,Config.netutil_throttling_threshold); #endif return (netutil > Config.netutil_throttling_threshold)?true:false; } public override void setThrottling() { #if DEBUG_NETUTIL Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); #endif //get the MPKI value for (int i = 0; i < Config.N; i++) { prev_MPKI[i]=MPKI[i]; if(num_ins_last_epoch[i]==0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0) MPKI[i]=0; else throw new Exception("MPKI error!"); } } recordStats(); if(isThrottling) { double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period); #if DEBUG_NETUTIL Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}", netutil,Config.netutil_throttling_threshold); #endif /* TODO: * 1.If the netutil remains high, lower the threshold value for each cluster * to reduce the netutil further more and create a new pool/schedule for * all the clusters. How to raise it back? * Worst case: 1 app per cluster. * * 2.Find the difference b/w the current netutil and the threshold. * Then increase the throttle rate for each cluster based on that difference. * * 3.maybe add stalling clusters? * */ isThrottling=false; //un-throttle the network for(int i=0;i<Config.N;i++) setThrottleRate(i,false); cluster_pool.removeAllClusters(); double diff=netutil-Config.netutil_throttling_threshold; //Option1: adjust the mpki thresh for each cluster //if netutil within range of 10% increase MPKI boundary for each cluster if(Config.adaptive_cluster_mpki) { double new_MPKI_thresh=cluster_pool.clusterThreshold(); if(diff<0.10) new_MPKI_thresh+=10; else if(diff>0.2) new_MPKI_thresh-=20; cluster_pool.changeThresh(new_MPKI_thresh); } //Option2: adjust the throttle rate // // //Use alpha*total_MPKI+base to find the optimal netutil for performance //0.5 is the baseline netutil threshold //0.03 is calculated empricically using some base cases to find this number b/w total_mpki and target netutil double total_mpki=0.0; for(int i=0;i<Config.N;i++) total_mpki+=MPKI[i]; double target_netutil=(0.03*total_mpki+50)/100; //50% baseline if(Config.alpha) { //within 2% range if(netutil<(0.98*target_netutil)) Config.RR_throttle_rate-=0.02; else if(netutil>(1.02*target_netutil)) if(Config.RR_throttle_rate<0.95)//max is 95% Config.RR_throttle_rate+=0.01; //if target is too high, only throttle max to 95% inj rate if(target_netutil>0.9) Config.RR_throttle_rate=0.95; } //Trying to force 60-70% netutil if(Config.adaptive_rate) { if(diff<0.1) Config.RR_throttle_rate-=0.02; else if(diff>0.2) if(Config.RR_throttle_rate<0.95) Config.RR_throttle_rate+=0.01; } #if DEBUG_CLUSTER_RATE Console.WriteLine("Netutil diff: {2}-{3}={1} New th rate:{0} New MPKI thresh: {6} Target netutil:{4} Total MPKI:{5}", Config.RR_throttle_rate,diff, netutil,Config.netutil_throttling_threshold,target_netutil,total_mpki,cluster_pool.clusterThreshold()); #endif Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate); } if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not { //determine if the node is high intensive by using MPKI int total_high = 0; double total_mpki=0.0; for (int i = 0; i < Config.N; i++) { total_mpki+=MPKI[i]; if (MPKI[i] > Config.MPKI_high_node) { cluster_pool.addNewNode(i,MPKI[i]); total_high++; //TODO: add stats? #if DEBUG Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } else { #if DEBUG Console.Write("@OFF@:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } } Simulator.stats.total_sum_mpki.Add(total_mpki); #if DEBUG Console.WriteLine(")"); #endif //if no node needs to be throttled, set throttling to false isThrottling = (total_high>0)?true:false; #if DEBUG_CLUSTER cluster_pool.printClusterPool(); #endif } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel.Diagnostics; using System.Threading; using System.ServiceModel.Diagnostics.Application; class TracingConnection : DelegatingConnection { ServiceModelActivity activity; static WaitCallback callback; public TracingConnection(IConnection connection, ServiceModelActivity activity) : base(connection) { this.activity = activity; } public TracingConnection(IConnection connection, bool inheritCurrentActivity) : base(connection) { this.activity = inheritCurrentActivity ? ServiceModelActivity.CreateActivity(DiagnosticTraceBase.ActivityId, false) : ServiceModelActivity.CreateActivity(); Fx.Assert(this.activity != null, ""); if (DiagnosticUtility.ShouldUseActivity && !inheritCurrentActivity) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(this.activity.Id); } } } public override void Abort() { try { using (ServiceModelActivity.BoundOperation(this.activity)) { base.Abort(); } } finally { if (this.activity != null) { this.activity.Dispose(); } } } static WaitCallback Callback { get { if (TracingConnection.callback == null) { TracingConnection.callback = new WaitCallback(TracingConnection.WaitCallback); } return TracingConnection.callback; } } public override void Close(TimeSpan timeout, bool asyncAndLinger) { try { using (ServiceModelActivity.BoundOperation(this.activity, true)) { base.Close(timeout, asyncAndLinger); } } finally { if (this.activity != null) { this.activity.Dispose(); } } } public override void Shutdown(TimeSpan timeout) { using (ServiceModelActivity.BoundOperation(this.activity, true)) { base.Shutdown(timeout); } } internal void ActivityStart(string name) { using (ServiceModelActivity.BoundOperation(this.activity)) { ServiceModelActivity.Start(this.activity, SR.GetString(SR.ActivityReceiveBytes, name), ActivityType.ReceiveBytes); } } internal void ActivityStart(Uri uri) { using (ServiceModelActivity.BoundOperation(this.activity)) { ServiceModelActivity.Start(this.activity, SR.GetString(SR.ActivityReceiveBytes, uri.ToString()), ActivityType.ReceiveBytes); } } public override AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, WaitCallback callback, object state) { using (ServiceModelActivity.BoundOperation(this.activity)) { return base.BeginWrite(buffer, offset, size, immediate, timeout, callback, state); } } public override void EndWrite() { using (ServiceModelActivity.BoundOperation(this.activity)) { base.EndWrite(); } } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { using (ServiceModelActivity.BoundOperation(this.activity)) { base.Write(buffer, offset, size, immediate, timeout); } } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { using (ServiceModelActivity.BoundOperation(this.activity)) { base.Write(buffer, offset, size, immediate, timeout, bufferManager); } } public override int Read(byte[] buffer, int offset, int size, TimeSpan timeout) { using (ServiceModelActivity.BoundOperation(this.activity)) { return base.Read(buffer, offset, size, timeout); } } static void WaitCallback(object state) { TracingConnectionState tracingData = (TracingConnectionState)state; tracingData.ExecuteCallback(); } public override AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, System.Threading.WaitCallback callback, object state) { using (ServiceModelActivity.BoundOperation(this.activity)) { TracingConnectionState completion = new TracingConnectionState(callback, this.activity, state); return base.BeginRead(offset, size, timeout, TracingConnection.Callback, completion); } } public override int EndRead() { int retval = 0; try { if (this.activity != null) { ExceptionUtility.UseActivityId(this.activity.Id); } retval = base.EndRead(); } finally { ExceptionUtility.ClearActivityId(); } return retval; } public override object DuplicateAndClose(int targetProcessId) { using (ServiceModelActivity.BoundOperation(this.activity, true)) { return base.DuplicateAndClose(targetProcessId); } } class TracingConnectionState { object state; WaitCallback callback; ServiceModelActivity activity; internal TracingConnectionState(WaitCallback callback, ServiceModelActivity activity, object state) { this.activity = activity; this.callback = callback; this.state = state; } internal void ExecuteCallback() { using (ServiceModelActivity.BoundOperation(this.activity)) { this.callback(state); } } } } }
using System; using System.Text.Encodings.Web; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Client; using BTCPayServer.Data; using BTCPayServer.Fido2; using BTCPayServer.Models; using BTCPayServer.Models.ManageViewModels; using BTCPayServer.Security.Greenfield; using BTCPayServer.Services; using BTCPayServer.Services.Mails; using BTCPayServer.Services.Stores; using BTCPayServer.Services.Wallets; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; namespace BTCPayServer.Controllers { [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewProfile)] [Route("account/{action:lowercase=Index}")] public partial class UIManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly EmailSenderFactory _EmailSenderFactory; private readonly ILogger _logger; private readonly UrlEncoder _urlEncoder; private readonly BTCPayServerEnvironment _btcPayServerEnvironment; private readonly APIKeyRepository _apiKeyRepository; private readonly IAuthorizationService _authorizationService; private readonly Fido2Service _fido2Service; private readonly LinkGenerator _linkGenerator; private readonly UserLoginCodeService _userLoginCodeService; private readonly UserService _userService; readonly StoreRepository _StoreRepository; public UIManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, EmailSenderFactory emailSenderFactory, ILogger<UIManageController> logger, UrlEncoder urlEncoder, StoreRepository storeRepository, BTCPayServerEnvironment btcPayServerEnvironment, APIKeyRepository apiKeyRepository, IAuthorizationService authorizationService, Fido2Service fido2Service, LinkGenerator linkGenerator, UserService userService, UserLoginCodeService userLoginCodeService ) { _userManager = userManager; _signInManager = signInManager; _EmailSenderFactory = emailSenderFactory; _logger = logger; _urlEncoder = urlEncoder; _btcPayServerEnvironment = btcPayServerEnvironment; _apiKeyRepository = apiKeyRepository; _authorizationService = authorizationService; _fido2Service = fido2Service; _linkGenerator = linkGenerator; _userLoginCodeService = userLoginCodeService; _userService = userService; _StoreRepository = storeRepository; } [HttpGet] public async Task<IActionResult> Index() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var model = new IndexViewModel { Username = user.UserName, Email = user.Email, IsEmailConfirmed = user.EmailConfirmed }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableShowInvoiceStatusChangeHint() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var blob = user.GetBlob(); blob.ShowInvoiceStatusChangeHint = false; if (user.SetBlob(blob)) { await _userManager.UpdateAsync(user); } return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(IndexViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var email = user.Email; if (model.Email != email) { if (!(await _userManager.FindByEmailAsync(model.Email) is null)) { TempData[WellKnownTempData.ErrorMessage] = "The email address is already in use with an other account."; return RedirectToAction(nameof(Index)); } var setUserResult = await _userManager.SetUserNameAsync(user, model.Email); if (!setUserResult.Succeeded) { throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'."); } var setEmailResult = await _userManager.SetEmailAsync(user, model.Email); if (!setEmailResult.Succeeded) { throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'."); } } TempData[WellKnownTempData.SuccessMessage] = "Your profile has been updated"; return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SendVerificationEmail(IndexViewModel model) { if (!ModelState.IsValid) { return View(nameof(Index), model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = _linkGenerator.EmailConfirmationLink(user.Id, code, Request.Scheme, Request.Host, Request.PathBase); var email = user.Email; (await _EmailSenderFactory.GetEmailSender()).SendEmailConfirmation(email, callbackUrl); TempData[WellKnownTempData.SuccessMessage] = "Verification email sent. Please check your email."; return RedirectToAction(nameof(Index)); } [HttpGet] public async Task<IActionResult> ChangePassword() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (!hasPassword) { return RedirectToAction(nameof(SetPassword)); } var model = new ChangePasswordViewModel(); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { AddErrors(changePasswordResult); return View(model); } await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation("User changed their password successfully."); TempData[WellKnownTempData.SuccessMessage] = "Your password has been changed."; return RedirectToAction(nameof(ChangePassword)); } [HttpGet] public async Task<IActionResult> SetPassword() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (hasPassword) { return RedirectToAction(nameof(ChangePassword)); } var model = new SetPasswordViewModel(); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword); if (!addPasswordResult.Succeeded) { AddErrors(addPasswordResult); return View(model); } await _signInManager.SignInAsync(user, isPersistent: false); TempData[WellKnownTempData.SuccessMessage] = "Your password has been set."; return RedirectToAction(nameof(SetPassword)); } [HttpPost()] public async Task<IActionResult> DeleteUserPost() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound(); } await _userService.DeleteUserAndAssociatedData(user); TempData[WellKnownTempData.SuccessMessage] = "Account successfully deleted."; await _signInManager.SignOutAsync(); return RedirectToAction(nameof(UIAccountController.Login), "UIAccount"); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } #endregion } }
namespace eidss.avr.QueryBuilder { partial class QuerySearchObjectInfo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QuerySearchObjectInfo)); this.splitContainerFilters = new DevExpress.XtraEditors.SplitContainerControl(); this.qsoFilter = new eidss.avr.FilterForm.QueryFilterControl(); this.cbReportType = new DevExpress.XtraEditors.LookUpEdit(); //old filter//this.QuerySearchFilter = new DevExpress.XtraEditors.FilterControl(); this.lblFilter = new DevExpress.XtraEditors.LabelControl(); this.lblReportType = new DevExpress.XtraEditors.LabelControl(); this.txtFilterText = new DevExpress.XtraEditors.MemoEdit(); this.splitContainerFields = new DevExpress.XtraEditors.SplitContainerControl(); this.lblAvailableField = new DevExpress.XtraEditors.LabelControl(); this.imlbcAvailableField = new DevExpress.XtraEditors.ImageListBoxControl(); this.ttcAvailableField = new DevExpress.Utils.ToolTipController(this.components); this.btnAdd = new DevExpress.XtraEditors.SimpleButton(); this.btnRemoveAll = new DevExpress.XtraEditors.SimpleButton(); this.btnAddAll = new DevExpress.XtraEditors.SimpleButton(); this.btnRemove = new DevExpress.XtraEditors.SimpleButton(); this.lblSelectedField = new DevExpress.XtraEditors.LabelControl(); this.gcSelectedField = new DevExpress.XtraGrid.GridControl(); this.gvSelectedField = new DevExpress.XtraGrid.Views.Grid.GridView(); this.colQuerySearchField = new DevExpress.XtraGrid.Columns.GridColumn(); this.colShow = new DevExpress.XtraGrid.Columns.GridColumn(); this.chShow = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit(); this.gcolTypeImage = new DevExpress.XtraGrid.Columns.GridColumn(); this.imTypeImage = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox(); this.colFieldCaption = new DevExpress.XtraGrid.Columns.GridColumn(); this.grcQueryObjectFiltration = new DevExpress.XtraEditors.GroupControl(); this.navSearchFields = new DevExpress.XtraNavBar.NavBarControl(); this.grpSearchFields = new DevExpress.XtraNavBar.NavBarGroup(); this.navSearchFieldsContainer = new DevExpress.XtraNavBar.NavBarGroupControlContainer(); this.cbFilterByDiagnosis = new DevExpress.XtraEditors.LookUpEdit(); this.lblFilterByDiagnosis = new DevExpress.XtraEditors.LabelControl(); this.splitFields = new DevExpress.XtraEditors.SplitterControl(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerFilters)).BeginInit(); this.splitContainerFilters.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cbReportType.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFilterText.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerFields)).BeginInit(); this.splitContainerFields.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.imlbcAvailableField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gcSelectedField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gvSelectedField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.chShow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imTypeImage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.grcQueryObjectFiltration)).BeginInit(); this.grcQueryObjectFiltration.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.navSearchFields)).BeginInit(); this.navSearchFields.SuspendLayout(); this.navSearchFieldsContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cbFilterByDiagnosis.Properties)).BeginInit(); this.SuspendLayout(); bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(QuerySearchObjectInfo), out resources); // Form Is Localizable: True // // splitContainerFilters // this.splitContainerFilters.Appearance.Options.UseFont = true; this.splitContainerFilters.AppearanceCaption.Options.UseFont = true; this.splitContainerFilters.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel2; resources.ApplyResources(this.splitContainerFilters, "splitContainerFilters"); this.splitContainerFilters.FixedPanel = DevExpress.XtraEditors.SplitFixedPanel.Panel2; this.splitContainerFilters.Horizontal = false; this.splitContainerFilters.Name = "splitContainerFilters"; this.splitContainerFilters.Panel1.Appearance.Options.UseFont = true; this.splitContainerFilters.Panel1.AppearanceCaption.Options.UseFont = true; this.splitContainerFilters.Panel1.Controls.Add(this.qsoFilter); this.splitContainerFilters.Panel1.Controls.Add(this.cbReportType); //old filter//this.splitContainerFilters.Panel1.Controls.Add(this.QuerySearchFilter); this.splitContainerFilters.Panel1.Controls.Add(this.lblFilter); this.splitContainerFilters.Panel1.Controls.Add(this.lblReportType); this.splitContainerFilters.Panel1.MinSize = 100; this.splitContainerFilters.Panel2.Appearance.Options.UseFont = true; this.splitContainerFilters.Panel2.AppearanceCaption.Options.UseFont = true; this.splitContainerFilters.Panel2.Controls.Add(this.txtFilterText); this.splitContainerFilters.Panel2.MinSize = 40; resources.ApplyResources(this.splitContainerFilters.Panel2, "splitContainerFilters.Panel2"); this.splitContainerFilters.SplitterPosition = 75; this.splitContainerFilters.SplitGroupPanelCollapsed += new DevExpress.XtraEditors.SplitGroupPanelCollapsedEventHandler(this.splitContainer_SplitGroupPanelCollapsed); // // qsoFilter // resources.ApplyResources(this.qsoFilter, "qsoFilter"); this.qsoFilter.Appearance.Options.UseFont = true; this.qsoFilter.AppearanceTreeLine.Options.UseFont = true; this.qsoFilter.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Flat; this.qsoFilter.Cursor = System.Windows.Forms.Cursors.Arrow; this.qsoFilter.HasChanges = false; this.qsoFilter.Name = "qsoFilter"; this.qsoFilter.ObjectHACode = EIDSS.HACode.None; // // cbReportType // resources.ApplyResources(this.cbReportType, "cbReportType"); this.cbReportType.Name = "cbReportType"; this.cbReportType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("cbReportType.Properties.Buttons"))))}); this.cbReportType.Properties.NullText = resources.GetString("cbReportType.Properties.NullText"); //old filter//// //old filter//// QuerySearchFilter //old filter//// //old filter//resources.ApplyResources(this.QuerySearchFilter, "QuerySearchFilter"); //old filter//this.QuerySearchFilter.Appearance.Options.UseFont = true; //old filter//this.QuerySearchFilter.AppearanceTreeLine.Options.UseFont = true; //old filter//this.QuerySearchFilter.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Flat; //old filter//this.QuerySearchFilter.Cursor = System.Windows.Forms.Cursors.Arrow; //old filter//this.QuerySearchFilter.Name = "QuerySearchFilter"; // // lblFilter // resources.ApplyResources(this.lblFilter, "lblFilter"); this.lblFilter.Name = "lblFilter"; // // lblReportType // resources.ApplyResources(this.lblReportType, "lblReportType"); this.lblReportType.Name = "lblReportType"; // // txtFilterText // resources.ApplyResources(this.txtFilterText, "txtFilterText"); this.txtFilterText.Name = "txtFilterText"; this.txtFilterText.Properties.Appearance.Options.UseFont = true; this.txtFilterText.Properties.AppearanceDisabled.BackColor = ((System.Drawing.Color)(resources.GetObject("txtFilterText.Properties.AppearanceDisabled.BackColor"))); this.txtFilterText.Properties.AppearanceDisabled.Options.UseBackColor = true; this.txtFilterText.Properties.AppearanceDisabled.Options.UseFont = true; this.txtFilterText.Properties.AppearanceFocused.Options.UseFont = true; this.txtFilterText.Properties.AppearanceReadOnly.BackColor = ((System.Drawing.Color)(resources.GetObject("txtFilterText.Properties.AppearanceReadOnly.BackColor"))); this.txtFilterText.Properties.AppearanceReadOnly.Options.UseBackColor = true; this.txtFilterText.Properties.AppearanceReadOnly.Options.UseFont = true; this.txtFilterText.Properties.ReadOnly = true; this.txtFilterText.Tag = "{R}"; this.txtFilterText.UseOptimizedRendering = true; // // splitContainerFields // resources.ApplyResources(this.splitContainerFields, "splitContainerFields"); this.splitContainerFields.Appearance.Options.UseFont = true; this.splitContainerFields.AppearanceCaption.Options.UseFont = true; this.splitContainerFields.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel2; this.splitContainerFields.FixedPanel = DevExpress.XtraEditors.SplitFixedPanel.Panel2; this.splitContainerFields.Name = "splitContainerFields"; this.splitContainerFields.Panel1.Appearance.Options.UseFont = true; this.splitContainerFields.Panel1.AppearanceCaption.Options.UseFont = true; this.splitContainerFields.Panel1.Controls.Add(this.lblAvailableField); this.splitContainerFields.Panel1.Controls.Add(this.imlbcAvailableField); this.splitContainerFields.Panel1.Controls.Add(this.btnAdd); this.splitContainerFields.Panel1.Controls.Add(this.btnRemoveAll); this.splitContainerFields.Panel1.Controls.Add(this.btnAddAll); this.splitContainerFields.Panel1.Controls.Add(this.btnRemove); this.splitContainerFields.Panel1.MinSize = 200; this.splitContainerFields.Panel2.Appearance.Options.UseFont = true; this.splitContainerFields.Panel2.AppearanceCaption.Options.UseFont = true; this.splitContainerFields.Panel2.Controls.Add(this.lblSelectedField); this.splitContainerFields.Panel2.Controls.Add(this.gcSelectedField); this.splitContainerFields.Panel2.MinSize = 100; resources.ApplyResources(this.splitContainerFields.Panel2, "splitContainerFields.Panel2"); this.splitContainerFields.SplitterPosition = 211; // // lblAvailableField // resources.ApplyResources(this.lblAvailableField, "lblAvailableField"); this.lblAvailableField.Name = "lblAvailableField"; // // imlbcAvailableField // resources.ApplyResources(this.imlbcAvailableField, "imlbcAvailableField"); this.imlbcAvailableField.HorizontalScrollbar = true; this.imlbcAvailableField.Name = "imlbcAvailableField"; this.imlbcAvailableField.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.imlbcAvailableField.ToolTipController = this.ttcAvailableField; this.imlbcAvailableField.SelectedIndexChanged += new System.EventHandler(this.imlbcAvailableField_SelectedIndexChanged); this.imlbcAvailableField.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.imlbcAvailableField_MouseDoubleClick); this.imlbcAvailableField.MouseLeave += new System.EventHandler(this.imlbcAvailableField_MouseLeave); this.imlbcAvailableField.MouseMove += new System.Windows.Forms.MouseEventHandler(this.imlbcAvailableField_MouseMove); // // ttcAvailableField // this.ttcAvailableField.CloseOnClick = DevExpress.Utils.DefaultBoolean.True; this.ttcAvailableField.InitialDelay = 1000; this.ttcAvailableField.ReshowDelay = 200; // // btnAdd // resources.ApplyResources(this.btnAdd, "btnAdd"); this.btnAdd.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnAdd.Appearance.Font"))); this.btnAdd.Appearance.Options.UseFont = true; this.btnAdd.ImageIndex = 0; this.btnAdd.ImageLocation = DevExpress.XtraEditors.ImageLocation.MiddleCenter; this.btnAdd.Name = "btnAdd"; this.btnAdd.Tag = "FixFont"; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnRemoveAll // resources.ApplyResources(this.btnRemoveAll, "btnRemoveAll"); this.btnRemoveAll.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnRemoveAll.Appearance.Font"))); this.btnRemoveAll.Appearance.Options.UseFont = true; this.btnRemoveAll.ImageIndex = 3; this.btnRemoveAll.Name = "btnRemoveAll"; this.btnRemoveAll.Tag = "FixFont"; this.btnRemoveAll.Click += new System.EventHandler(this.btnRemoveAll_Click); // // btnAddAll // resources.ApplyResources(this.btnAddAll, "btnAddAll"); this.btnAddAll.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnAddAll.Appearance.Font"))); this.btnAddAll.Appearance.Options.UseFont = true; this.btnAddAll.ImageIndex = 2; this.btnAddAll.Name = "btnAddAll"; this.btnAddAll.Tag = "FixFont"; this.btnAddAll.Click += new System.EventHandler(this.btnAddAll_Click); // // btnRemove // resources.ApplyResources(this.btnRemove, "btnRemove"); this.btnRemove.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnRemove.Appearance.Font"))); this.btnRemove.Appearance.Options.UseFont = true; this.btnRemove.Name = "btnRemove"; this.btnRemove.Tag = "FixFont"; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // lblSelectedField // resources.ApplyResources(this.lblSelectedField, "lblSelectedField"); this.lblSelectedField.Name = "lblSelectedField"; // // gcSelectedField // resources.ApplyResources(this.gcSelectedField, "gcSelectedField"); this.gcSelectedField.EmbeddedNavigator.Appearance.Options.UseFont = true; this.gcSelectedField.MainView = this.gvSelectedField; this.gcSelectedField.Name = "gcSelectedField"; this.gcSelectedField.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.chShow, this.imTypeImage}); this.gcSelectedField.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gvSelectedField}); // // gvSelectedField // this.gvSelectedField.ActiveFilterEnabled = false; this.gvSelectedField.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colQuerySearchField, this.colShow, this.gcolTypeImage, this.colFieldCaption}); this.gvSelectedField.GridControl = this.gcSelectedField; this.gvSelectedField.Name = "gvSelectedField"; this.gvSelectedField.OptionsCustomization.AllowColumnMoving = false; this.gvSelectedField.OptionsCustomization.AllowFilter = false; this.gvSelectedField.OptionsCustomization.AllowGroup = false; this.gvSelectedField.OptionsCustomization.AllowSort = false; this.gvSelectedField.OptionsNavigation.AutoFocusNewRow = true; this.gvSelectedField.OptionsSelection.MultiSelect = true; this.gvSelectedField.OptionsView.ShowColumnHeaders = false; this.gvSelectedField.OptionsView.ShowDetailButtons = false; this.gvSelectedField.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never; this.gvSelectedField.OptionsView.ShowGroupExpandCollapseButtons = false; this.gvSelectedField.OptionsView.ShowGroupPanel = false; this.gvSelectedField.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.False; this.gvSelectedField.OptionsView.ShowIndicator = false; this.gvSelectedField.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.False; this.gvSelectedField.RowCellClick += new DevExpress.XtraGrid.Views.Grid.RowCellClickEventHandler(this.gvSelectedField_RowCellClick); // // colQuerySearchField // resources.ApplyResources(this.colQuerySearchField, "colQuerySearchField"); this.colQuerySearchField.FieldName = "idfQuerySearchField"; this.colQuerySearchField.Name = "colQuerySearchField"; // // colShow // resources.ApplyResources(this.colShow, "colShow"); this.colShow.ColumnEdit = this.chShow; this.colShow.FieldName = "blnShow"; this.colShow.Name = "colShow"; this.colShow.OptionsColumn.AllowMove = false; this.colShow.OptionsColumn.AllowSize = false; this.colShow.OptionsColumn.ShowInCustomizationForm = false; // // chShow // this.chShow.Appearance.Options.UseFont = true; this.chShow.AppearanceDisabled.Options.UseFont = true; this.chShow.AppearanceFocused.Options.UseFont = true; this.chShow.AppearanceReadOnly.Options.UseFont = true; resources.ApplyResources(this.chShow, "chShow"); this.chShow.Name = "chShow"; // // gcolTypeImage // resources.ApplyResources(this.gcolTypeImage, "gcolTypeImage"); this.gcolTypeImage.ColumnEdit = this.imTypeImage; this.gcolTypeImage.FieldName = "TypeImageIndex"; this.gcolTypeImage.Name = "gcolTypeImage"; this.gcolTypeImage.OptionsColumn.AllowEdit = false; this.gcolTypeImage.OptionsColumn.AllowMove = false; this.gcolTypeImage.OptionsColumn.AllowSize = false; this.gcolTypeImage.OptionsColumn.ShowInCustomizationForm = false; this.gcolTypeImage.OptionsColumn.TabStop = false; // // imTypeImage // resources.ApplyResources(this.imTypeImage, "imTypeImage"); this.imTypeImage.Name = "imTypeImage"; this.imTypeImage.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never; // // colFieldCaption // resources.ApplyResources(this.colFieldCaption, "colFieldCaption"); this.colFieldCaption.FieldName = "FieldCaption"; this.colFieldCaption.Name = "colFieldCaption"; this.colFieldCaption.OptionsColumn.AllowEdit = false; this.colFieldCaption.OptionsColumn.AllowMove = false; this.colFieldCaption.OptionsColumn.AllowShowHide = false; this.colFieldCaption.OptionsColumn.ShowInCustomizationForm = false; // // grcQueryObjectFiltration // this.grcQueryObjectFiltration.Appearance.Options.UseFont = true; this.grcQueryObjectFiltration.AppearanceCaption.Options.UseFont = true; this.grcQueryObjectFiltration.Controls.Add(this.splitContainerFilters); resources.ApplyResources(this.grcQueryObjectFiltration, "grcQueryObjectFiltration"); this.grcQueryObjectFiltration.Name = "grcQueryObjectFiltration"; // // navSearchFields // this.navSearchFields.ActiveGroup = this.grpSearchFields; this.navSearchFields.Appearance.Background.Options.UseFont = true; this.navSearchFields.Appearance.Button.Options.UseFont = true; this.navSearchFields.Appearance.ButtonDisabled.Options.UseFont = true; this.navSearchFields.Appearance.ButtonHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.ButtonPressed.Options.UseFont = true; this.navSearchFields.Appearance.GroupBackground.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeader.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderActive.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderPressed.Options.UseFont = true; this.navSearchFields.Appearance.Hint.Options.UseFont = true; this.navSearchFields.Appearance.Item.Options.UseFont = true; this.navSearchFields.Appearance.ItemActive.Options.UseFont = true; this.navSearchFields.Appearance.ItemDisabled.Options.UseFont = true; this.navSearchFields.Appearance.ItemHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.ItemPressed.Options.UseFont = true; this.navSearchFields.Appearance.LinkDropTarget.Options.UseFont = true; this.navSearchFields.Appearance.NavigationPaneHeader.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButton.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonPressed.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonReleased.Options.UseFont = true; this.navSearchFields.ContentButtonHint = null; this.navSearchFields.Controls.Add(this.navSearchFieldsContainer); resources.ApplyResources(this.navSearchFields, "navSearchFields"); this.navSearchFields.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] { this.grpSearchFields}); this.navSearchFields.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003; this.navSearchFields.Name = "navSearchFields"; this.navSearchFields.NavigationPaneOverflowPanelUseSmallImages = false; this.navSearchFields.OptionsNavPane.ExpandedWidth = ((int)(resources.GetObject("resource.ExpandedWidth"))); this.navSearchFields.OptionsNavPane.ShowOverflowPanel = false; this.navSearchFields.OptionsNavPane.ShowSplitter = false; this.navSearchFields.ShowGroupHint = false; this.navSearchFields.View = new DevExpress.XtraNavBar.ViewInfo.SkinNavigationPaneViewInfoRegistrator(); // // grpSearchFields // resources.ApplyResources(this.grpSearchFields, "grpSearchFields"); this.grpSearchFields.ControlContainer = this.navSearchFieldsContainer; this.grpSearchFields.Expanded = true; this.grpSearchFields.GroupClientHeight = 308; this.grpSearchFields.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer; this.grpSearchFields.Name = "grpSearchFields"; this.grpSearchFields.NavigationPaneVisible = false; // // navSearchFieldsContainer // this.navSearchFieldsContainer.Controls.Add(this.splitContainerFields); this.navSearchFieldsContainer.Controls.Add(this.cbFilterByDiagnosis); this.navSearchFieldsContainer.Controls.Add(this.lblFilterByDiagnosis); this.navSearchFieldsContainer.Name = "navSearchFieldsContainer"; resources.ApplyResources(this.navSearchFieldsContainer, "navSearchFieldsContainer"); // // cbFilterByDiagnosis // resources.ApplyResources(this.cbFilterByDiagnosis, "cbFilterByDiagnosis"); this.cbFilterByDiagnosis.Name = "cbFilterByDiagnosis"; this.cbFilterByDiagnosis.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("cbFilterByDiagnosis.Properties.Buttons"))))}); this.cbFilterByDiagnosis.Properties.NullText = resources.GetString("cbFilterByDiagnosis.Properties.NullText"); this.cbFilterByDiagnosis.EditValueChanged += new System.EventHandler(this.cbFilterByDiagnosis_EditValueChanged); // // lblFilterByDiagnosis // resources.ApplyResources(this.lblFilterByDiagnosis, "lblFilterByDiagnosis"); this.lblFilterByDiagnosis.Name = "lblFilterByDiagnosis"; // // splitFields // resources.ApplyResources(this.splitFields, "splitFields"); this.splitFields.Name = "splitFields"; this.splitFields.TabStop = false; // // QuerySearchObjectInfo // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.grcQueryObjectFiltration); this.Controls.Add(this.splitFields); this.Controls.Add(this.navSearchFields); this.DefaultFormState = System.Windows.Forms.FormWindowState.Normal; this.KeyFieldName = "idfQuerySearchObject"; this.MinHeight = 300; this.Name = "QuerySearchObjectInfo"; this.ObjectName = "QuerySearchObject"; this.Status = bv.common.win.FormStatus.Draft; this.TableName = "tasQuerySearchObject"; this.OnBeforePost += new System.EventHandler(this.QuerySearchObjectInfo_OnBeforePost); this.OnAfterPost += new System.EventHandler(this.QuerySearchObjectInfo_OnAfterPost); this.AfterLoadData += new System.EventHandler(this.QuerySearchObjectInfo_AfterLoadData); ((System.ComponentModel.ISupportInitialize)(this.splitContainerFilters)).EndInit(); this.splitContainerFilters.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.cbReportType.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFilterText.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerFields)).EndInit(); this.splitContainerFields.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.imlbcAvailableField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gcSelectedField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gvSelectedField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.chShow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imTypeImage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.grcQueryObjectFiltration)).EndInit(); this.grcQueryObjectFiltration.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.navSearchFields)).EndInit(); this.navSearchFields.ResumeLayout(false); this.navSearchFieldsContainer.ResumeLayout(false); this.navSearchFieldsContainer.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.cbFilterByDiagnosis.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.LabelControl lblSelectedField; private DevExpress.XtraEditors.LabelControl lblAvailableField; private DevExpress.XtraEditors.GroupControl grcQueryObjectFiltration; private DevExpress.XtraEditors.LabelControl lblFilter; private DevExpress.XtraGrid.GridControl gcSelectedField; private DevExpress.XtraGrid.Views.Grid.GridView gvSelectedField; private DevExpress.XtraGrid.Columns.GridColumn colShow; private DevExpress.XtraGrid.Columns.GridColumn colQuerySearchField; private DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit chShow; private DevExpress.XtraGrid.Columns.GridColumn colFieldCaption; //old filter//private DevExpress.XtraEditors.FilterControl QuerySearchFilter; private DevExpress.XtraEditors.MemoEdit txtFilterText; private DevExpress.XtraNavBar.NavBarControl navSearchFields; private DevExpress.XtraNavBar.NavBarGroup grpSearchFields; private DevExpress.XtraNavBar.NavBarGroupControlContainer navSearchFieldsContainer; private DevExpress.XtraEditors.SplitContainerControl splitContainerFilters; private DevExpress.XtraEditors.SplitterControl splitFields; private DevExpress.XtraGrid.Columns.GridColumn gcolTypeImage; private DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox imTypeImage; private DevExpress.Utils.ToolTipController ttcAvailableField; private DevExpress.XtraEditors.LookUpEdit cbFilterByDiagnosis; private DevExpress.XtraEditors.LabelControl lblFilterByDiagnosis; private DevExpress.XtraEditors.LookUpEdit cbReportType; private DevExpress.XtraEditors.LabelControl lblReportType; private DevExpress.XtraEditors.SplitContainerControl splitContainerFields; private DevExpress.XtraEditors.ImageListBoxControl imlbcAvailableField; private DevExpress.XtraEditors.SimpleButton btnAdd; private DevExpress.XtraEditors.SimpleButton btnRemoveAll; private DevExpress.XtraEditors.SimpleButton btnAddAll; private DevExpress.XtraEditors.SimpleButton btnRemove; private FilterForm.QueryFilterControl qsoFilter; } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableGreaterThanOrEqualTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableByteGreaterThanOrEqualTest(bool useInterpreter) { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableCharGreaterThanOrEqualTest(bool useInterpreter) { char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalGreaterThanOrEqualTest(bool useInterpreter) { decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleGreaterThanOrEqualTest(bool useInterpreter) { double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatGreaterThanOrEqualTest(bool useInterpreter) { float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntGreaterThanOrEqualTest(bool useInterpreter) { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongGreaterThanOrEqualTest(bool useInterpreter) { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableSByteGreaterThanOrEqualTest(bool useInterpreter) { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortGreaterThanOrEqualTest(bool useInterpreter) { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntGreaterThanOrEqualTest(bool useInterpreter) { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongGreaterThanOrEqualTest(bool useInterpreter) { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortGreaterThanOrEqualTest(bool useInterpreter) { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortGreaterThanOrEqual(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyNullableByteGreaterThanOrEqual(byte? a, byte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableCharGreaterThanOrEqual(char? a, char? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableDecimalGreaterThanOrEqual(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableDoubleGreaterThanOrEqual(double? a, double? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableFloatGreaterThanOrEqual(float? a, float? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableIntGreaterThanOrEqual(int? a, int? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableLongGreaterThanOrEqual(long? a, long? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableSByteGreaterThanOrEqual(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableShortGreaterThanOrEqual(short? a, short? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableUIntGreaterThanOrEqual(uint? a, uint? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableULongGreaterThanOrEqual(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } private static void VerifyNullableUShortGreaterThanOrEqual(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThanOrEqual( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal(a >= b, f()); } #endregion } }
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 ArcheageCraft.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; } } }
// // FeedEnclosure.cs // // Authors: // Mike Urbanski <michael.c.urbanski@gmail.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007 Michael C. Urbanski // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using Hyena; using Hyena.Data.Sqlite; namespace Migo.Syndication { public class FeedEnclosure : MigoItem<FeedEnclosure> { private static SqliteModelProvider<FeedEnclosure> provider; public static SqliteModelProvider<FeedEnclosure> Provider { get { return provider; } } public static void Init () { provider = new MigoModelProvider<FeedEnclosure> (FeedsManager.Instance.Connection, "PodcastEnclosures"); } private string mimetype; private FeedDownloadStatus download_status; private FeedDownloadError last_download_error; private long file_size; private TimeSpan duration; private string keywords; private string local_path; private FeedItem item; private string url; private readonly object sync = new object (); #region Constructors public FeedEnclosure () { } #endregion #region Public Properties public FeedItem Item { get { return item ?? (item = FeedItem.Provider.FetchSingle (item_id)); } internal set { item = value; if (item != null && item.DbId > 0) { item_id = item.DbId; } } } #endregion public static EnclosureManager Manager { get { return FeedsManager.Instance.EnclosureManager; } } public FeedDownloadError LastDownloadError { get { return last_download_error; } internal set { last_download_error = value; } } #region Public Methods public void Save (bool save_item) { Provider.Save (this); if (save_item) { Item.Save (); } } public void Save () { Save (true); } public void Delete (bool and_delete_file) { if (and_delete_file) { DeleteFile (); } Provider.Delete (this); } public void AsyncDownload () { if (DownloadedAt == DateTime.MinValue && DownloadStatus == FeedDownloadStatus.None) { Manager.QueueDownload (this); } } public void CancelAsyncDownload () { Manager.CancelDownload (this); } public void StopAsyncDownload () { Manager.StopDownload (this); } // Deletes file associated with enclosure. // Does not cancel an active download like the WRP. public void DeleteFile () { lock (sync) { if (!String.IsNullOrEmpty (local_path) && File.Exists (local_path)) { try { File.SetAttributes (local_path, FileAttributes.Normal); File.Delete (local_path); Directory.Delete (Path.GetDirectoryName (local_path)); } catch {} } LocalPath = null; DownloadStatus = FeedDownloadStatus.None; LastDownloadError = FeedDownloadError.None; Save (); } } public void SetFileImpl (string url, string path, string mimeType, string filename) { if (filename.EndsWith (".torrent", StringComparison.OrdinalIgnoreCase)) { filename = filename.Substring (0, filename.Length - 8); } string local_enclosure_path = Item.Feed.LocalEnclosurePath; string full_path = Path.Combine (path, filename); string new_local_path = Path.Combine (local_enclosure_path, filename); try { if (!Directory.Exists (path)) { throw new InvalidOperationException ("Directory specified by path does not exist"); } else if (!File.Exists (full_path)) { throw new InvalidOperationException (String.Format ("File: {0}, does not exist", full_path)); } if (!Directory.Exists (local_enclosure_path)) { Directory.CreateDirectory (local_enclosure_path); } if (File.Exists (new_local_path)) { int last_dot = new_local_path.LastIndexOf ("."); if (last_dot == -1) { last_dot = new_local_path.Length-1; } string rep = String.Format ("-{0}", Guid.NewGuid ().ToString () .Replace ("-", String.Empty) .ToLower () ); new_local_path = new_local_path.Insert (last_dot, rep); } File.Move (full_path, new_local_path); File.SetAttributes (new_local_path, FileAttributes.ReadOnly); try { Directory.Delete (path); } catch {} } catch { LastDownloadError = FeedDownloadError.DownloadFailed; DownloadStatus = FeedDownloadStatus.DownloadFailed; Save (); throw; } LocalPath = new_local_path; Url = url; MimeType = mimeType; DownloadStatus = FeedDownloadStatus.Downloaded; LastDownloadError = FeedDownloadError.None; Save (); } #endregion #region Database Columns private long dbid; [DatabaseColumn ("EnclosureID", Constraints = DatabaseColumnConstraints.PrimaryKey)] public override long DbId { get { return dbid; } protected set { dbid = value; } } [DatabaseColumn ("ItemID", Index = "PodcastEnclosuresItemIDIndex")] protected long item_id; public long ItemId { get { return Item.DbId; } } [DatabaseColumn] public string LocalPath { get { return local_path; } set { local_path = value; } } [DatabaseColumn] public string Url { get { return url; } set { url = value; } } [DatabaseColumn] public string Keywords { get { return keywords; } set { keywords = value; } } [DatabaseColumn] public TimeSpan Duration { get { return duration; } set { duration = value; } } [DatabaseColumn] public long FileSize { get { return file_size; } set { file_size = value; } } [DatabaseColumn] public string MimeType { get { return mimetype; } set { mimetype = value; if (String.IsNullOrEmpty (mimetype)) { mimetype = "application/octet-stream"; } } } private DateTime downloaded_at; [DatabaseColumn] public DateTime DownloadedAt { get { return downloaded_at; } internal set { downloaded_at = value; } } [DatabaseColumn] public FeedDownloadStatus DownloadStatus { get { lock (sync) { return download_status; } } internal set { lock (sync) { download_status = value; } } } #endregion public override string ToString () { return String.Format ("FeedEnclosure<DbId: {0}, Url: {1}>", DbId, Url); } } }
using System; using System.Runtime.InteropServices; using System.Security; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// This class defines a view (position, size, etc.) ; /// you can consider it as a 2D camera /// </summary> //////////////////////////////////////////////////////////// public class View : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Create a default view (1000x1000) /// </summary> //////////////////////////////////////////////////////////// public View() : base(sfView_Create()) { } //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from a rectangle /// </summary> /// <param name="viewRect">Rectangle defining the position and size of the view</param> //////////////////////////////////////////////////////////// public View(FloatRect viewRect) : base(sfView_CreateFromRect(viewRect)) { } //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from its center and size /// </summary> /// <param name="center">Center of the view</param> /// <param name="size">Size of the view</param> //////////////////////////////////////////////////////////// public View(Vector2 center, Vector2 size) : base(sfView_Create()) { this.Center = center; this.Size = size; } //////////////////////////////////////////////////////////// /// <summary> /// Construct the view from another view /// </summary> /// <param name="copy">View to copy</param> //////////////////////////////////////////////////////////// public View(View copy) : base(sfView_Copy(copy.This)) { } //////////////////////////////////////////////////////////// /// <summary> /// Center of the view /// </summary> //////////////////////////////////////////////////////////// public Vector2 Center { get { return new Vector2(sfView_GetCenterX(This), sfView_GetCenterY(This)); } set { sfView_SetCenter(This, value.X, value.Y); } } //////////////////////////////////////////////////////////// /// <summary> /// Half-size of the view /// </summary> //////////////////////////////////////////////////////////// public Vector2 Size { get { return new Vector2(sfView_GetWidth(This), sfView_GetHeight(This)); } set { sfView_SetSize(This, value.X, value.Y); } } //////////////////////////////////////////////////////////// /// <summary> /// Rotation of the view, in degrees /// </summary> //////////////////////////////////////////////////////////// public float Rotation { get { return sfView_GetRotation(This); } set { sfView_SetRotation(This, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Target viewport of the view, defined as a factor of the /// size of the target to which the view is applied /// </summary> //////////////////////////////////////////////////////////// public FloatRect Viewport { get { return sfView_GetViewport(This); } set { sfView_SetViewport(This, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Rebuild the view from a rectangle /// </summary> /// <param name="rectangle">Rectangle defining the position and size of the view</param> //////////////////////////////////////////////////////////// public void Reset(FloatRect rectangle) { sfView_Reset(This, rectangle); } //////////////////////////////////////////////////////////// /// <summary> /// Move the view /// </summary> /// <param name="offset">Offset to move the view</param> //////////////////////////////////////////////////////////// public void Move(Vector2 offset) { sfView_Move(This, offset.X, offset.Y); } //////////////////////////////////////////////////////////// /// <summary> /// Rotate the view /// </summary> /// <param name="angle">Angle of rotation, in degrees</param> //////////////////////////////////////////////////////////// public void Rotate(float angle) { sfView_Rotate(This, angle); } //////////////////////////////////////////////////////////// /// <summary> /// Resize the view rectangle to simulate a zoom / unzoom effect /// </summary> /// <param name="factor">Zoom factor to apply, relative to the current zoom</param> //////////////////////////////////////////////////////////// public void Zoom(float factor) { sfView_Zoom(This, factor); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[View]" + " Center(" + Center + ")" + " Size(" + Size + ")" + " Rotation(" + Rotation + ")" + " Viewport(" + Viewport + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Internal constructor for other classes which need to manipulate raw views /// </summary> /// <param name="thisPtr">Direct pointer to the view object in the C library</param> //////////////////////////////////////////////////////////// internal View(IntPtr thisPtr) : base(thisPtr) { myExternal = true; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (!myExternal) sfView_Destroy(This); } private bool myExternal = false; #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfView_Create(); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfView_CreateFromRect(FloatRect Rect); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfView_Copy(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_Destroy(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_SetCenter(IntPtr View, float X, float Y); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_SetSize(IntPtr View, float Width, float Height); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_SetRotation(IntPtr View, float Angle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_SetViewport(IntPtr View, FloatRect Viewport); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_Reset(IntPtr View, FloatRect Rectangle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfView_GetCenterX(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfView_GetCenterY(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfView_GetWidth(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfView_GetHeight(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfView_GetRotation(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern FloatRect sfView_GetViewport(IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_Move(IntPtr View, float OffsetX, float OffsetY); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_Rotate(IntPtr View, float Angle); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfView_Zoom(IntPtr View, float Factor); #endregion } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using DevExpress.XtraPivotGrid; using EIDSS.RAM_DB.Components; using EIDSS.RAM_DB.Views; using bv.common; using bv.common.Configuration; using bv.common.Core; using bv.common.db.Core; using eidss.model.Core; using eidss.model.Resources; namespace EIDSS.RAM.Presenters.RamPivotGrid.PivotSummary { public class CustomSummaryHandler { public static readonly string m_NumberFormat; private readonly string m_NoStatInfo; private readonly string m_Unsupported; private readonly IRamPivotGridView m_RamPivotGrid; private bool m_IsLookupException; static CustomSummaryHandler() { string separator = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator; string format = Config.GetSetting("AvrNumericFormat"); m_NumberFormat = string.Format(string.IsNullOrEmpty(format) ? "0{0}00" : format, separator); } public CustomSummaryHandler(IRamPivotGridView ramPivotGrid) { Utils.CheckNotNull(ramPivotGrid, "ramPivotGrid"); m_RamPivotGrid = ramPivotGrid; m_NoStatInfo = EidssMessages.Get("strNoStatsCustomAggregate", "No information"); m_Unsupported = EidssMessages.Get("strUnsupportedCustomAggregate", "Unsupported Aggregate Function"); NameSummaryTypeDictionary = new Dictionary<string, CustomSummaryType>(); } #region properties public Dictionary<string, CustomSummaryType> NameSummaryTypeDictionary { get; set; } public static string NumberFormat { get { return m_NumberFormat; } } #endregion #region Process Summary public void OnCustomSummary(object sender, PivotGridCustomSummaryEventArgsWrapper e) { try { if (m_RamPivotGrid.LayoutRestoring) { return; } CustomSummaryType summaryType; if (!TryGetSummaryType(e, out summaryType)) { return; } PivotDrillDownDataSource ds = e.CreateDrillDownDataSource(); if (ProcessSumSummary(e, ds, summaryType)) { return; } if (ProcessPercentSummary(e, ds, summaryType)) { return; } if (ProcessProportionSummary(e, ds, summaryType)) { return; } if (ProcessMinSummary(e, ds, summaryType)) { return; } if (ProcessMaxSummary(e, ds, summaryType)) { return; } if (ProcessStatSummary(e, ds, summaryType)) { return; } if (ProcessPopulationSummary(e, ds, summaryType)) { return; } if (ProcessPopulationGenderSummary(e, ds, summaryType)) { return; } if (ProcessPopulationAgeGroupGenderSummary(e, ds, summaryType)) { return; } e.CustomValue = m_Unsupported; } catch (Exception ex) { e.CustomValue = ex; Trace.WriteLine(ex); } } private static bool ProcessSumSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.Sum) { return false; } e.CustomValue = GetCountOrSum(e, ds); return true; } private static bool ProcessPercentSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if ((summaryType != CustomSummaryType.PercentOfColumn) && (summaryType != CustomSummaryType.PercentOfRow)) { return false; } e.CustomValue = GetCountOrSum(e, ds); return true; } private static bool ProcessProportionSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if ((summaryType != CustomSummaryType.Proportion)) { return false; } e.CustomValue = GetCountOrSum(e, ds); return true; } private static bool ProcessMinSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.Min) { return false; } if (e.IsWeb) { //this is because e.SummaryValue is empty in web IEnumerable<IComparable> values = GetComparableValues(e, ds); e.CustomValue = FormatCustomValue(e, values.Min()); } else { e.CustomValue = FormatCustomValue(e, e.SummaryValue.Min); } return true; } private static bool ProcessMaxSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.Max) { return false; } if (e.IsWeb) { //this is because e.SummaryValue is empty in web IEnumerable<IComparable> values = GetComparableValues(e, ds); e.CustomValue = FormatCustomValue(e, values.Max()); } else { e.CustomValue = FormatCustomValue(e, e.SummaryValue.Max); } return true; } #region Process Statistics Summary private bool ProcessStatSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if ((summaryType != CustomSummaryType.Average) && (summaryType != CustomSummaryType.StdDev) && (summaryType != CustomSummaryType.Variance)) { return false; } if (ProcessNumericStatSummary(e, ds, summaryType)) { return true; } if (ProcessDefaultStatSummary(e, ds, summaryType)) { return true; } return false; } private bool ProcessDefaultStatSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if ((summaryType != CustomSummaryType.Average) && (summaryType != CustomSummaryType.StdDev) && (summaryType != CustomSummaryType.Variance)) { return false; } if (e.IsDataFieldNumeric) { return false; } ICollection<int> values; // if no row fields found, collection should contains values as result of count aggregate function int rowCount = m_RamPivotGrid.RowAreaFields.Count; if (rowCount == 0) { values = GetStatCountValues(ds, e.DataField.Index); } else { if (e.RowField == null) { values = GetStatCountValues(ds, e.DataField.Index, -1); } else { // if current row is not total row, return count value if (e.RowField.AreaIndex == rowCount - 1) { e.CustomValue = GetStatCountValues(ds, e.DataField.Index).Sum().ToString(NumberFormat); return true; } // if current row is total, collection should contains values as result of count aggregate function values = GetStatCountValues(ds, e.DataField.Index, e.RowField.AreaIndex); } } //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery var doubles = new List<double>(); foreach (int value in values) { doubles.Add(value); } // ReSharper restore LoopCanBeConvertedToQuery e.CustomValue = CalculateStatCustomValue(doubles, summaryType); return true; } private static bool ProcessNumericStatSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (!e.IsDataFieldNumeric) { return false; } if ((summaryType != CustomSummaryType.Average) && (summaryType != CustomSummaryType.StdDev) && (summaryType != CustomSummaryType.Variance)) { return false; } if (e.IsWeb) { //this is because e.SummaryValue is empty in web List<object> objects = GetValues(e, ds); List<double> values = ConvertValuesToDouble(objects); e.CustomValue = CalculateStatCustomValue(values, summaryType); return true; } switch (summaryType) { case CustomSummaryType.Average: e.CustomValue = ValueToString(e.SummaryValue.Average); return true; case CustomSummaryType.StdDev: e.CustomValue = ValueToString(e.SummaryValue.StdDev ?? 0); return true; case CustomSummaryType.Variance: double deviation = DisplayTextHandler.GetValueFrom(e.SummaryValue.StdDev); e.CustomValue = ValueToString(deviation * deviation); return true; } return true; } private static ICollection<int> GetStatCountValues(PivotDrillDownDataSource ds, int dataFieldIndex) { var values = new List<int>(); for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; int value = (row[dataFieldIndex] == null) ? 0 : 1; values.Add(value); } return values; } private ICollection<int> GetStatCountValues(PivotDrillDownDataSource ds, int dataFieldIndex, int rowAreaIndex) { int index = m_RamPivotGrid.RowAreaFields[rowAreaIndex + 1].Index; var valuesDictionary = new Dictionary<string, int>(); for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; string key = (row[index] == null) ? string.Empty : row[index].ToString(); if (!valuesDictionary.ContainsKey(key)) { valuesDictionary.Add(key, 0); } int value = (row[dataFieldIndex] == null) ? 0 : 1; valuesDictionary[key] += value; } return valuesDictionary.Values; } private static string CalculateStatCustomValue(ICollection<double> values, CustomSummaryType summaryType) { double sum = values.Sum(); double average = (values.Count == 0) ? 0 : sum / values.Count; double displayValue = 0; // ReSharper disable LoopCanBeConvertedToQuery switch (summaryType) { case CustomSummaryType.Average: displayValue = average; break; case CustomSummaryType.StdDev: case CustomSummaryType.Variance: double sumVariance = 0; foreach (double value in values) { double delta = (value - average); sumVariance += delta * delta; } double variance = (values.Count <= 1) ? 0 : sumVariance / (values.Count - 1); displayValue = (summaryType == CustomSummaryType.StdDev) ? Math.Sqrt(variance) : variance; break; } // ReSharper restore LoopCanBeConvertedToQuery return displayValue.ToString(NumberFormat); } private static List<double> ConvertValuesToDouble(List<object> values) { var result = new List<double>(); if (values.Count == 0) { return result; } //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery if (values[0] is int) { foreach (object value in values) { result.Add((int) value); } } else if (values[0] is long) { foreach (object value in values) { result.Add((long) value); } } else if (values[0] is decimal) { foreach (object value in values) { result.Add((double) (decimal) value); } } else if (values[0] is float) { foreach (object value in values) { result.Add((float) value); } } else if (values[0] is double) { foreach (object value in values) { result.Add((double) value); } } // ReSharper restore LoopCanBeConvertedToQuery return result; } private static string ValueToString(object value) { if ((value is double) || (value is float)) { return ((double) value).ToString(NumberFormat); } if (value is decimal) { return ((decimal) value).ToString(NumberFormat); } if (value is int) { return ((int) value).ToString(NumberFormat); } return (value == null) ? string.Empty : value.ToString(); } #endregion #region Process population statistics summary private bool ProcessPopulationSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if ((summaryType != CustomSummaryType.Pop10000) && (summaryType != CustomSummaryType.Pop100000)) { return false; } if (ds.RowCount == 0) { e.CustomValue = m_NoStatInfo; return true; } //Getting related Statistics Field UnitField unitField = m_RamPivotGrid.GetIdUnitFieldName(e.DataField.FieldName); //we take case date and gender from first row because in all rows case date has the same year and case gender is the same DateTime? datDateId = null; if (unitField.DateFieldName != null) { object dateObject = ds[0][unitField.DateFieldName]; datDateId = (dateObject is DateTime) ? (DateTime?) dateObject : null; } uint statSum = 0; uint valSum = 0; var admUnitList = new List<string>(); for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (!Utils.IsEmpty(row[e.DataField.Index])) { valSum++; } string strAdmUnitId = unitField.UnitFieldName != null ? Utils.Str(row[unitField.UnitFieldName]) : string.Empty; if (unitField.UnitFieldName == null || string.IsNullOrEmpty(strAdmUnitId)) { // take whole statistic for the country if no adm unit selected // it shouldn't be done each iteration of the cycle, firs one will be enought if (statSum == 0) { string countryId = string.Format("{0} ({1})", EidssSiteContext.Instance.CountryName, EidssSiteContext.Instance.CountryHascCode); statSum = GetPopulation(LookupTables.PopulationStatistics, countryId, datDateId); } } else if (!admUnitList.Contains(strAdmUnitId)) { //We have name of the field containing Rayon or whatever the hellID we have chosen as a demoninator (stridUnitFieldName) //All that's left is to figure out where the hell do we get Population related to this ID admUnitList.Add(strAdmUnitId); uint nCurrentPopulation = GetPopulation(LookupTables.PopulationStatistics, strAdmUnitId, datDateId); //Make sense to proceed only if Statistical information for the Administrative unit is present //"No information" otherwise if (nCurrentPopulation != 0) { statSum += nCurrentPopulation; } else { e.CustomValue = m_NoStatInfo; return true; } } } int denominator = (summaryType == CustomSummaryType.Pop10000) ? 10000 : 100000; SetStatisticsResultIntoCustomValue(e, denominator * valSum, statSum); return true; } private bool ProcessPopulationGenderSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.PopGender100000) { return false; } if (ds.RowCount == 0 || m_RamPivotGrid.GenderField == null) { e.CustomValue = m_NoStatInfo; return true; } return ProcessPopulationGenderAndAgeGroupGenderSummary(e, ds, summaryType); } private bool ProcessPopulationAgeGroupGenderSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.PopAgeGroupGender10000 && summaryType != CustomSummaryType.PopAgeGroupGender100000) { return false; } if (ds.RowCount == 0 || m_RamPivotGrid.AgeGroupField == null) { e.CustomValue = m_NoStatInfo; return true; } return ProcessPopulationGenderAndAgeGroupGenderSummary(e, ds, summaryType); } private bool ProcessPopulationGenderAndAgeGroupGenderSummary (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds, CustomSummaryType summaryType) { if (summaryType != CustomSummaryType.PopGender100000 && summaryType != CustomSummaryType.PopAgeGroupGender10000 && summaryType != CustomSummaryType.PopAgeGroupGender100000) { return false; } // no Administrative unit should be, because statistics by gender calculating by country // calculating count of rows with not null values uint valSum = 0; for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (!Utils.IsEmpty(row[e.DataField.Index])) { valSum++; } } //Getting related Statistics Field UnitField unitField = m_RamPivotGrid.GetIdUnitFieldName(e.DataField.FieldName); //we take case date and gender from first row because in all rows case date has the same year and case gender is the same DateTime? datDateId = null; if (unitField.DateFieldName != null) { object dateObject = ds[0][unitField.DateFieldName]; datDateId = (dateObject is DateTime) ? (DateTime?) dateObject : null; } // get statistical information for first row only (for other rows it is the same) string strGender = (m_RamPivotGrid.GenderField != null) ? Utils.Str(ds[0][m_RamPivotGrid.GenderField]) : string.Empty; uint statSum; if (summaryType == CustomSummaryType.PopGender100000) { statSum = GetPopulation(LookupTables.PopulationGenderStatistics, strGender, datDateId); } else { string strAgeGroup = (m_RamPivotGrid.AgeGroupField != null) ? Utils.Str(ds[0][m_RamPivotGrid.AgeGroupField]) : string.Empty; if (string.IsNullOrEmpty(strGender)) { DataView genderView = LookupCache.Get(LookupTables.Sex); statSum = 0; foreach (DataRowView row in genderView) { strGender = row["name"].ToString(); string key = string.Format("{0}_{1}", strAgeGroup, strGender); statSum += GetPopulation(LookupTables.PopulationAgeGroupGenderStatistics, key, datDateId); } } else { string key = string.Format("{0}_{1}", strAgeGroup, strGender); statSum = GetPopulation(LookupTables.PopulationAgeGroupGenderStatistics, key, datDateId); } } int denominator = (summaryType == CustomSummaryType.PopAgeGroupGender10000) ? 10000 : 100000; SetStatisticsResultIntoCustomValue(e, denominator * valSum, statSum); return true; } private void SetStatisticsResultIntoCustomValue(PivotGridCustomSummaryEventArgsWrapper e, double valueSum, uint statSum) { double fResult = 0; if (statSum == 0) { e.CustomValue = m_NoStatInfo; return; } fResult += valueSum / statSum; string result = Utils.Str(fResult); e.CustomValue = FormatCustomValue(e, result); } private uint GetPopulation(LookupTables tableId, string strAdmUnitId, DateTime? datDateId) { if (m_IsLookupException) { return 0; } try { string strPopulation = null; if (datDateId.HasValue) { string key = string.Format("{0}__{1:yyyy}", strAdmUnitId, datDateId); strPopulation = LookupCache.GetLookupValue(key, tableId, "intValue"); } if (Utils.IsEmpty(strPopulation)) { strPopulation = LookupCache.GetLookupValue(strAdmUnitId, tableId, "intValue"); } return (Utils.IsEmpty(strPopulation)) ? 0 : Convert.ToUInt32(strPopulation); } catch (Exception) { m_IsLookupException = true; throw; } } #endregion #endregion #region Helper methods private bool TryGetSummaryType(PivotGridCustomSummaryEventArgsWrapper e, out CustomSummaryType summaryType) { bool result = true; if (!NameSummaryTypeDictionary.TryGetValue(e.DataField.FieldName, out summaryType)) { string message = EidssMessages.Get("msgCannotFindSummaryType", "Cannot find summaryType type for column {0}"); e.CustomValue = string.Format(message, e.DataField.FieldName); result = false; } return result; } private static object GetCountOrSum(PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds) { if (e.IsWeb) { //this is because e.SummaryValue is empty in web List<object> values = GetValues(e, ds); if (!e.IsDataFieldNumeric) { return values.Count; } if (values.Count == 0) { return 0; } //note: LINQ may be too slow, so these calculations should not be converted into LINQ expression // ReSharper disable LoopCanBeConvertedToQuery if (values[0] is int) { int sum = 0; foreach (object value in values) { sum += (int) value; } return sum; } if (values[0] is long) { long sum = 0; foreach (object value in values) { sum += (long) value; } return sum; } if (values[0] is decimal) { decimal sum = 0; foreach (object value in values) { sum += (decimal) value; } return sum; } if (values[0] is float) { float sum = 0; foreach (object value in values) { sum += (float) value; } return sum; } if (values[0] is double) { double sum = 0; foreach (object value in values) { sum += (double) value; } return sum; } return 0; // ReSharper restore LoopCanBeConvertedToQuery } return e.IsDataFieldNumeric ? e.SummaryValue.Summary : e.SummaryValue.Count; } private static IEnumerable<IComparable> GetComparableValues (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds) { var values = new List<IComparable>(); int fieldIndex = e.DataField.Index; for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (row[fieldIndex] != null) { object value = row[fieldIndex]; var comparable = value as IComparable; if (comparable != null) { values.Add(comparable); } } } return values; } private static List<object> GetValues (PivotGridCustomSummaryEventArgsWrapper e, PivotDrillDownDataSource ds) { var values = new List<object>(); int fieldIndex = e.DataField.Index; for (int i = 0; i < ds.RowCount; i++) { PivotDrillDownDataRow row = ds[i]; if (row[fieldIndex] != null) { values.Add(row[fieldIndex]); } } return values; } private static object FormatCustomValue(PivotGridCustomSummaryEventArgsWrapper e, object result) { return (result != null) && (result is DateTime) ? ((DateTime) result).ToString(e.DataField.GroupInterval) : result; } #endregion } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy { public class CallHierarchyTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task InvokeOnMethod() { var text = @" namespace N { class C { void F$$oo() { } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task InvokeOnProperty() { var text = @" namespace N { class C { public int F$$oo { get; set;} } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task InvokeOnEvent() { var text = @" using System; namespace N { class C { public event EventHandler Fo$$o; } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task Method_FindCalls() { var text = @" namespace N { class C { void F$$oo() { } } class G { void Main() { var c = new C(); c.Foo(); } void Main2() { var c = new C(); c.Foo(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main()", "N.G.Main2()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task Method_InterfaceImplementation() { var text = @" namespace N { interface I { void Foo(); } class C : I { public void F$$oo() { } } class G { void Main() { I c = new C(); c.Foo(); } void Main2() { var c = new C(); c.Foo(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Foo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main2()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Foo()"), new[] { "N.G.Main()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task Method_CallToOverride() { var text = @" namespace N { class C { protected virtual void F$$oo() { } } class D : C { protected override void Foo() { } void Bar() { C c; c.Foo() } void Baz() { D d; d.Foo(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.D.Bar()" }); testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" }); } [WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task Method_CallToBase() { var text = @" namespace N { class C { protected virtual void Foo() { } } class D : C { protected override void Foo() { } void Bar() { C c; c.Foo() } void Baz() { D d; d.Fo$$o(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.D.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Foo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.D.Baz()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Foo()"), new[] { "N.D.Bar()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task FieldInitializers() { var text = @" namespace N { class C { public int foo = Foo(); protected int Foo$$() { return 0; } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo") }); testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { EditorFeaturesResources.Initializers }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task FieldReferences() { var text = @" namespace N { class C { public int f$$oo = Foo(); protected int Foo() { foo = 3; } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.foo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "foo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "foo"), new[] { "N.C.Foo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task PropertyGet() { var text = @" namespace N { class C { public int val { g$$et { return 0; } } public int foo() { var x = this.val; } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.foo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task Generic() { var text = @" namespace N { class C { public int gen$$eric<T>(this string generic, ref T stuff) { return 0; } public int foo() { int i; generic("", ref i); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.foo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task ExtensionMethods() { var text = @" namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var x = ""string""; x.BarStr$$ing(); } } public static class Extensions { public static string BarString(this string s) { return s; } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task GenericExtensionMethods() { var text = @" using System.Collections.Generic; using System.Linq; namespace N { class Program { static void Main(string[] args) { List<int> x = new List<int>(); var z = x.Si$$ngle(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task InterfaceImplementors() { var text = @" namespace N { interface I { void Fo$$o(); } class C : I { public async Task Foo() { } } class G { void Main() { I c = new C(); c.Foo(); } void Main2() { var c = new C(); c.Foo(); } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.I.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), string.Format(EditorFeaturesResources.Implements_0, "Foo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), new[] { "N.G.Main()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Foo"), new[] { "N.C.Foo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task NoFindOverridesOnSealedMethod() { var text = @" namespace N { class C { void F$$oo() { } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task FindOverrides() { var text = @" namespace N { class C { public virtual void F$$oo() { } } class G : C { public override void Foo() { } } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Foo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Foo"), EditorFeaturesResources.Overrides_ }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Foo()" }); } [WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")] [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public async Task AbstractMethodInclusionToOverrides() { var text = @" using System; abstract class Base { public abstract void $$M(); } class Derived : Base { public override void M() { throw new NotImplementedException(); } }"; var testState = await CallHierarchyTestState.CreateAsync(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" }); } } }
using NUnit.Framework; 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 Term = Lucene.Net.Index.Term; /// <summary> /// TestExplanations subclass focusing on basic query types /// </summary> [TestFixture] public class TestSimpleExplanations : TestExplanations { // we focus on queries that don't rewrite to other queries. // if we get those covered well, then the ones that rewrite should // also be covered. /* simple term tests */ [Test] public virtual void TestT1() { Qtest(new TermQuery(new Term(FIELD, "w1")), new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestT2() { TermQuery termQuery = new TermQuery(new Term(FIELD, "w1")); termQuery.Boost = 100; Qtest(termQuery, new int[] { 0, 1, 2, 3 }); } /* MatchAllDocs */ [Test] public virtual void TestMA1() { Qtest(new MatchAllDocsQuery(), new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMA2() { Query q = new MatchAllDocsQuery(); q.Boost = 1000; Qtest(q, new int[] { 0, 1, 2, 3 }); } /* some simple phrase tests */ [Test] public virtual void TestP1() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Add(new Term(FIELD, "w1")); phraseQuery.Add(new Term(FIELD, "w2")); Qtest(phraseQuery, new int[] { 0 }); } [Test] public virtual void TestP2() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Add(new Term(FIELD, "w1")); phraseQuery.Add(new Term(FIELD, "w3")); Qtest(phraseQuery, new int[] { 1, 3 }); } [Test] public virtual void TestP3() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Slop = 1; phraseQuery.Add(new Term(FIELD, "w1")); phraseQuery.Add(new Term(FIELD, "w2")); Qtest(phraseQuery, new int[] { 0, 1, 2 }); } [Test] public virtual void TestP4() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Slop = 1; phraseQuery.Add(new Term(FIELD, "w2")); phraseQuery.Add(new Term(FIELD, "w3")); Qtest(phraseQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestP5() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Slop = 1; phraseQuery.Add(new Term(FIELD, "w3")); phraseQuery.Add(new Term(FIELD, "w2")); Qtest(phraseQuery, new int[] { 1, 3 }); } [Test] public virtual void TestP6() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Slop = 2; phraseQuery.Add(new Term(FIELD, "w3")); phraseQuery.Add(new Term(FIELD, "w2")); Qtest(phraseQuery, new int[] { 0, 1, 3 }); } [Test] public virtual void TestP7() { PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.Slop = 3; phraseQuery.Add(new Term(FIELD, "w3")); phraseQuery.Add(new Term(FIELD, "w2")); Qtest(phraseQuery, new int[] { 0, 1, 2, 3 }); } /* some simple filtered query tests */ [Test] public virtual void TestFQ1() { Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")), new ItemizedFilter(new int[] { 0, 1, 2, 3 })), new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestFQ2() { Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")), new ItemizedFilter(new int[] { 0, 2, 3 })), new int[] { 0, 2, 3 }); } [Test] public virtual void TestFQ3() { Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 })), new int[] { 3 }); } [Test] public virtual void TestFQ4() { TermQuery termQuery = new TermQuery(new Term(FIELD, "xx")); termQuery.Boost = 1000; Qtest(new FilteredQuery(termQuery, new ItemizedFilter(new int[] { 1, 3 })), new int[] { 3 }); } [Test] public virtual void TestFQ6() { Query q = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 })); q.Boost = 1000; Qtest(q, new int[] { 3 }); } /* ConstantScoreQueries */ [Test] public virtual void TestCSQ1() { Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 1, 2, 3 })); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestCSQ2() { Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 1, 3 })); Qtest(q, new int[] { 1, 3 }); } [Test] public virtual void TestCSQ3() { Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 2 })); q.Boost = 1000; Qtest(q, new int[] { 0, 2 }); } /* DisjunctionMaxQuery */ [Test] public virtual void TestDMQ1() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f); q.Add(new TermQuery(new Term(FIELD, "w1"))); q.Add(new TermQuery(new Term(FIELD, "w5"))); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestDMQ2() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); q.Add(new TermQuery(new Term(FIELD, "w1"))); q.Add(new TermQuery(new Term(FIELD, "w5"))); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestDMQ3() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); q.Add(new TermQuery(new Term(FIELD, "QQ"))); q.Add(new TermQuery(new Term(FIELD, "w5"))); Qtest(q, new int[] { 0 }); } [Test] public virtual void TestDMQ4() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); q.Add(new TermQuery(new Term(FIELD, "QQ"))); q.Add(new TermQuery(new Term(FIELD, "xx"))); Qtest(q, new int[] { 2, 3 }); } [Test] public virtual void TestDMQ5() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); booleanQuery.Add(new TermQuery(new Term(FIELD, "QQ")), Occur.MUST_NOT); q.Add(booleanQuery); q.Add(new TermQuery(new Term(FIELD, "xx"))); Qtest(q, new int[] { 2, 3 }); } [Test] public virtual void TestDMQ6() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), Occur.MUST_NOT); booleanQuery.Add(new TermQuery(new Term(FIELD, "w3")), Occur.SHOULD); q.Add(booleanQuery); q.Add(new TermQuery(new Term(FIELD, "xx"))); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestDMQ7() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), Occur.MUST_NOT); booleanQuery.Add(new TermQuery(new Term(FIELD, "w3")), Occur.SHOULD); q.Add(booleanQuery); q.Add(new TermQuery(new Term(FIELD, "w2"))); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestDMQ8() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5")); boostedQuery.Boost = 100; booleanQuery.Add(boostedQuery, Occur.SHOULD); q.Add(booleanQuery); TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx")); xxBoostedQuery.Boost = 100000; q.Add(xxBoostedQuery); Qtest(q, new int[] { 0, 2, 3 }); } [Test] public virtual void TestDMQ9() { DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5")); boostedQuery.Boost = 100; booleanQuery.Add(boostedQuery, Occur.SHOULD); q.Add(booleanQuery); TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx")); xxBoostedQuery.Boost = 0; q.Add(xxBoostedQuery); Qtest(q, new int[] { 0, 2, 3 }); } /* MultiPhraseQuery */ [Test] public virtual void TestMPQ1() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1" })); q.Add(Ta(new string[] { "w2", "w3", "xx" })); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMPQ2() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1" })); q.Add(Ta(new string[] { "w2", "w3" })); Qtest(q, new int[] { 0, 1, 3 }); } [Test] public virtual void TestMPQ3() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1", "xx" })); q.Add(Ta(new string[] { "w2", "w3" })); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMPQ4() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1" })); q.Add(Ta(new string[] { "w2" })); Qtest(q, new int[] { 0 }); } [Test] public virtual void TestMPQ5() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1" })); q.Add(Ta(new string[] { "w2" })); q.Slop = 1; Qtest(q, new int[] { 0, 1, 2 }); } [Test] public virtual void TestMPQ6() { MultiPhraseQuery q = new MultiPhraseQuery(); q.Add(Ta(new string[] { "w1", "w3" })); q.Add(Ta(new string[] { "w2" })); q.Slop = 1; Qtest(q, new int[] { 0, 1, 2, 3 }); } /* some simple tests of boolean queries containing term queries */ [Test] public virtual void TestBQ1() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); query.Add(new TermQuery(new Term(FIELD, "w2")), Occur.MUST); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ2() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.MUST); query.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); Qtest(query, new int[] { 2, 3 }); } [Test] public virtual void TestBQ3() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); query.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ4() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); innerQuery.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ5() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.MUST); innerQuery.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ6() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.MUST_NOT); innerQuery.Add(new TermQuery(new Term(FIELD, "w5")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.MUST_NOT); Qtest(outerQuery, new int[] { 1, 2, 3 }); } [Test] public virtual void TestBQ7() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.SHOULD); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.MUST_NOT); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.SHOULD); outerQuery.Add(innerQuery, Occur.MUST); Qtest(outerQuery, new int[] { 0 }); } [Test] public virtual void TestBQ8() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.SHOULD); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.MUST_NOT); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ9() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.MUST_NOT); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ10() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(FIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.MUST_NOT); outerQuery.Add(innerQuery, Occur.MUST); Qtest(outerQuery, new int[] { 1 }); } [Test] public virtual void TestBQ11() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1")); boostedQuery.Boost = 1000; query.Add(boostedQuery, Occur.SHOULD); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ14() { BooleanQuery q = new BooleanQuery(true); q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), Occur.SHOULD); q.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ15() { BooleanQuery q = new BooleanQuery(true); q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), Occur.MUST_NOT); q.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ16() { BooleanQuery q = new BooleanQuery(true); q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), Occur.SHOULD); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); booleanQuery.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); q.Add(booleanQuery, Occur.SHOULD); Qtest(q, new int[] { 0, 1 }); } [Test] public virtual void TestBQ17() { BooleanQuery q = new BooleanQuery(true); q.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); booleanQuery.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); q.Add(booleanQuery, Occur.SHOULD); Qtest(q, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestBQ19() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.MUST_NOT); query.Add(new TermQuery(new Term(FIELD, "w3")), Occur.SHOULD); Qtest(query, new int[] { 0, 1 }); } [Test] public virtual void TestBQ20() { BooleanQuery q = new BooleanQuery(); q.MinimumNumberShouldMatch = 2; q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), Occur.SHOULD); q.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); q.Add(new TermQuery(new Term(FIELD, "zz")), Occur.SHOULD); q.Add(new TermQuery(new Term(FIELD, "w5")), Occur.SHOULD); q.Add(new TermQuery(new Term(FIELD, "w4")), Occur.SHOULD); Qtest(q, new int[] { 0, 3 }); } /* BQ of TQ: using alt so some fields have zero boost and some don't */ [Test] public virtual void TestMultiFieldBQ1() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); query.Add(new TermQuery(new Term(ALTFIELD, "w2")), Occur.MUST); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ2() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.MUST); query.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); Qtest(query, new int[] { 2, 3 }); } [Test] public virtual void TestMultiFieldBQ3() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD); query.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ4() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w2")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ5() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), Occur.MUST); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w2")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ6() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), Occur.MUST_NOT); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w5")), Occur.SHOULD); outerQuery.Add(innerQuery, Occur.MUST_NOT); Qtest(outerQuery, new int[] { 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ7() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(ALTFIELD, "xx")), Occur.SHOULD); childLeft.Add(new TermQuery(new Term(ALTFIELD, "w2")), Occur.MUST_NOT); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(ALTFIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.SHOULD); outerQuery.Add(innerQuery, Occur.MUST); Qtest(outerQuery, new int[] { 0 }); } [Test] public virtual void TestMultiFieldBQ8() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(ALTFIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(ALTFIELD, "xx")), Occur.SHOULD); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.MUST_NOT); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.SHOULD); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ9() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); childLeft.Add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.MUST_NOT); outerQuery.Add(innerQuery, Occur.SHOULD); Qtest(outerQuery, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQ10() { BooleanQuery outerQuery = new BooleanQuery(); outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), Occur.MUST); BooleanQuery innerQuery = new BooleanQuery(); innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), Occur.SHOULD); BooleanQuery childLeft = new BooleanQuery(); childLeft.Add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST_NOT); childLeft.Add(new TermQuery(new Term(ALTFIELD, "w2")), Occur.SHOULD); innerQuery.Add(childLeft, Occur.SHOULD); BooleanQuery childRight = new BooleanQuery(); childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), Occur.MUST); childRight.Add(new TermQuery(new Term(FIELD, "w4")), Occur.MUST); innerQuery.Add(childRight, Occur.MUST_NOT); outerQuery.Add(innerQuery, Occur.MUST); Qtest(outerQuery, new int[] { 1 }); } /* BQ of PQ: using alt so some fields have zero boost and some don't */ [Test] public virtual void TestMultiFieldBQofPQ1() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Add(new Term(FIELD, "w1")); leftChild.Add(new Term(FIELD, "w2")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Add(new Term(ALTFIELD, "w1")); rightChild.Add(new Term(ALTFIELD, "w2")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 0 }); } [Test] public virtual void TestMultiFieldBQofPQ2() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Add(new Term(FIELD, "w1")); leftChild.Add(new Term(FIELD, "w3")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Add(new Term(ALTFIELD, "w1")); rightChild.Add(new Term(ALTFIELD, "w3")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 1, 3 }); } [Test] public virtual void TestMultiFieldBQofPQ3() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Slop = 1; leftChild.Add(new Term(FIELD, "w1")); leftChild.Add(new Term(FIELD, "w2")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Slop = 1; rightChild.Add(new Term(ALTFIELD, "w1")); rightChild.Add(new Term(ALTFIELD, "w2")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 0, 1, 2 }); } [Test] public virtual void TestMultiFieldBQofPQ4() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Slop = 1; leftChild.Add(new Term(FIELD, "w2")); leftChild.Add(new Term(FIELD, "w3")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Slop = 1; rightChild.Add(new Term(ALTFIELD, "w2")); rightChild.Add(new Term(ALTFIELD, "w3")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 0, 1, 2, 3 }); } [Test] public virtual void TestMultiFieldBQofPQ5() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Slop = 1; leftChild.Add(new Term(FIELD, "w3")); leftChild.Add(new Term(FIELD, "w2")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Slop = 1; rightChild.Add(new Term(ALTFIELD, "w3")); rightChild.Add(new Term(ALTFIELD, "w2")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 1, 3 }); } [Test] public virtual void TestMultiFieldBQofPQ6() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Slop = 2; leftChild.Add(new Term(FIELD, "w3")); leftChild.Add(new Term(FIELD, "w2")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Slop = 2; rightChild.Add(new Term(ALTFIELD, "w3")); rightChild.Add(new Term(ALTFIELD, "w2")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 0, 1, 3 }); } [Test] public virtual void TestMultiFieldBQofPQ7() { BooleanQuery query = new BooleanQuery(); PhraseQuery leftChild = new PhraseQuery(); leftChild.Slop = 3; leftChild.Add(new Term(FIELD, "w3")); leftChild.Add(new Term(FIELD, "w2")); query.Add(leftChild, Occur.SHOULD); PhraseQuery rightChild = new PhraseQuery(); rightChild.Slop = 1; rightChild.Add(new Term(ALTFIELD, "w3")); rightChild.Add(new Term(ALTFIELD, "w2")); query.Add(rightChild, Occur.SHOULD); Qtest(query, new int[] { 0, 1, 2, 3 }); } } }
// 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Net.Security; using System.ServiceModel.Security; namespace System.ServiceModel.Description { [DebuggerDisplay("Name={_name}, Namespace={_ns}, ContractType={_contractType}")] public class ContractDescription { private Type _callbackContractType; private string _configurationName; private Type _contractType; private XmlName _name; private string _ns; private OperationDescriptionCollection _operations; private SessionMode _sessionMode; private KeyedByTypeCollection<IContractBehavior> _behaviors = new KeyedByTypeCollection<IContractBehavior>(); private ProtectionLevel _protectionLevel; private bool _hasProtectionLevel; public ContractDescription(string name) : this(name, null) { } public ContractDescription(string name, string ns) { // the property setter validates given value this.Name = name; if (!string.IsNullOrEmpty(ns)) NamingHelper.CheckUriParameter(ns, "ns"); _operations = new OperationDescriptionCollection(); _ns = ns ?? NamingHelper.DefaultNamespace; // ns can be "" } internal string CodeName { get { return _name.DecodedName; } } [DefaultValue(null)] public string ConfigurationName { get { return _configurationName; } set { _configurationName = value; } } public Type ContractType { get { return _contractType; } set { _contractType = value; } } public Type CallbackContractType { get { return _callbackContractType; } set { _callbackContractType = value; } } public string Name { get { return _name.EncodedName; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value", SR.SFxContractDescriptionNameCannotBeEmpty)); } _name = new XmlName(value, true /*isEncoded*/); } } public string Namespace { get { return _ns; } set { if (!string.IsNullOrEmpty(value)) NamingHelper.CheckUriProperty(value, "Namespace"); _ns = value; } } public OperationDescriptionCollection Operations { get { return _operations; } } public ProtectionLevel ProtectionLevel { get { return _protectionLevel; } set { if (!ProtectionLevelHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); _protectionLevel = value; _hasProtectionLevel = true; } } public bool ShouldSerializeProtectionLevel() { return this.HasProtectionLevel; } public bool HasProtectionLevel { get { return _hasProtectionLevel; } } [DefaultValue(SessionMode.Allowed)] public SessionMode SessionMode { get { return _sessionMode; } set { if (!SessionModeHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _sessionMode = value; } } public KeyedCollection<Type, IContractBehavior> ContractBehaviors { get { return this.Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IContractBehavior> Behaviors { get { return _behaviors; } } public static ContractDescription GetContract(Type contractType) { if (contractType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); TypeLoader typeLoader = new TypeLoader(); return typeLoader.LoadContractDescription(contractType); } public static ContractDescription GetContract(Type contractType, Type serviceType) { if (contractType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); if (serviceType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceType"); TypeLoader typeLoader = new TypeLoader(); ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType); return description; } public static ContractDescription GetContract(Type contractType, object serviceImplementation) { if (contractType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); if (serviceImplementation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceImplementation"); TypeLoader typeLoader = new TypeLoader(); Type serviceType = serviceImplementation.GetType(); ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType, serviceImplementation); return description; } public Collection<ContractDescription> GetInheritedContracts() { Collection<ContractDescription> result = new Collection<ContractDescription>(); for (int i = 0; i < Operations.Count; i++) { OperationDescription od = Operations[i]; if (od.DeclaringContract != this) { ContractDescription inheritedContract = od.DeclaringContract; if (!result.Contains(inheritedContract)) { result.Add(inheritedContract); } } } return result; } internal void EnsureInvariants() { if (string.IsNullOrEmpty(this.Name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.AChannelServiceEndpointSContractSNameIsNull0)); } if (this.Namespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.AChannelServiceEndpointSContractSNamespace0)); } if (this.Operations.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxContractHasZeroOperations, this.Name))); } bool thereIsAtLeastOneInitiatingOperation = false; for (int i = 0; i < this.Operations.Count; i++) { OperationDescription operationDescription = this.Operations[i]; operationDescription.EnsureInvariants(); if (operationDescription.IsInitiating) thereIsAtLeastOneInitiatingOperation = true; if ((!operationDescription.IsInitiating) && (this.SessionMode != SessionMode.Required)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.ContractIsNotSelfConsistentItHasOneOrMore2, this.Name))); } } if (!thereIsAtLeastOneInitiatingOperation) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxContractHasZeroInitiatingOperations, this.Name))); } } internal bool IsDuplex() { for (int i = 0; i < _operations.Count; ++i) { if (_operations[i].IsServerInitiated()) { return true; } } return false; } } }
using System; 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 ReserveBankOfAustraliaTests { private readonly ICurrencyFactory _currencyFactory; private readonly ITimeProvider _timeProvider; public ReserveBankOfAustraliaTests() { 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 ConversionDirection001Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var AustralianDollar = new CurrencyInfo(new System.Globalization.RegionInfo("AU")); var PoundSterling = new CurrencyInfo(new System.Globalization.RegionInfo("GB")); var BeforeInPound = new Money(PoundSterling, 100m); var AfterInDollar = await Bank.ConvertCurrencyAsync(BeforeInPound, AustralianDollar, DateTime.Now, default).ConfigureAwait(true); Assert.True(BeforeInPound.Amount < AfterInDollar.Amount); } [Fact] public async Task ConvertCurrency001Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, 10m); var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now, default).ConfigureAwait(true); Assert.True(After.Amount > decimal.Zero); Assert.True(After.Currency == pair.CounterCurrency); } } [Fact] public async Task ConvertCurrency002Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, 10m); var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default).ConfigureAwait(true); var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now, default).ConfigureAwait(true); Assert.True(After.Amount == Before.Amount * rate); } } [Fact] public async Task ConvertCurrency003Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, 10m); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now.AddMinutes(1d), default).ConfigureAwait(true)).ConfigureAwait(true); } } [Fact] public async Task ConvertCurrency004Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var Before = new Money(pair.BaseCurrency, 10m); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now.AddDays(-20d), default).ConfigureAwait(true)).ConfigureAwait(true); } } [Fact] public async Task ConvertCurrency005Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var Armenia = new System.Globalization.RegionInfo("AM"); var Belarus = new System.Globalization.RegionInfo("BY"); var ArmenianDram = new CurrencyInfo(Armenia); var BelarusianRuble = new CurrencyInfo(Belarus); var Before = new Money(ArmenianDram, 10m); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.ConvertCurrencyAsync(Before, BelarusianRuble, DateTime.Now, default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task Fetch001Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); _ = await Bank.GetExchangeRatesAsync(DateTimeOffset.Now, default).ConfigureAwait(true); } [Fact] public async Task GetCurrencyPairs001Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); Assert.Contains(CurrencyPairs, P => P.ToString() == "USD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "CNY/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "JPY/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "EUR/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "KRW/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "GBP/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "SGD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "INR/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "THB/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "NZD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "TWD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "MYR/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "IDR/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "VND/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "HKD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "CAD/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "CHF/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "PGK/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "XDR/AUD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/USD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/CNY"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/JPY"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/EUR"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/KRW"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/GBP"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/SGD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/INR"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/THB"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/NZD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/TWD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/MYR"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/IDR"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/VND"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/HKD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/CAD"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/CHF"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/PGK"); Assert.Contains(CurrencyPairs, P => P.ToString() == "AUD/XDR"); } [Fact] public async Task GetCurrencyPairs002Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { var reversedPair = new CurrencyPair(pair.CounterCurrency, pair.BaseCurrency); Assert.Contains(CurrencyPairs, P => P == reversedPair); } } [Fact] public async Task GetCurrencyPairs003Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var PairSet = new System.Collections.Generic.HashSet<CurrencyPair>(); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { _ = PairSet.Add(pair); } Assert.True(PairSet.Count == CurrencyPairs.Count()); } [Fact] public async Task GetCurrencyPairs004Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.GetCurrencyPairsAsync(DateTime.Now.AddMinutes(10), default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task GetCurrencyPairs005Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); _ = await Assert.ThrowsAsync<ArgumentException>( async () => await Bank.GetCurrencyPairsAsync(DateTime.Now.AddDays(-20), default).ConfigureAwait(true)).ConfigureAwait(true); } [Fact] public async Task GetExchangeRate001Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { Assert.True(await Bank.GetExchangeRateAsync(pair, DateTime.Now, default).ConfigureAwait(true) > decimal.Zero); } } [Fact] public async Task GetExchangeRate002Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { _ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, DateTime.Now.AddMinutes(1d), default).ConfigureAwait(true)).ConfigureAwait(true); } } [Fact] public async Task GetExchangeRate003Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var CurrencyPairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default).ConfigureAwait(true); foreach (var pair in CurrencyPairs) { _ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, DateTime.Now.AddDays(-20d), default).ConfigureAwait(true)).ConfigureAwait(true); } } [Fact] public async Task GetExchangeRate004Async() { var Bank = new ReserveBankOfAustralia(this._currencyFactory, this._timeProvider); var Armenia = new System.Globalization.RegionInfo("AM"); var Belarus = new System.Globalization.RegionInfo("BY"); var ArmenianDram = new CurrencyInfo(Armenia); var BelarusianRuble = new CurrencyInfo(Belarus); var pair = new CurrencyPair(ArmenianDram, BelarusianRuble); _ = await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, DateTime.Now, default).ConfigureAwait(true)).ConfigureAwait(true); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using bv.common.Configuration; using bv.common.Core; using DevExpress.XtraPivotGrid; using DevExpress.XtraPivotGrid.Data; using eidss.avr.BaseComponents; using eidss.avr.db.AvrEventArgs.DevExpressEventArgsWrappers; using eidss.avr.db.Common; using eidss.avr.db.Interfaces; using eidss.avr.Tools; using eidss.model.Avr.Commands; using eidss.model.Avr.Commands.Layout; using eidss.model.Avr.Pivot; using eidss.model.Avr.View; namespace eidss.avr.PivotComponents { public class AvrPivotGridPresenter : BaseAvrPresenter { private IAvrPivotGridView m_PivotGridView; private Dictionary<string, string> m_CaptionDictionary; private DistinctCounter m_DistinctCounter; public AvrPivotGridPresenter(SharedPresenter sharedPresenter, IAvrPivotGridView view) : base(sharedPresenter) { m_PivotGridView = view; DistinctCounter = new DistinctCounter(); } public DistinctCounter DistinctCounter { get { return m_DistinctCounter; } set { if (m_DistinctCounter != null) { m_DistinctCounter.Dispose(); } m_DistinctCounter = value; } } public override void Process(Command cmd) { } public override void Dispose() { try { m_PivotGridView = null; DistinctCounter = null; } finally { base.Dispose(); } } #region Prepare Avr View Data public PivotGridDataLoadedCommand CreatePivotDataLoadedCommand(string layoutName, bool skipData = false) { var view = new AvrView(m_SharedPresenter.SharedModel.SelectedLayoutId, layoutName); CreateTotalSuffixForView(view); bool isFlat = m_PivotGridView.PivotData.VisualItems.GetLevelCount(true) == 1; CreateViewHeaderFromRowArea(view, isFlat); CreateViewHeaderFromColumnArea(view, isFlat); AddColumnsToEmptyBands(view.Bands); view.AssignOwnerAndUniquePath(); DataTable dataSource = CreateViewDataSourceStructure(view); CheckViewHeaderColumnCount(view); if (!skipData) { FillViewDataSource(view, dataSource); } var model = new AvrPivotViewModel(view, dataSource); // string viewXmlNew = AvrViewSerializer.Serialize(view); // string data = DataTableSerializer.Serialize(dataSource); return new PivotGridDataLoadedCommand(this, model); } private void CreateTotalSuffixForView(AvrView view) { List<CustomSummaryType> types = m_PivotGridView.DataAreaFields.Select(field => field.CustomSummaryType).ToList(); view.TotalSuffix = " " + m_PivotGridView.DisplayTextHandler.GetGrandTotalDisplayText(types, false); view.GrandTotalSuffix = m_PivotGridView.DisplayTextHandler.GetGrandTotalDisplayText(types, true); } private void CreateViewHeaderFromRowArea(AvrView view, bool isFlat) { DataView dvMapFieldList = AvrPivotGridHelper.GetMapFiledView(SharedPresenter.SharedModel.SelectedQueryId, true); AvrViewBand rowAreaRootBand = null; if (!isFlat && m_PivotGridView.RowAreaFields.Count > 0) { var firstField = (PivotGridFieldBase) m_PivotGridView.RowAreaFields[0]; long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(firstField.FieldName); string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(firstField.FieldName); rowAreaRootBand = new AvrViewBand(fieldId, fieldAlias, string.Empty, 100); view.Bands.Add(rowAreaRootBand); } foreach (IAvrPivotGridField field in m_PivotGridView.RowAreaFields) { AvrViewColumn column = CreateViewColumnInternal(field.FieldName, field.Caption, field.Width); column.IsRowArea = true; foreach (DataRowView rowView in dvMapFieldList) { string value = Utils.Str(rowView["FieldAlias"]); if (field.FieldName.Contains(value)) { column.GisReferenceTypeId = field.GisReferenceTypeId; column.IsAdministrativeUnit = true; column.MapDisplayOrder = rowView["intMapDisplayOrder"] is int ? (int) rowView["intMapDisplayOrder"] : int.MaxValue; } } if (rowAreaRootBand == null) { view.Columns.Add(column); } else { rowAreaRootBand.AddColumn(column); } } } private void CreateViewHeaderFromColumnArea(AvrView view, bool isFlat) { int columnItemCount = m_PivotGridView.PivotData.VisualItems.GetItemCount(true); for (int i = 0; i < columnItemCount; i++) { PivotFieldValueItem item = m_PivotGridView.PivotData.VisualItems.GetItem(true, i); if (item.Level == 0) { string displayText = item.DisplayText; if (isFlat) { string fieldName = GetFieldName(item); int width = (m_PivotGridView.ColumnAreaFields.Count == 0) ? GetFieldWidth(item) : GetBandWidth(item); AvrViewColumn column = CreateViewColumnInternal(fieldName, displayText, width); view.Columns.Add(column); } else { string bandName = GetBandName(item); string fieldName = GetFieldName(item); int width = GetFieldWidth(item); AvrViewBand band = CreateViewBandInternal(bandName, fieldName, displayText, width); view.Bands.Add(band); CreateViewBandsAndColumns(band, item); } } } } internal void CreateViewBandsAndColumns(AvrViewBand band, PivotFieldValueItem item) { Utils.CheckNotNull(band, "band"); Utils.CheckNotNull(item, "item"); var children = new List<PivotFieldValueItem>(); for (int i = 0; i < item.CellCount; i++) { children.Add(item.GetCell(i)); } bool isChildrenHasChildren = children.Any(child => child.CellCount != 0); foreach (PivotFieldValueItem child in children) { if (isChildrenHasChildren) { AvrViewBand childBand = CreateViewBand(band, child); band.Bands.Add(childBand); CreateViewBandsAndColumns(childBand, child); } else { AvrViewColumn childColumn = CreateViewColumn(band, child); band.Columns.Add(childColumn); } } } private DataTable CreateViewDataSourceStructure(AvrView view) { var dataSource = new DataTable("ViewData"); dataSource.BeginInit(); var fields = new List<IAvrPivotGridField>(); fields.AddRange(m_PivotGridView.RowAreaFields); fields.AddRange(m_PivotGridView.DataAreaFields); List<AvrViewColumn> viewColumns = GetAllViewColumns(view); foreach (AvrViewColumn viewColumn in viewColumns) { Type columnType = GetViewColumnType(viewColumn, fields); viewColumn.FieldType = GetViewColumnType(viewColumn, fields); DataColumn dataColumn = dataSource.Columns.Add(viewColumn.UniquePath, columnType); dataColumn.Caption = viewColumn.DisplayText; } dataSource.EndInit(); return dataSource; } private Type GetViewColumnType(AvrViewColumn column, IEnumerable<IAvrPivotGridField> fields) { Type type = typeof (string); string fieldName = AvrPivotGridFieldHelper.CreateFieldName(column.LayoutSearchFieldName, column.LayoutSearchFieldId); IAvrPivotGridField field = fields.FirstOrDefault(f => f.FieldName == fieldName); if (field != null && field.Area == PivotArea.DataArea) { switch (field.CustomSummaryType) { case CustomSummaryType.Average: case CustomSummaryType.Pop10000: case CustomSummaryType.Pop100000: case CustomSummaryType.PopGender100000: case CustomSummaryType.PopAgeGroupGender100000: case CustomSummaryType.PopAgeGroupGender10000: case CustomSummaryType.StdDev: case CustomSummaryType.Variance: type = typeof (double); break; case CustomSummaryType.Count: case CustomSummaryType.DistinctCount: type = typeof (long); break; case CustomSummaryType.Sum: type = field.DataType == typeof (double) || field.DataType == typeof (float) || field.DataType == typeof (decimal) ? field.DataType : typeof (long); break; case CustomSummaryType.Max: case CustomSummaryType.Min: type = GetRealFieldType(field); break; } } return type; } private Type GetRealFieldType(IAvrPivotGridField field) { Utils.CheckNotNull(field, "field"); Type type; if (field.GroupInterval.IsDate()) { switch (field.GroupInterval) { case PivotGroupInterval.DateDayOfYear: case PivotGroupInterval.DateQuarter: case PivotGroupInterval.DateWeekOfYear: case PivotGroupInterval.DateWeekOfMonth: case PivotGroupInterval.DateYear: case PivotGroupInterval.DateDay: type = typeof (int); break; case PivotGroupInterval.Date: type = typeof (DateTime); break; default: type = typeof (DateTime); break; } } else { type = field.DataType; } return type; } private void CheckViewHeaderColumnCount(AvrView view) { List<AvrViewColumn> viewColumns = GetAllViewColumns(view); if (viewColumns.Count - m_PivotGridView.RowAreaFields.Count != m_PivotGridView.Cells.ColumnCount) { throw new AvrException("Internal Error. DataArea column count isn't equal to RowArea column count."); } } private void FillViewDataSource(AvrView view, DataTable dataSource) { if (m_PivotGridView.Cells.RowCount > 0) { Dictionary<string, CustomSummaryType> summaryTypes = m_PivotGridView.DataAreaFields.ToDictionary(field => field.FieldName, field => field.CustomSummaryType); dataSource.BeginLoadData(); for (int rowIndex = 0; rowIndex < m_PivotGridView.Cells.RowCount; rowIndex++) { DataRow dataRow = dataSource.NewRow(); bool isRowAreaCreated = false; for (int columnIndex = 0; columnIndex < m_PivotGridView.Cells.ColumnCount; columnIndex++) { PivotCellEventArgs cellInfo = m_PivotGridView.Cells.GetCellInfo(columnIndex, rowIndex); if (cellInfo != null) { if (!isRowAreaCreated) { isRowAreaCreated = CreateRowAreaCells(view, cellInfo, m_PivotGridView.RowAreaFields, dataRow); } int currentRowIndex = m_PivotGridView.RowAreaFields.Count + columnIndex; CreateDataAreaCell(dataRow, currentRowIndex, cellInfo, summaryTypes); } } dataSource.Rows.Add(dataRow); } dataSource.EndLoadData(); dataSource.AcceptChanges(); } } private bool CreateRowAreaCells (AvrView view, PivotCellEventArgs cellInfo, List<IAvrPivotGridField> rowAreaFields, DataRow dataRow) { PivotDrillDownDataSource drillDown = cellInfo.CreateDrillDownDataSource(); bool result = drillDown.RowCount > 0; if (result) { int totalIndex = 0; if (cellInfo.RowValueType == PivotGridValueType.Value) { totalIndex = rowAreaFields.Count; } else if (cellInfo.RowField != null) { totalIndex = cellInfo.RowField.AreaIndex; } for (int i = 0; i < rowAreaFields.Count; i++) { IAvrPivotGridField rowAreaField = rowAreaFields[i]; object rowAreaValue = (i < totalIndex + 1) ? drillDown[0][rowAreaField.FieldName] : string.Empty; if (rowAreaValue == null && BaseSettings.ShowAvrAsterisk && cellInfo.RowValueType == PivotGridValueType.Value) { rowAreaValue = BaseSettings.Asterisk; } var displayTextArgs = new InternalPivotCellDisplayTextEventArgs(rowAreaValue, rowAreaField, false); m_PivotGridView.DisplayTextHandler.DisplayCellText(displayTextArgs, CustomSummaryType.Max, -1); dataRow[i] = displayTextArgs.DisplayText; } if (rowAreaFields.Count > 0) { if (cellInfo.RowValueType == PivotGridValueType.GrandTotal) { dataRow[0] = view.GrandTotalSuffix; } else if (cellInfo.RowValueType != PivotGridValueType.Value) { dataRow[totalIndex] += view.TotalSuffix; } } } return result; } private static void CreateDataAreaCell (DataRow dataRow, int currentRowIndex, PivotCellEventArgs cellInfo, Dictionary<string, CustomSummaryType> summaryTypes) { object value; if (cellInfo.Value != null) { value = cellInfo.Value; } else { value = DBNull.Value; if (cellInfo.DataField != null && summaryTypes.ContainsKey(cellInfo.DataField.FieldName)) { CustomSummaryType summaryType = summaryTypes[cellInfo.DataField.FieldName]; if (summaryType != CustomSummaryType.Max && summaryType != CustomSummaryType.Min) { value = 0; } } } dataRow[currentRowIndex] = value; } internal AvrViewBand CreateViewBand(AvrViewBand parentBand, PivotFieldValueItem item) { Utils.CheckNotNull(item, "item"); string bandName = GetBandName(item); string fieldName = GetFieldName(item); int width = GetBandWidth(item); AvrViewBand band = CreateViewBandInternal(bandName, fieldName, item.DisplayText, width); if (parentBand != null) { band.IsAdministrativeUnit = parentBand.IsAdministrativeUnit; band.MapDisplayOrder = parentBand.MapDisplayOrder; band.IsRowArea = parentBand.IsRowArea; } return band; } private AvrViewBand CreateViewBandInternal(string bandName, string fieldName, string caption, int width) { long bandId = AvrPivotGridFieldHelper.GetIdFromFieldName(bandName); string bandAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(bandName); long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(fieldName); string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(fieldName); int? presicion = GetPrecisionByName(fieldName); var band = new AvrViewBand(bandId, bandAlias, caption, width, presicion) { LayoutChildSearchFieldId = fieldId, LayoutChildSearchFieldName = fieldAlias, }; return band; } internal AvrViewColumn CreateViewColumn(AvrViewBand parentBand, PivotFieldValueItem item) { Utils.CheckNotNull(item, "item"); string fieldName = GetFieldName(item); int width = GetFieldWidth(item); AvrViewColumn column = CreateViewColumnInternal(fieldName, item.DisplayText, width); if (parentBand != null) { column.IsAdministrativeUnit = parentBand.IsAdministrativeUnit; column.MapDisplayOrder = parentBand.MapDisplayOrder; column.IsRowArea = parentBand.IsRowArea; } return column; } private AvrViewColumn CreateViewColumnInternal(string fieldName, string caption, int width) { long fieldId = AvrPivotGridFieldHelper.GetIdFromFieldName(fieldName); string fieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromFieldName(fieldName); int? presicion = GetPrecisionByName(fieldName); var column = new AvrViewColumn(fieldId, fieldAlias, caption, width, presicion); return column; } private int? GetPrecisionByName(string fieldName) { var field = m_PivotGridView.BaseFields.GetFieldByName("field" + fieldName) as IAvrPivotGridField; int? presicion = (field == null || field.IsDateTimeField) ? null : field.Precision; return presicion; } internal static int GetFieldWidth(PivotFieldValueItem item) { PivotFieldItemBase field = GetCorrespondingField(item, true); return field == null ? AvrView.DefaultFieldWidth : field.Width; } internal static int GetBandWidth(PivotFieldValueItem item) { PivotFieldItemBase field = GetCorrespondingField(item, false); return field == null ? AvrView.DefaultFieldWidth : field.Width; } internal static string GetFieldName(PivotFieldValueItem item) { return GetName(item, true); } internal static string GetBandName(PivotFieldValueItem item) { return GetName(item, false); } private static string GetName(PivotFieldValueItem item, bool isColumn) { PivotFieldItemBase field = GetCorrespondingField(item, isColumn); return field == null ? string.Empty : field.FieldName; } private static PivotFieldItemBase GetCorrespondingField(PivotFieldValueItem item, bool isColumn) { Utils.CheckNotNull(item, "item"); PivotFieldItemBase primaryField = isColumn ? item.DataField : item.ColumnField; PivotFieldItemBase secondaryField = isColumn ? item.ColumnField : item.DataField; PivotFieldItemBase field = null; if (primaryField != null) { field = primaryField; } else if (secondaryField != null) { field = secondaryField; } return field; } internal static List<AvrViewColumn> GetAllViewColumns(AvrView view) { List<AvrViewColumn> viewColumns = (view.Bands.Count == 0) ? view.Columns : GetAllBandColumns(view.Bands); return viewColumns; } internal static List<AvrViewColumn> GetAllBandColumns(IEnumerable<AvrViewBand> avrViewBands) { var colums = new List<AvrViewColumn>(); foreach (AvrViewBand band in avrViewBands) { colums.AddRange(band.Columns.Count == 0 ? GetAllBandColumns(band.Bands) : band.Columns); } return colums; } internal static void AddColumnsToEmptyBands(IEnumerable<AvrViewBand> avrViewBands) { foreach (AvrViewBand band in avrViewBands) { if (band.Bands.Count == 0 && band.Columns.Count == 0) { var column = new AvrViewColumn(band.LayoutChildSearchFieldId, band.LayoutChildSearchFieldName, String.Empty, band.ColumnWidth, band.Precision) { IsAdministrativeUnit = band.IsAdministrativeUnit, MapDisplayOrder = band.MapDisplayOrder, IsRowArea = band.IsRowArea, }; band.Columns.Add(column); } else { AddColumnsToEmptyBands(band.Bands); } } } #endregion #region Pivot Captions /// <summary> /// Init captions given from data columns of data table /// </summary> public void InitPivotCaptions(DataTable data) { m_CaptionDictionary = new Dictionary<string, string>(); foreach (DataColumn column in data.Columns) { m_CaptionDictionary.Add(column.ColumnName, column.Caption); } } /// <summary> /// Update captions given from internal dictionary of fields of pivot grid /// </summary> public void UpdatePivotCaptions() { if (m_CaptionDictionary == null) { return; } using (m_PivotGridView.BeginTransaction()) { foreach (PivotGridField field in m_PivotGridView.BaseFields) { if (!m_CaptionDictionary.ContainsKey(field.FieldName)) { throw new AvrException("Pivot caption dictionary doesn't contains field " + field.FieldName); } field.Caption = m_CaptionDictionary[field.FieldName]; } } } #endregion } }
using McMaster.Extensions.CommandLineUtils; using OpenKh.Kh2; using OpenKh.Common; using System; using System.ComponentModel.DataAnnotations; using System.IO; using System.Reflection; using System.Linq; using OpenKh.Kh2.Utils; using OpenKh.Command.DoctChanger.Utils; namespace OpenKh.Command.DoctChanger { [Command("OpenKh.Command.DoctChanger")] [VersionOptionFromMember("--version", MemberName = nameof(GetVersion))] [Subcommand(typeof(UseThisDoctCommand), typeof(CreateDoctForMapCommand) , typeof(CreateDummyDoctCommand) , typeof(ReadDoctCommand), typeof(ReadMapDoctCommand) , typeof(ShowStatsCommand) , typeof(DumpDoctCommand))] class Program { static int Main(string[] args) { try { return CommandLineApplication.Execute<Program>(args); } catch (FileNotFoundException e) { Console.WriteLine($"The file {e.FileName} cannot be found. The program will now exit."); return 1; } catch (Exception e) { Console.WriteLine($"FATAL ERROR: {e.Message}\n{e.StackTrace}"); return 1; } } protected int OnExecute(CommandLineApplication app) { app.ShowHelp(); return 1; } private static string GetVersion() => typeof(Program).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; [HelpOption] [Command(Description = "map file: replace doct with your doct")] private class UseThisDoctCommand { [Required] [DirectoryExists] [Argument(0, Description = "Input map dir")] public string Input { get; set; } [Required] [DirectoryExists] [Argument(1, Description = "Output map dir")] public string Output { get; set; } [Required] [FileExists] [Argument(2, Description = "DOCT file input")] public string DoctIn { get; set; } protected int OnExecute(CommandLineApplication app) { var doctBin = File.ReadAllBytes(DoctIn); foreach (var mapIn in Directory.GetFiles(Input, "*.map")) { Console.WriteLine(mapIn); var mapOut = Path.Combine(Output, Path.GetFileName(mapIn)); var entries = File.OpenRead(mapIn).Using(s => Bar.Read(s)) .Select( it => { if (it.Type == Bar.EntryType.DrawOctalTree) { it.Stream = new MemoryStream(doctBin, false); } return it; } ) .ToArray(); File.Create(mapOut).Using(s => Bar.Write(s, entries)); } return 0; } } private static void SummaryDoct(Doct doct, string file, TextWriter writer) { writer.WriteLine($"# DOCT ({Path.GetFileName(file)})"); writer.WriteLine(); writer.WriteLine($"- Version: {doct.Header.Version}"); writer.WriteLine($"- Unk2: {doct.Header.Unk2}"); writer.WriteLine(); writer.WriteLine("## Entry1"); writer.WriteLine(); writer.WriteLine("```"); foreach (var pair in doct.Entry1List.Select((it, index) => (it, index))) { writer.WriteLine($"{pair.index,4}:{pair.it}"); } writer.WriteLine("```"); writer.WriteLine(); writer.WriteLine("## Entry2"); writer.WriteLine(); writer.WriteLine("```"); foreach (var pair in doct.Entry2List.Select((it, index) => (it, index))) { writer.WriteLine($"{pair.index,4}:{pair.it}"); } writer.WriteLine("```"); } [HelpOption] [Command(Description = "doct file: read")] private class ReadDoctCommand { [Required] [FileExists] [Argument(0, Description = "DOCT file input")] public string DoctIn { get; set; } protected int OnExecute(CommandLineApplication app) { var doct = File.OpenRead(DoctIn).Using(s => Doct.Read(s)); SummaryDoct(doct, DoctIn, Console.Out); return 0; } } [HelpOption] [Command(Description = "doct file: dump")] private class DumpDoctCommand { [Required] [FileExists] [Argument(0, Description = "DOCT file input")] public string DoctIn { get; set; } protected int OnExecute(CommandLineApplication app) { var doct = File.OpenRead(DoctIn).Using(s => Doct.Read(s)); new DumpDoctUtil(doct, Console.Out); return 0; } } [HelpOption] [Command(Description = "map file: read doct")] private class ReadMapDoctCommand { [Required] [FileExists] [Argument(0, Description = "Map file input")] public string MapIn { get; set; } protected int OnExecute(CommandLineApplication app) { var doctBin = File.ReadAllBytes(MapIn); var entries = File.OpenRead(MapIn).Using(s => Bar.Read(s)); var doctEntry = entries.Single(it => it.Type == Bar.EntryType.DrawOctalTree); var doct = Doct.Read(doctEntry.Stream); SummaryDoct(doct, MapIn, Console.Out); return 0; } } [HelpOption] [Command(Description = "doct file: create dummy")] private class CreateDummyDoctCommand { [Required] [Argument(0, Description = "DOCT file output")] public string DoctOut { get; set; } protected int OnExecute(CommandLineApplication app) { var doct = new Doct(); doct.Entry1List.Add(new Doct.Entry1 { }); doct.Entry2List.Add(new Doct.Entry2 { }); File.Create(DoctOut).Using(s => Doct.Write(s, doct)); return 0; } } [HelpOption] [Command(Description = "map file: create and set unoptimized doct for rendering entire map")] private class CreateDoctForMapCommand { [Required] [Argument(0, Description = "Map file input")] public string MapIn { get; set; } [Argument(1, Description = "Map file output. Default output is same file name at current folder")] public string MapOut { get; set; } private static bool IsMapModel(Bar.Entry entry) => entry.Type == Bar.EntryType.Model && entry.Name == "MAP"; private static bool IsDoct(Bar.Entry entry) => entry.Type == Bar.EntryType.DrawOctalTree; protected int OnExecute(CommandLineApplication app) { MapOut = Path.GetFullPath(MapOut ?? Path.GetFileName(MapIn)); Console.WriteLine($"Output map file: {MapOut}"); var entries = File.OpenRead(MapIn).Using(s => Bar.Read(s).ToArray()); var mapModel = Mdlx.Read(entries.Single(IsMapModel).Stream); var numVifPackets = mapModel.MapModel.VifPackets.Count; var numAlb2Groups = mapModel.MapModel.vifPacketRenderingGroup.Count; Console.WriteLine($"numVifPackets: {numVifPackets:#,##0}"); Console.WriteLine($"numAlb2Groups: {numAlb2Groups:#,##0}"); Console.WriteLine($"Note: this tool will build a unoptimized doct that renders all ALB2 {numAlb2Groups:#,##0} groups."); var doctStream = new MemoryStream(); { var doct = new Doct(); doct.Entry1List.Add( new Doct.Entry1 { Entry2Index = 0, Entry2LastIndex = Convert.ToUInt16(numAlb2Groups), // max 65535 } ); const float WorldBounds = 18000; doct.Entry2List.AddRange( Enumerable.Range(0, numAlb2Groups) .Select( index => new Doct.Entry2 { BoundingBox = new BoundingBox( new System.Numerics.Vector3(-WorldBounds), new System.Numerics.Vector3(WorldBounds) ) } ) ); Doct.Write(doctStream, doct); doctStream.Position = 0; } foreach (var entry in entries.Where(IsDoct)) { Console.WriteLine("DOCT entry replaced."); entry.Stream = doctStream; } File.Create(MapOut).Using(s => Bar.Write(s, entries)); Console.WriteLine("Output map file is written successfully."); return 0; } } [HelpOption] [Command(Description = "doct file: show stats")] private class ShowStatsCommand { [Required] [FileExists] [Argument(0, Description = "Input map/doct file (decided by file extension: `.map` or not)")] public string InputFile { get; set; } protected int OnExecute(CommandLineApplication app) { var isMap = Path.GetExtension(InputFile).ToLowerInvariant() == ".map"; if (isMap) { foreach (var entry in File.OpenRead(InputFile).Using(Bar.Read) .Where(entry => false || entry.Type == Bar.EntryType.DrawOctalTree ) ) { Console.WriteLine($"# {entry.Name}:{entry.Index} ({entry.Type})"); PrintSummary(Doct.Read(entry.Stream)); Console.WriteLine(); } } else { PrintSummary(File.OpenRead(InputFile).Using(Doct.Read)); } return 0; } private void PrintSummary(Doct coct) { Console.WriteLine($"{coct.Entry1List.Count,8:#,##0} drawing mesh groups."); Console.WriteLine($"{coct.Entry2List.Count,8:#,##0} drawing meshes."); } } } }
// 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.Data; namespace WebsitePanel.Portal { /// <summary> /// Summary description for ServerItemsHelper /// </summary> public class ServiceItemsHelper { #region Web Sites DataSet dsItemsPaged; public int GetServiceItemsPagedCount(int packageId, string groupName, string typeName, int serverId, bool recursive, string filterColumn, string filterValue) { return (int)dsItemsPaged.Tables[0].Rows[0][0]; } public DataTable GetServiceItemsPaged(int packageId, string groupName, string typeName, int serverId, bool recursive, string filterColumn, string filterValue, int maximumRows, int startRowIndex, string sortColumn) { dsItemsPaged = ES.Services.Packages.GetRawPackageItemsPaged(packageId, groupName, typeName, serverId, recursive, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsItemsPaged.Tables[1]; } #endregion #region Web Sites DataSet dsWebSitesPaged; public int GetWebSitesPagedCount(string filterColumn, string filterValue) { return (int)dsWebSitesPaged.Tables[0].Rows[0][0]; } public DataTable GetWebSitesPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsWebSitesPaged = ES.Services.WebServers.GetRawWebSitesPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsWebSitesPaged.Tables[1]; } #endregion #region Ftp Accounts DataSet dsFtpAccountsPaged; public int GetFtpAccountsPagedCount(string filterColumn, string filterValue) { return (int)dsFtpAccountsPaged.Tables[0].Rows[0][0]; } public DataTable GetFtpAccountsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsFtpAccountsPaged = ES.Services.FtpServers.GetRawFtpAccountsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsFtpAccountsPaged.Tables[1]; } #endregion #region Mail Accounts DataSet dsMailAccountsPaged; public int GetMailAccountsPagedCount(string filterColumn, string filterValue) { return (int)dsMailAccountsPaged.Tables[0].Rows[0][0]; } public DataTable GetMailAccountsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsMailAccountsPaged = ES.Services.MailServers.GetRawMailAccountsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsMailAccountsPaged.Tables[1]; } #endregion #region Mail Forwardings DataSet dsMailForwardingsPaged; public int GetMailForwardingsPagedCount(string filterColumn, string filterValue) { return (int)dsMailForwardingsPaged.Tables[0].Rows[0][0]; } public DataTable GetMailForwardingsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsMailForwardingsPaged = ES.Services.MailServers.GetRawMailForwardingsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsMailForwardingsPaged.Tables[1]; } #endregion #region Mail Groups DataSet dsMailGroupsPaged; public int GetMailGroupsPagedCount(string filterColumn, string filterValue) { return (int)dsMailGroupsPaged.Tables[0].Rows[0][0]; } public DataTable GetMailGroupsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsMailGroupsPaged = ES.Services.MailServers.GetRawMailGroupsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsMailGroupsPaged.Tables[1]; } #endregion #region Mail Lists DataSet dsMailListsPaged; public int GetMailListsPagedCount(string filterColumn, string filterValue) { return (int)dsMailListsPaged.Tables[0].Rows[0][0]; } public DataTable GetMailListsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsMailListsPaged = ES.Services.MailServers.GetRawMailListsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsMailListsPaged.Tables[1]; } #endregion #region Mail Domains DataSet dsMailDomainsPaged; public int GetMailDomainsPagedCount(string filterColumn, string filterValue) { return (int)dsMailDomainsPaged.Tables[0].Rows[0][0]; } public DataTable GetMailDomainsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsMailDomainsPaged = ES.Services.MailServers.GetRawMailDomainsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsMailDomainsPaged.Tables[1]; } #endregion #region Databases DataSet dsSqlDatabasesPaged; public int GetSqlDatabasesPagedCount(string groupName, string filterColumn, string filterValue) { return (int)dsSqlDatabasesPaged.Tables[0].Rows[0][0]; } public DataTable GetSqlDatabasesPaged(int maximumRows, int startRowIndex, string sortColumn, string groupName, string filterColumn, string filterValue) { dsSqlDatabasesPaged = ES.Services.DatabaseServers.GetRawSqlDatabasesPaged(PanelSecurity.PackageId, groupName, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSqlDatabasesPaged.Tables[1]; } #endregion #region Database Users DataSet dsSqlUsersPaged; public int GetSqlUsersPagedCount(string groupName, string filterColumn, string filterValue) { return (int)dsSqlUsersPaged.Tables[0].Rows[0][0]; } public DataTable GetSqlUsersPaged(int maximumRows, int startRowIndex, string sortColumn, string groupName, string filterColumn, string filterValue) { dsSqlUsersPaged = ES.Services.DatabaseServers.GetRawSqlUsersPaged(PanelSecurity.PackageId, groupName, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSqlUsersPaged.Tables[1]; } #endregion #region SharePoint Users DataSet dsSharePointUsersPaged; public int GetSharePointUsersPagedCount(string filterColumn, string filterValue) { return (int)dsSharePointUsersPaged.Tables[0].Rows[0][0]; } public DataTable GetSharePointUsersPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsSharePointUsersPaged = ES.Services.SharePointServers.GetRawSharePointUsersPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSharePointUsersPaged.Tables[1]; } #endregion #region SharePoint Groups DataSet dsSharePointGroupsPaged; public int GetSharePointGroupsPagedCount(string filterColumn, string filterValue) { return (int)dsSharePointGroupsPaged.Tables[0].Rows[0][0]; } public DataTable GetSharePointGroupsPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsSharePointGroupsPaged = ES.Services.SharePointServers.GetRawSharePointGroupsPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSharePointGroupsPaged.Tables[1]; } #endregion #region Statistics Items DataSet dsStatisticsItemsPaged; public int GetStatisticsSitesPagedCount(string filterColumn, string filterValue) { return (int)dsStatisticsItemsPaged.Tables[0].Rows[0][0]; } public DataTable GetStatisticsSitesPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsStatisticsItemsPaged = ES.Services.StatisticsServers.GetRawStatisticsSitesPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsStatisticsItemsPaged.Tables[1]; } #endregion #region SharePoint Sites DataSet dsSharePointSitesPaged; public int GetSharePointSitesPagedCount(string filterColumn, string filterValue) { return (int)dsSharePointSitesPaged.Tables[0].Rows[0][0]; } public DataTable GetSharePointSitesPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsSharePointSitesPaged = ES.Services.SharePointServers.GetRawSharePointSitesPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSharePointSitesPaged.Tables[1]; } #endregion #region ODBC DSNs DataSet dsOdbcSourcesPaged; public int GetOdbcSourcesPagedCount(string filterColumn, string filterValue) { return (int)dsOdbcSourcesPaged.Tables[0].Rows[0][0]; } public DataTable GetOdbcSourcesPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsOdbcSourcesPaged = ES.Services.OperatingSystems.GetRawOdbcSourcesPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsOdbcSourcesPaged.Tables[1]; } #endregion #region Shared SSL Folders DataSet dsSharedSSLFoldersPaged; public int GetSharedSSLFoldersPagedCount(string filterColumn, string filterValue) { return (int)dsSharedSSLFoldersPaged.Tables[0].Rows[0][0]; } public DataTable GetSharedSSLFoldersPaged(int maximumRows, int startRowIndex, string sortColumn, string filterColumn, string filterValue) { dsSharedSSLFoldersPaged = ES.Services.WebServers.GetRawSSLFoldersPaged(PanelSecurity.PackageId, filterColumn, filterValue, sortColumn, startRowIndex, maximumRows); return dsSharedSSLFoldersPaged.Tables[1]; } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Udf { using System; using System.Collections.Generic; using System.IO; using DiscUtils.Iso9660; using DiscUtils.Vfs; /// <summary> /// Class for accessing OSTA Universal Disk Format file systems. /// </summary> public sealed class UdfReader : VfsFileSystemFacade { /// <summary> /// Initializes a new instance of the UdfReader class. /// </summary> /// <param name="data">The stream containing the UDF file system.</param> public UdfReader(Stream data) : base(new VfsUdfReader(data)) { } /// <summary> /// Initializes a new instance of the UdfReader class. /// </summary> /// <param name="data">The stream containing the UDF file system.</param> /// <param name="sectorSize">The sector size of the physical media.</param> public UdfReader(Stream data, int sectorSize) : base(new VfsUdfReader(data, sectorSize)) { } /// <summary> /// Detects if a stream contains a valid UDF file system. /// </summary> /// <param name="data">The stream to inspect.</param> /// <returns><c>true</c> if the stream contains a UDF file system, else false.</returns> public static bool Detect(Stream data) { if (data.Length < IsoUtilities.SectorSize) { return false; } long vdpos = 0x8000; // Skip lead-in byte[] buffer = new byte[IsoUtilities.SectorSize]; bool validDescriptor = true; bool foundUdfMarker = false; BaseVolumeDescriptor bvd; while (validDescriptor) { data.Position = vdpos; int numRead = Utilities.ReadFully(data, buffer, 0, IsoUtilities.SectorSize); if (numRead != IsoUtilities.SectorSize) { break; } bvd = new BaseVolumeDescriptor(buffer, 0); switch (bvd.StandardIdentifier) { case "NSR02": case "NSR03": foundUdfMarker = true; break; case "BEA01": case "BOOT2": case "CD001": case "CDW02": case "TEA01": break; default: validDescriptor = false; break; } vdpos += IsoUtilities.SectorSize; } return foundUdfMarker; } /// <summary> /// Gets UDF extended attributes for a file or directory. /// </summary> /// <param name="path">Path to the file or directory.</param> /// <returns>Array of extended attributes, which may be empty or <c>null</c> if /// there are no extended attributes.</returns> public ExtendedAttribute[] GetExtendedAttributes(string path) { VfsUdfReader realFs = GetRealFileSystem<VfsUdfReader>(); return realFs.GetExtendedAttributes(path); } private sealed class VfsUdfReader : VfsReadOnlyFileSystem<FileIdentifier, File, Directory, UdfContext> { private Stream _data; private uint _sectorSize; private LogicalVolumeDescriptor _lvd; private PrimaryVolumeDescriptor _pvd; public VfsUdfReader(Stream data) : base(null) { _data = data; if (!UdfReader.Detect(data)) { throw new InvalidDataException("Stream is not a recognized UDF format"); } // Try a number of possible sector sizes, from most common. if (ProbeSectorSize(2048)) { _sectorSize = 2048; } else if (ProbeSectorSize(512)) { _sectorSize = 512; } else if (ProbeSectorSize(4096)) { _sectorSize = 4096; } else if (ProbeSectorSize(1024)) { _sectorSize = 1024; } else { throw new InvalidDataException("Unable to detect physical media sector size"); } Initialize(); } public VfsUdfReader(Stream data, int sectorSize) : base(null) { _data = data; _sectorSize = (uint)sectorSize; if (!UdfReader.Detect(data)) { throw new InvalidDataException("Stream is not a recognized UDF format"); } Initialize(); } public override string FriendlyName { get { return "OSTA Universal Disk Format"; } } public override string VolumeLabel { get { return _lvd.LogicalVolumeIdentifier; } } public ExtendedAttribute[] GetExtendedAttributes(string path) { List<ExtendedAttribute> result = new List<ExtendedAttribute>(); File file = GetFile(path); foreach (var record in file.ExtendedAttributes) { ImplementationUseExtendedAttributeRecord implRecord = record as ImplementationUseExtendedAttributeRecord; if (implRecord != null) { result.Add(new ExtendedAttribute(implRecord.ImplementationIdentifier.Identifier, implRecord.ImplementationUseData)); } } return result.ToArray(); } /// <summary> /// Size of the Filesystem in bytes /// </summary> public override long Size { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } /// <summary> /// Used space of the Filesystem in bytes /// </summary> public override long UsedSpace { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } /// <summary> /// Available space of the Filesystem in bytes /// </summary> public override long AvailableSpace { get { throw new NotSupportedException("Filesystem size is not (yet) supported"); } } protected override File ConvertDirEntryToFile(FileIdentifier dirEntry) { return File.FromDescriptor(Context, dirEntry.FileLocation); } private void Initialize() { Context = new UdfContext() { PhysicalPartitions = new Dictionary<ushort, PhysicalPartition>(), PhysicalSectorSize = (int)_sectorSize, LogicalPartitions = new List<LogicalPartition>(), }; IBuffer dataBuffer = new StreamBuffer(_data, Ownership.None); AnchorVolumeDescriptorPointer avdp = AnchorVolumeDescriptorPointer.FromStream(_data, 256, _sectorSize); uint sector = avdp.MainDescriptorSequence.Location; bool terminatorFound = false; while (!terminatorFound) { _data.Position = sector * (long)_sectorSize; DescriptorTag dt; if (!DescriptorTag.TryFromStream(_data, out dt)) { break; } switch (dt.TagIdentifier) { case TagIdentifier.PrimaryVolumeDescriptor: _pvd = PrimaryVolumeDescriptor.FromStream(_data, sector, _sectorSize); break; case TagIdentifier.ImplementationUseVolumeDescriptor: // Not used break; case TagIdentifier.PartitionDescriptor: PartitionDescriptor pd = PartitionDescriptor.FromStream(_data, sector, _sectorSize); if (Context.PhysicalPartitions.ContainsKey(pd.PartitionNumber)) { throw new IOException("Duplicate partition number reading UDF Partition Descriptor"); } Context.PhysicalPartitions[pd.PartitionNumber] = new PhysicalPartition(pd, dataBuffer, _sectorSize); break; case TagIdentifier.LogicalVolumeDescriptor: _lvd = LogicalVolumeDescriptor.FromStream(_data, sector, _sectorSize); break; case TagIdentifier.UnallocatedSpaceDescriptor: // Not used for reading break; case TagIdentifier.TerminatingDescriptor: terminatorFound = true; break; default: break; } sector++; } // Convert logical partition descriptors into actual partition objects for (int i = 0; i < _lvd.PartitionMaps.Length; ++i) { Context.LogicalPartitions.Add(LogicalPartition.FromDescriptor(Context, _lvd, i)); } byte[] fsdBuffer = UdfUtilities.ReadExtent(Context, _lvd.FileSetDescriptorLocation); if (DescriptorTag.IsValid(fsdBuffer, 0)) { FileSetDescriptor fsd = Utilities.ToStruct<FileSetDescriptor>(fsdBuffer, 0); RootDirectory = (Directory)File.FromDescriptor(Context, fsd.RootDirectoryIcb); } } private bool ProbeSectorSize(int size) { if (_data.Length < 257 * (long)size) { return false; } _data.Position = 256 * (long)size; DescriptorTag dt; if (!DescriptorTag.TryFromStream(_data, out dt)) { return false; } return dt.TagIdentifier == TagIdentifier.AnchorVolumeDescriptorPointer && dt.TagLocation == 256; } } } }
// // 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.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.ServiceBus; using Microsoft.WindowsAzure.Management.ServiceBus.Models; namespace Microsoft.WindowsAzure.Management.ServiceBus { /// <summary> /// The Service Bus Management API is a REST API for managing Service Bus /// queues, topics, rules and subscriptions. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh780776.aspx for /// more information) /// </summary> public partial class ServiceBusManagementClient : ServiceClient<ServiceBusManagementClient>, Microsoft.WindowsAzure.Management.ServiceBus.IServiceBusManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private INamespaceOperations _namespaces; /// <summary> /// The Service Bus Management API includes operations for managing /// Service Bus namespaces. /// </summary> public virtual INamespaceOperations Namespaces { get { return this._namespaces; } } private INotificationHubOperations _notificationHubs; /// <summary> /// The Service Bus Management API includes operations for managing /// Service Bus notification hubs. /// </summary> public virtual INotificationHubOperations NotificationHubs { get { return this._notificationHubs; } } private IQueueOperations _queues; /// <summary> /// The Service Bus Management API includes operations for managing /// Service Bus queues. /// </summary> public virtual IQueueOperations Queues { get { return this._queues; } } private IRelayOperations _relays; /// <summary> /// The Service Bus Management API includes operations for managing /// Service Bus relays. /// </summary> public virtual IRelayOperations Relays { get { return this._relays; } } private ITopicOperations _topics; /// <summary> /// The Service Bus Management API includes operations for managing /// Service Bus topics for a namespace. /// </summary> public virtual ITopicOperations Topics { get { return this._topics; } } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> private ServiceBusManagementClient() : base() { this._namespaces = new NamespaceOperations(this); this._notificationHubs = new NotificationHubOperations(this); this._queues = new QueueOperations(this); this._relays = new RelayOperations(this); this._topics = new TopicOperations(this); this._apiVersion = "2013-08-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> public ServiceBusManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ServiceBusManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private ServiceBusManagementClient(HttpClient httpClient) : base(httpClient) { this._namespaces = new NamespaceOperations(this); this._notificationHubs = new NotificationHubOperations(this); this._queues = new QueueOperations(this); this._relays = new RelayOperations(this); this._topics = new TopicOperations(this); this._apiVersion = "2013-08-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ServiceBusManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ServiceBusManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ServiceBusManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ServiceBusManagementClient instance /// </summary> /// <param name='client'> /// Instance of ServiceBusManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ServiceBusManagementClient> client) { base.Clone(client); if (client is ServiceBusManagementClient) { ServiceBusManagementClient clonedClient = ((ServiceBusManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of /// thespecified operation. After calling an asynchronous operation, /// you can call Get Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim(); string baseUrl = this.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("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieves the list of regions that support the creation and /// management of Service Bus service namespaces. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj860465.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response to a request for a list of regions. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ServiceBus.Models.ServiceBusRegionsResponse> GetServiceBusRegionsAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "GetServiceBusRegionsAsync", tracingParameters); } // Construct URL string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services/servicebus/regions"; string baseUrl = this.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/atom+xml"); httpRequest.Headers.Add("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceBusRegionsResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceBusRegionsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom")); if (feedElement != null) { if (feedElement != null) { foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom"))) { ServiceBusLocation entryInstance = new ServiceBusLocation(); result.Regions.Add(entryInstance); XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom")); if (contentElement != null) { XElement regionCodeDescriptionElement = contentElement.Element(XName.Get("RegionCodeDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (regionCodeDescriptionElement != null) { XElement codeElement = regionCodeDescriptionElement.Element(XName.Get("Code", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (codeElement != null) { string codeInstance = codeElement.Value; entryInstance.Code = codeInstance; } XElement fullNameElement = regionCodeDescriptionElement.Element(XName.Get("FullName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")); if (fullNameElement != null) { string fullNameInstance = fullNameElement.Value; entryInstance.FullName = fullNameInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
#if !__MonoCS__ namespace Nancy.Tests.Unit.Bootstrapper.Base { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Routing; using Xunit; /// <summary> /// Base class for testing the basic behaviour of a bootstrapper that /// implements either of the two bootstrapper base classes. /// These tests only test basic external behaviour, they are not exhaustive; /// it is expected that additional tests specific to the bootstrapper implementation /// are also created. /// </summary> public abstract class BootstrapperBaseFixtureBase<TContainer> where TContainer : class { private readonly NancyInternalConfiguration configuration; protected abstract NancyBootstrapperBase<TContainer> Bootstrapper { get; } protected NancyInternalConfiguration Configuration { get { return this.configuration; } } protected BootstrapperBaseFixtureBase() { this.configuration = NancyInternalConfiguration.WithOverrides( builder => { builder.NancyEngine = typeof(FakeEngine); }); } [Fact] public virtual void Should_throw_if_get_engine_called_without_being_initialised() { // Given / When var result = Record.Exception(() => this.Bootstrapper.GetEngine()); result.ShouldNotBeNull(); } [Fact] public virtual void Should_resolve_engine_when_initialised() { // Given this.Bootstrapper.Initialise(); // When var result = this.Bootstrapper.GetEngine(); // Then result.ShouldNotBeNull(); result.ShouldBeOfType(typeof(INancyEngine)); } [Fact] public virtual void Should_use_types_from_config() { // Given this.Bootstrapper.Initialise(); // When var result = this.Bootstrapper.GetEngine(); // Then result.ShouldBeOfType(typeof(FakeEngine)); } [Fact] public virtual void Should_register_config_types_as_singletons() { // Given this.Bootstrapper.Initialise(); // When var result1 = this.Bootstrapper.GetEngine(); var result2 = this.Bootstrapper.GetEngine(); // Then result1.ShouldBeSameAs(result2); } [Fact] public void Should_honour_typeregistration_singleton_lifetimes() { // Given this.Bootstrapper.Initialise(); // When var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); // Then result1.Singleton.ShouldBeSameAs(result2.Singleton); } [Fact] public void Should_honour_typeregistration_transient_lifetimes() { // Given this.Bootstrapper.Initialise(); // When var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); // Then result1.Transient.ShouldNotBeSameAs(result2.Transient); } public class FakeEngine : INancyEngine { private readonly IRouteResolver resolver; private readonly IRouteCache routeCache; private readonly INancyContextFactory contextFactory; public INancyContextFactory ContextFactory { get { return this.contextFactory; } } public IRouteCache RouteCache { get { return this.routeCache; } } public IRouteResolver Resolver { get { return this.resolver; } } public Func<NancyContext, Response> PreRequestHook { get; set; } public Action<NancyContext> PostRequestHook { get; set; } public Func<NancyContext, Exception, dynamic> OnErrorHook { get; set; } public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; } public Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken) { throw new NotImplementedException(); } public FakeEngine(IRouteResolver resolver, IRouteCache routeCache, INancyContextFactory contextFactory) { if (resolver == null) { throw new ArgumentNullException("resolver", "The resolver parameter cannot be null."); } if (routeCache == null) { throw new ArgumentNullException("routeCache", "The routeCache parameter cannot be null."); } if (contextFactory == null) { throw new ArgumentNullException("contextFactory"); } this.resolver = resolver; this.routeCache = routeCache; this.contextFactory = contextFactory; } } } public class TestRegistrations : IRegistrations { public IEnumerable<TypeRegistration> TypeRegistrations { get; private set; } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; private set; } public IEnumerable<InstanceRegistration> InstanceRegistrations { get; private set; } public TestRegistrations() { this.TypeRegistrations = new[] { new TypeRegistration( typeof(Singleton), typeof(Singleton), Lifetime.Singleton), new TypeRegistration( typeof(Transient), typeof(Transient), Lifetime.Transient), }; } } public class Singleton { } public class Transient { } public class TestDependencyModule : NancyModule { public Singleton Singleton { get; set; } public Transient Transient { get; set; } public TestDependencyModule(Singleton singleton, Transient transient) { this.Singleton = singleton; this.Transient = transient; } } } #endif
// This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.VBox vbox2; private global::Gtk.Expander expander2; private global::Gtk.VBox vbox4; private global::Gtk.HSeparator hseparator1; private global::Gtk.Table table1; private global::Gtk.ComboBox _environments; private global::Gtk.SpinButton _generationsToRun; private global::Gtk.SpinButton _genomeLength; private global::Gtk.SpinButton _lifetimeIterations; private global::Gtk.SpinButton _population; private global::Gtk.Button _reset; private global::Gtk.Label _resetWarning; private global::Gtk.HSeparator hseparator2; private global::Gtk.HSeparator hseparator4; private global::Gtk.HSeparator hseparator5; private global::Gtk.HSeparator hseparator6; private global::Gtk.HSeparator hseparator7; private global::Gtk.HSeparator hseparator8; private global::Gtk.HSeparator hseparator9; private global::Gtk.Label label10; private global::Gtk.Label label11; private global::Gtk.Label label6; private global::Gtk.Label label7; private global::Gtk.Label label8; private global::Gtk.Label label9; private global::Gtk.Label GtkLabel1; private global::Gtk.HSeparator hseparator3; private global::Gtk.VBox vbox1; private global::Gtk.VBox vbox3; private global::Gtk.HBox hbox1; private global::Gtk.Label label3; private global::Gtk.Label _generationLabel; private global::Gtk.VSeparator vseparator1; private global::Gtk.Label label20; private global::Gtk.Label _foodLabel; private global::Gtk.Notebook notebook2; private global::Gtk.Table table2; private global::Gtk.Label _dCost1; private global::Gtk.Label _dCost2; private global::Gtk.Label _dining1; private global::Gtk.Label _dining2; private global::Gtk.Label _eCost1; private global::Gtk.Label _eCost2; private global::Gtk.Label _energy1; private global::Gtk.Label _energy2; private global::Gtk.Label _enzC1; private global::Gtk.Label _enzC2; private global::Gtk.Label _ep1; private global::Gtk.Label _ep2; private global::Gtk.Label _ex1; private global::Gtk.Label _ex2; private global::Gtk.Label _fEnz1; private global::Gtk.Label _fEnz2; private global::Gtk.Label _fitness1; private global::Gtk.Label _fitness2; private global::Gtk.Button _inject1; private global::Gtk.Button _inject2; private global::Gtk.Label _max1; private global::Gtk.Label _max2; private global::Gtk.Button _save1; private global::Gtk.Button _save2; private global::Gtk.Label _sEnz1; private global::Gtk.Label _sEnz2; private global::Gtk.Label _state1; private global::Gtk.Label _state2; private global::Gtk.Label label; private global::Gtk.Label label12; private global::Gtk.Label label13; private global::Gtk.Label label14; private global::Gtk.Label label15; private global::Gtk.Label label16; private global::Gtk.Label label17; private global::Gtk.Label label18; private global::Gtk.Label label25; private global::Gtk.Label label26; private global::Gtk.Label label27; private global::Gtk.Label label28; private global::Gtk.Label label4; private global::Gtk.Label label5; private global::Gtk.Label label2; private global::Gtk.Notebook notebook3; private global::Gtk.HBox hbox3; private global::Gtk.VBox vbox5; private global::Gtk.RadioButton _selection1rb; private global::Gtk.RadioButton _selection2rb; private global::Gtk.HBox hbox5; private global::Gtk.Button button2; private global::Gtk.Fixed fixed1; private global::Gtk.ScrolledWindow GtkScrolledWindow; private global::Gtk.TextView _eatDecisionText; private global::Gtk.Label label1; private global::Gtk.Label _decisionProcessing; private global::Gtk.HBox hbox4; private global::Gtk.VBox vbox6; private global::Gtk.Button _loadSim1; private global::Gtk.Button _loadSim2; private global::Gtk.Label _loadedSimulatorLabel; private global::Gtk.Button _simulate1Turn; private global::Gtk.ScrolledWindow GtkScrolledWindow1; private global::Gtk.TextView _simDescription; private global::Gtk.Label label19; private global::Gtk.HBox hbox2; private global::Gtk.Button _action; private global::Gtk.Alignment alignment3; private global::Gtk.Button button5; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("Harness"); this.WindowPosition = ((global::Gtk.WindowPosition)(1)); // Container child MainWindow.Gtk.Container+ContainerChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; this.vbox2.BorderWidth = ((uint)(3)); // Container child vbox2.Gtk.Box+BoxChild this.expander2 = new global::Gtk.Expander (null); this.expander2.CanFocus = true; this.expander2.Name = "expander2"; this.expander2.Expanded = true; // Container child expander2.Gtk.Container+ContainerChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; // Container child vbox4.Gtk.Box+BoxChild this.hseparator1 = new global::Gtk.HSeparator (); this.hseparator1.Name = "hseparator1"; this.vbox4.Add (this.hseparator1); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.hseparator1])); w1.Position = 0; w1.Expand = false; w1.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.table1 = new global::Gtk.Table (((uint)(4)), ((uint)(7)), false); this.table1.Name = "table1"; this.table1.RowSpacing = ((uint)(6)); this.table1.ColumnSpacing = ((uint)(6)); // Container child table1.Gtk.Table+TableChild this._environments = global::Gtk.ComboBox.NewText (); this._environments.Name = "_environments"; this.table1.Add (this._environments); global::Gtk.Table.TableChild w2 = ((global::Gtk.Table.TableChild)(this.table1 [this._environments])); w2.LeftAttach = ((uint)(5)); w2.RightAttach = ((uint)(6)); w2.XOptions = ((global::Gtk.AttachOptions)(4)); w2.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._generationsToRun = new global::Gtk.SpinButton (0, 10000000000, 1); this._generationsToRun.CanFocus = true; this._generationsToRun.Name = "_generationsToRun"; this._generationsToRun.Adjustment.PageIncrement = 10; this._generationsToRun.ClimbRate = 1; this._generationsToRun.Numeric = true; this._generationsToRun.Value = 10; this.table1.Add (this._generationsToRun); global::Gtk.Table.TableChild w3 = ((global::Gtk.Table.TableChild)(this.table1 [this._generationsToRun])); w3.LeftAttach = ((uint)(1)); w3.RightAttach = ((uint)(2)); w3.XOptions = ((global::Gtk.AttachOptions)(4)); w3.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._genomeLength = new global::Gtk.SpinButton (0, 10000, 1); this._genomeLength.CanFocus = true; this._genomeLength.Name = "_genomeLength"; this._genomeLength.Adjustment.PageIncrement = 10; this._genomeLength.ClimbRate = 1; this._genomeLength.Numeric = true; this._genomeLength.Value = 32; this.table1.Add (this._genomeLength); global::Gtk.Table.TableChild w4 = ((global::Gtk.Table.TableChild)(this.table1 [this._genomeLength])); w4.TopAttach = ((uint)(3)); w4.BottomAttach = ((uint)(4)); w4.LeftAttach = ((uint)(3)); w4.RightAttach = ((uint)(4)); w4.XOptions = ((global::Gtk.AttachOptions)(4)); w4.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._lifetimeIterations = new global::Gtk.SpinButton (0, 10000000000, 1); this._lifetimeIterations.CanFocus = true; this._lifetimeIterations.Name = "_lifetimeIterations"; this._lifetimeIterations.Adjustment.PageIncrement = 10; this._lifetimeIterations.ClimbRate = 1; this._lifetimeIterations.Numeric = true; this._lifetimeIterations.Value = 1000; this.table1.Add (this._lifetimeIterations); global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table1 [this._lifetimeIterations])); w5.TopAttach = ((uint)(1)); w5.BottomAttach = ((uint)(2)); w5.LeftAttach = ((uint)(1)); w5.RightAttach = ((uint)(2)); w5.XOptions = ((global::Gtk.AttachOptions)(4)); w5.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._population = new global::Gtk.SpinButton (0, 10000000000, 1); this._population.CanFocus = true; this._population.Name = "_population"; this._population.Adjustment.PageIncrement = 10; this._population.ClimbRate = 1; this._population.Numeric = true; this._population.Value = 10000; this.table1.Add (this._population); global::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.table1 [this._population])); w6.TopAttach = ((uint)(3)); w6.BottomAttach = ((uint)(4)); w6.LeftAttach = ((uint)(1)); w6.RightAttach = ((uint)(2)); w6.XOptions = ((global::Gtk.AttachOptions)(4)); w6.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._reset = new global::Gtk.Button (); this._reset.CanFocus = true; this._reset.Name = "_reset"; this._reset.UseUnderline = true; this._reset.Label = global::Mono.Unix.Catalog.GetString ("Reset"); this.table1.Add (this._reset); global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table1 [this._reset])); w7.LeftAttach = ((uint)(6)); w7.RightAttach = ((uint)(7)); w7.XOptions = ((global::Gtk.AttachOptions)(4)); w7.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this._resetWarning = new global::Gtk.Label (); this._resetWarning.Name = "_resetWarning"; this._resetWarning.LabelProp = global::Mono.Unix.Catalog.GetString ("Click Reset To Apply Changes"); this.table1.Add (this._resetWarning); global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this._resetWarning])); w8.TopAttach = ((uint)(3)); w8.BottomAttach = ((uint)(4)); w8.LeftAttach = ((uint)(4)); w8.RightAttach = ((uint)(5)); w8.XOptions = ((global::Gtk.AttachOptions)(4)); w8.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator2 = new global::Gtk.HSeparator (); this.hseparator2.Name = "hseparator2"; this.table1.Add (this.hseparator2); global::Gtk.Table.TableChild w9 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator2])); w9.TopAttach = ((uint)(2)); w9.BottomAttach = ((uint)(3)); w9.XOptions = ((global::Gtk.AttachOptions)(4)); w9.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator4 = new global::Gtk.HSeparator (); this.hseparator4.Name = "hseparator4"; this.table1.Add (this.hseparator4); global::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator4])); w10.TopAttach = ((uint)(2)); w10.BottomAttach = ((uint)(3)); w10.LeftAttach = ((uint)(1)); w10.RightAttach = ((uint)(2)); w10.XOptions = ((global::Gtk.AttachOptions)(4)); w10.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator5 = new global::Gtk.HSeparator (); this.hseparator5.Name = "hseparator5"; this.table1.Add (this.hseparator5); global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator5])); w11.TopAttach = ((uint)(2)); w11.BottomAttach = ((uint)(3)); w11.LeftAttach = ((uint)(2)); w11.RightAttach = ((uint)(3)); w11.XOptions = ((global::Gtk.AttachOptions)(4)); w11.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator6 = new global::Gtk.HSeparator (); this.hseparator6.Name = "hseparator6"; this.table1.Add (this.hseparator6); global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator6])); w12.TopAttach = ((uint)(2)); w12.BottomAttach = ((uint)(3)); w12.LeftAttach = ((uint)(3)); w12.RightAttach = ((uint)(4)); w12.XOptions = ((global::Gtk.AttachOptions)(4)); w12.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator7 = new global::Gtk.HSeparator (); this.hseparator7.Name = "hseparator7"; this.table1.Add (this.hseparator7); global::Gtk.Table.TableChild w13 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator7])); w13.TopAttach = ((uint)(2)); w13.BottomAttach = ((uint)(3)); w13.LeftAttach = ((uint)(4)); w13.RightAttach = ((uint)(5)); w13.XOptions = ((global::Gtk.AttachOptions)(4)); w13.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator8 = new global::Gtk.HSeparator (); this.hseparator8.Name = "hseparator8"; this.table1.Add (this.hseparator8); global::Gtk.Table.TableChild w14 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator8])); w14.TopAttach = ((uint)(2)); w14.BottomAttach = ((uint)(3)); w14.LeftAttach = ((uint)(5)); w14.RightAttach = ((uint)(6)); w14.XOptions = ((global::Gtk.AttachOptions)(4)); w14.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.hseparator9 = new global::Gtk.HSeparator (); this.hseparator9.Name = "hseparator9"; this.table1.Add (this.hseparator9); global::Gtk.Table.TableChild w15 = ((global::Gtk.Table.TableChild)(this.table1 [this.hseparator9])); w15.TopAttach = ((uint)(2)); w15.BottomAttach = ((uint)(3)); w15.LeftAttach = ((uint)(6)); w15.RightAttach = ((uint)(7)); w15.XOptions = ((global::Gtk.AttachOptions)(4)); w15.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label10 = new global::Gtk.Label (); this.label10.Name = "label10"; this.label10.Xalign = 1F; this.label10.LabelProp = global::Mono.Unix.Catalog.GetString ("Environment"); this.table1.Add (this.label10); global::Gtk.Table.TableChild w16 = ((global::Gtk.Table.TableChild)(this.table1 [this.label10])); w16.LeftAttach = ((uint)(4)); w16.RightAttach = ((uint)(5)); w16.XOptions = ((global::Gtk.AttachOptions)(4)); w16.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label11 = new global::Gtk.Label (); this.label11.Name = "label11"; this.label11.Ypad = 3; this.label11.LabelProp = global::Mono.Unix.Catalog.GetString ("Lifetime Iterations"); this.label11.Justify = ((global::Gtk.Justification)(3)); this.table1.Add (this.label11); global::Gtk.Table.TableChild w17 = ((global::Gtk.Table.TableChild)(this.table1 [this.label11])); w17.TopAttach = ((uint)(1)); w17.BottomAttach = ((uint)(2)); w17.XOptions = ((global::Gtk.AttachOptions)(4)); w17.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label6 = new global::Gtk.Label (); this.label6.Name = "label6"; this.label6.Ypad = 3; this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("Pause After"); this.label6.Justify = ((global::Gtk.Justification)(3)); this.table1.Add (this.label6); global::Gtk.Table.TableChild w18 = ((global::Gtk.Table.TableChild)(this.table1 [this.label6])); w18.XOptions = ((global::Gtk.AttachOptions)(4)); w18.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.Ypad = 3; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("Population Size"); this.table1.Add (this.label7); global::Gtk.Table.TableChild w19 = ((global::Gtk.Table.TableChild)(this.table1 [this.label7])); w19.TopAttach = ((uint)(3)); w19.BottomAttach = ((uint)(4)); w19.XOptions = ((global::Gtk.AttachOptions)(4)); w19.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label8 = new global::Gtk.Label (); this.label8.Name = "label8"; this.label8.Ypad = 3; this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("Genome Size"); this.table1.Add (this.label8); global::Gtk.Table.TableChild w20 = ((global::Gtk.Table.TableChild)(this.table1 [this.label8])); w20.TopAttach = ((uint)(3)); w20.BottomAttach = ((uint)(4)); w20.LeftAttach = ((uint)(2)); w20.RightAttach = ((uint)(3)); w20.XOptions = ((global::Gtk.AttachOptions)(4)); w20.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label9 = new global::Gtk.Label (); this.label9.Name = "label9"; this.label9.LabelProp = global::Mono.Unix.Catalog.GetString ("Iterations"); this.table1.Add (this.label9); global::Gtk.Table.TableChild w21 = ((global::Gtk.Table.TableChild)(this.table1 [this.label9])); w21.LeftAttach = ((uint)(2)); w21.RightAttach = ((uint)(3)); w21.XOptions = ((global::Gtk.AttachOptions)(4)); w21.YOptions = ((global::Gtk.AttachOptions)(4)); this.vbox4.Add (this.table1); global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.table1])); w22.Position = 1; w22.Expand = false; w22.Fill = false; this.expander2.Add (this.vbox4); this.GtkLabel1 = new global::Gtk.Label (); this.GtkLabel1.Name = "GtkLabel1"; this.GtkLabel1.LabelProp = global::Mono.Unix.Catalog.GetString ("Settings"); this.GtkLabel1.UseUnderline = true; this.expander2.LabelWidget = this.GtkLabel1; this.vbox2.Add (this.expander2); global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.expander2])); w24.Position = 0; w24.Expand = false; w24.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.hseparator3 = new global::Gtk.HSeparator (); this.hseparator3.Name = "hseparator3"; this.vbox2.Add (this.hseparator3); global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.hseparator3])); w25.Position = 1; w25.Expand = false; w25.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.label3 = new global::Gtk.Label (); this.label3.Name = "label3"; this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Generation"); this.hbox1.Add (this.label3); global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.label3])); w26.Position = 0; w26.Expand = false; w26.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this._generationLabel = new global::Gtk.Label (); this._generationLabel.Name = "_generationLabel"; this._generationLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.hbox1.Add (this._generationLabel); global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this._generationLabel])); w27.Position = 1; w27.Expand = false; w27.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.vseparator1 = new global::Gtk.VSeparator (); this.vseparator1.Name = "vseparator1"; this.hbox1.Add (this.vseparator1); global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vseparator1])); w28.Position = 2; w28.Expand = false; w28.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.label20 = new global::Gtk.Label (); this.label20.Name = "label20"; this.label20.LabelProp = global::Mono.Unix.Catalog.GetString ("Remaining Food"); this.hbox1.Add (this.label20); global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.label20])); w29.Position = 3; w29.Expand = false; w29.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this._foodLabel = new global::Gtk.Label (); this._foodLabel.Name = "_foodLabel"; this._foodLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("N/A"); this.hbox1.Add (this._foodLabel); global::Gtk.Box.BoxChild w30 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this._foodLabel])); w30.Position = 4; w30.Expand = false; w30.Fill = false; this.vbox3.Add (this.hbox1); global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.hbox1])); w31.Position = 0; w31.Expand = false; w31.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.notebook2 = new global::Gtk.Notebook (); this.notebook2.CanFocus = true; this.notebook2.Name = "notebook2"; this.notebook2.CurrentPage = 0; // Container child notebook2.Gtk.Notebook+NotebookChild this.table2 = new global::Gtk.Table (((uint)(3)), ((uint)(15)), false); this.table2.Name = "table2"; this.table2.RowSpacing = ((uint)(6)); this.table2.ColumnSpacing = ((uint)(6)); this.table2.BorderWidth = ((uint)(2)); // Container child table2.Gtk.Table+TableChild this._dCost1 = new global::Gtk.Label (); this._dCost1.Name = "_dCost1"; this._dCost1.Xalign = 0F; this._dCost1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._dCost1); global::Gtk.Table.TableChild w32 = ((global::Gtk.Table.TableChild)(this.table2 [this._dCost1])); w32.TopAttach = ((uint)(1)); w32.BottomAttach = ((uint)(2)); w32.LeftAttach = ((uint)(6)); w32.RightAttach = ((uint)(7)); w32.XOptions = ((global::Gtk.AttachOptions)(4)); w32.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._dCost2 = new global::Gtk.Label (); this._dCost2.Name = "_dCost2"; this._dCost2.Xalign = 0F; this._dCost2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._dCost2); global::Gtk.Table.TableChild w33 = ((global::Gtk.Table.TableChild)(this.table2 [this._dCost2])); w33.TopAttach = ((uint)(2)); w33.BottomAttach = ((uint)(3)); w33.LeftAttach = ((uint)(6)); w33.RightAttach = ((uint)(7)); w33.XOptions = ((global::Gtk.AttachOptions)(4)); w33.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._dining1 = new global::Gtk.Label (); this._dining1.Name = "_dining1"; this._dining1.Xalign = 0F; this._dining1.LabelProp = global::Mono.Unix.Catalog.GetString ("Energy"); this.table2.Add (this._dining1); global::Gtk.Table.TableChild w34 = ((global::Gtk.Table.TableChild)(this.table2 [this._dining1])); w34.TopAttach = ((uint)(1)); w34.BottomAttach = ((uint)(2)); w34.LeftAttach = ((uint)(3)); w34.RightAttach = ((uint)(4)); w34.XOptions = ((global::Gtk.AttachOptions)(4)); w34.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._dining2 = new global::Gtk.Label (); this._dining2.Name = "_dining2"; this._dining2.Xalign = 0F; this._dining2.LabelProp = global::Mono.Unix.Catalog.GetString ("Energy"); this.table2.Add (this._dining2); global::Gtk.Table.TableChild w35 = ((global::Gtk.Table.TableChild)(this.table2 [this._dining2])); w35.TopAttach = ((uint)(2)); w35.BottomAttach = ((uint)(3)); w35.LeftAttach = ((uint)(3)); w35.RightAttach = ((uint)(4)); w35.XOptions = ((global::Gtk.AttachOptions)(4)); w35.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._eCost1 = new global::Gtk.Label (); this._eCost1.Name = "_eCost1"; this._eCost1.Xalign = 0F; this._eCost1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._eCost1); global::Gtk.Table.TableChild w36 = ((global::Gtk.Table.TableChild)(this.table2 [this._eCost1])); w36.TopAttach = ((uint)(1)); w36.BottomAttach = ((uint)(2)); w36.LeftAttach = ((uint)(7)); w36.RightAttach = ((uint)(8)); w36.XOptions = ((global::Gtk.AttachOptions)(4)); w36.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._eCost2 = new global::Gtk.Label (); this._eCost2.Name = "_eCost2"; this._eCost2.Xalign = 0F; this._eCost2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._eCost2); global::Gtk.Table.TableChild w37 = ((global::Gtk.Table.TableChild)(this.table2 [this._eCost2])); w37.TopAttach = ((uint)(2)); w37.BottomAttach = ((uint)(3)); w37.LeftAttach = ((uint)(7)); w37.RightAttach = ((uint)(8)); w37.XOptions = ((global::Gtk.AttachOptions)(4)); w37.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._energy1 = new global::Gtk.Label (); this._energy1.Name = "_energy1"; this._energy1.Xalign = 0F; this._energy1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._energy1); global::Gtk.Table.TableChild w38 = ((global::Gtk.Table.TableChild)(this.table2 [this._energy1])); w38.TopAttach = ((uint)(1)); w38.BottomAttach = ((uint)(2)); w38.LeftAttach = ((uint)(4)); w38.RightAttach = ((uint)(5)); w38.XOptions = ((global::Gtk.AttachOptions)(4)); w38.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._energy2 = new global::Gtk.Label (); this._energy2.Name = "_energy2"; this._energy2.Xalign = 0F; this._energy2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._energy2); global::Gtk.Table.TableChild w39 = ((global::Gtk.Table.TableChild)(this.table2 [this._energy2])); w39.TopAttach = ((uint)(2)); w39.BottomAttach = ((uint)(3)); w39.LeftAttach = ((uint)(4)); w39.RightAttach = ((uint)(5)); w39.XOptions = ((global::Gtk.AttachOptions)(4)); w39.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._enzC1 = new global::Gtk.Label (); this._enzC1.Name = "_enzC1"; this._enzC1.Xalign = 0F; this._enzC1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._enzC1); global::Gtk.Table.TableChild w40 = ((global::Gtk.Table.TableChild)(this.table2 [this._enzC1])); w40.TopAttach = ((uint)(1)); w40.BottomAttach = ((uint)(2)); w40.LeftAttach = ((uint)(9)); w40.RightAttach = ((uint)(10)); w40.XOptions = ((global::Gtk.AttachOptions)(4)); w40.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._enzC2 = new global::Gtk.Label (); this._enzC2.Name = "_enzC2"; this._enzC2.Xalign = 0F; this._enzC2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._enzC2); global::Gtk.Table.TableChild w41 = ((global::Gtk.Table.TableChild)(this.table2 [this._enzC2])); w41.TopAttach = ((uint)(2)); w41.BottomAttach = ((uint)(3)); w41.LeftAttach = ((uint)(9)); w41.RightAttach = ((uint)(10)); w41.XOptions = ((global::Gtk.AttachOptions)(4)); w41.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._ep1 = new global::Gtk.Label (); this._ep1.Name = "_ep1"; this._ep1.Xalign = 0F; this._ep1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._ep1); global::Gtk.Table.TableChild w42 = ((global::Gtk.Table.TableChild)(this.table2 [this._ep1])); w42.TopAttach = ((uint)(1)); w42.BottomAttach = ((uint)(2)); w42.LeftAttach = ((uint)(12)); w42.RightAttach = ((uint)(13)); w42.XOptions = ((global::Gtk.AttachOptions)(4)); w42.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._ep2 = new global::Gtk.Label (); this._ep2.Name = "_ep2"; this._ep2.Xalign = 0F; this._ep2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._ep2); global::Gtk.Table.TableChild w43 = ((global::Gtk.Table.TableChild)(this.table2 [this._ep2])); w43.TopAttach = ((uint)(2)); w43.BottomAttach = ((uint)(3)); w43.LeftAttach = ((uint)(12)); w43.RightAttach = ((uint)(13)); w43.XOptions = ((global::Gtk.AttachOptions)(4)); w43.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._ex1 = new global::Gtk.Label (); this._ex1.Name = "_ex1"; this._ex1.Xalign = 0F; this._ex1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this._ex1.Wrap = true; this.table2.Add (this._ex1); global::Gtk.Table.TableChild w44 = ((global::Gtk.Table.TableChild)(this.table2 [this._ex1])); w44.TopAttach = ((uint)(1)); w44.BottomAttach = ((uint)(2)); w44.LeftAttach = ((uint)(8)); w44.RightAttach = ((uint)(9)); w44.XOptions = ((global::Gtk.AttachOptions)(4)); w44.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._ex2 = new global::Gtk.Label (); this._ex2.Name = "_ex2"; this._ex2.Xalign = 0F; this._ex2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._ex2); global::Gtk.Table.TableChild w45 = ((global::Gtk.Table.TableChild)(this.table2 [this._ex2])); w45.TopAttach = ((uint)(2)); w45.BottomAttach = ((uint)(3)); w45.LeftAttach = ((uint)(8)); w45.RightAttach = ((uint)(9)); w45.XOptions = ((global::Gtk.AttachOptions)(4)); w45.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._fEnz1 = new global::Gtk.Label (); this._fEnz1.Name = "_fEnz1"; this._fEnz1.Xalign = 0F; this._fEnz1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._fEnz1); global::Gtk.Table.TableChild w46 = ((global::Gtk.Table.TableChild)(this.table2 [this._fEnz1])); w46.TopAttach = ((uint)(1)); w46.BottomAttach = ((uint)(2)); w46.LeftAttach = ((uint)(10)); w46.RightAttach = ((uint)(11)); w46.XOptions = ((global::Gtk.AttachOptions)(4)); w46.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._fEnz2 = new global::Gtk.Label (); this._fEnz2.Name = "_fEnz2"; this._fEnz2.Xalign = 0F; this._fEnz2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._fEnz2); global::Gtk.Table.TableChild w47 = ((global::Gtk.Table.TableChild)(this.table2 [this._fEnz2])); w47.TopAttach = ((uint)(2)); w47.BottomAttach = ((uint)(3)); w47.LeftAttach = ((uint)(10)); w47.RightAttach = ((uint)(11)); w47.XOptions = ((global::Gtk.AttachOptions)(4)); w47.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._fitness1 = new global::Gtk.Label (); this._fitness1.Name = "_fitness1"; this._fitness1.Xalign = 0F; this._fitness1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._fitness1); global::Gtk.Table.TableChild w48 = ((global::Gtk.Table.TableChild)(this.table2 [this._fitness1])); w48.TopAttach = ((uint)(1)); w48.BottomAttach = ((uint)(2)); w48.LeftAttach = ((uint)(1)); w48.RightAttach = ((uint)(2)); w48.XOptions = ((global::Gtk.AttachOptions)(4)); w48.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._fitness2 = new global::Gtk.Label (); this._fitness2.Name = "_fitness2"; this._fitness2.Xalign = 0F; this._fitness2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._fitness2); global::Gtk.Table.TableChild w49 = ((global::Gtk.Table.TableChild)(this.table2 [this._fitness2])); w49.TopAttach = ((uint)(2)); w49.BottomAttach = ((uint)(3)); w49.LeftAttach = ((uint)(1)); w49.RightAttach = ((uint)(2)); w49.XOptions = ((global::Gtk.AttachOptions)(4)); w49.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._inject1 = new global::Gtk.Button (); this._inject1.Sensitive = false; this._inject1.CanFocus = true; this._inject1.Name = "_inject1"; this._inject1.UseUnderline = true; this._inject1.Label = global::Mono.Unix.Catalog.GetString ("Inject"); this.table2.Add (this._inject1); global::Gtk.Table.TableChild w50 = ((global::Gtk.Table.TableChild)(this.table2 [this._inject1])); w50.TopAttach = ((uint)(1)); w50.BottomAttach = ((uint)(2)); w50.LeftAttach = ((uint)(14)); w50.RightAttach = ((uint)(15)); w50.XOptions = ((global::Gtk.AttachOptions)(4)); w50.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._inject2 = new global::Gtk.Button (); this._inject2.Sensitive = false; this._inject2.CanFocus = true; this._inject2.Name = "_inject2"; this._inject2.UseUnderline = true; this._inject2.Label = global::Mono.Unix.Catalog.GetString ("Inject"); this.table2.Add (this._inject2); global::Gtk.Table.TableChild w51 = ((global::Gtk.Table.TableChild)(this.table2 [this._inject2])); w51.TopAttach = ((uint)(2)); w51.BottomAttach = ((uint)(3)); w51.LeftAttach = ((uint)(14)); w51.RightAttach = ((uint)(15)); w51.XOptions = ((global::Gtk.AttachOptions)(4)); w51.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._max1 = new global::Gtk.Label (); this._max1.Name = "_max1"; this._max1.Xalign = 0F; this._max1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._max1); global::Gtk.Table.TableChild w52 = ((global::Gtk.Table.TableChild)(this.table2 [this._max1])); w52.TopAttach = ((uint)(1)); w52.BottomAttach = ((uint)(2)); w52.LeftAttach = ((uint)(5)); w52.RightAttach = ((uint)(6)); w52.XOptions = ((global::Gtk.AttachOptions)(4)); w52.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._max2 = new global::Gtk.Label (); this._max2.Name = "_max2"; this._max2.Xalign = 0F; this._max2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._max2); global::Gtk.Table.TableChild w53 = ((global::Gtk.Table.TableChild)(this.table2 [this._max2])); w53.TopAttach = ((uint)(2)); w53.BottomAttach = ((uint)(3)); w53.LeftAttach = ((uint)(5)); w53.RightAttach = ((uint)(6)); w53.XOptions = ((global::Gtk.AttachOptions)(4)); w53.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._save1 = new global::Gtk.Button (); this._save1.Sensitive = false; this._save1.CanFocus = true; this._save1.Name = "_save1"; this._save1.UseUnderline = true; this._save1.Label = global::Mono.Unix.Catalog.GetString ("Save"); this.table2.Add (this._save1); global::Gtk.Table.TableChild w54 = ((global::Gtk.Table.TableChild)(this.table2 [this._save1])); w54.TopAttach = ((uint)(1)); w54.BottomAttach = ((uint)(2)); w54.LeftAttach = ((uint)(13)); w54.RightAttach = ((uint)(14)); w54.XOptions = ((global::Gtk.AttachOptions)(4)); w54.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._save2 = new global::Gtk.Button (); this._save2.Sensitive = false; this._save2.CanFocus = true; this._save2.Name = "_save2"; this._save2.UseUnderline = true; this._save2.Label = global::Mono.Unix.Catalog.GetString ("Save"); this.table2.Add (this._save2); global::Gtk.Table.TableChild w55 = ((global::Gtk.Table.TableChild)(this.table2 [this._save2])); w55.TopAttach = ((uint)(2)); w55.BottomAttach = ((uint)(3)); w55.LeftAttach = ((uint)(13)); w55.RightAttach = ((uint)(14)); w55.XOptions = ((global::Gtk.AttachOptions)(4)); w55.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._sEnz1 = new global::Gtk.Label (); this._sEnz1.Name = "_sEnz1"; this._sEnz1.Xalign = 0F; this._sEnz1.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._sEnz1); global::Gtk.Table.TableChild w56 = ((global::Gtk.Table.TableChild)(this.table2 [this._sEnz1])); w56.TopAttach = ((uint)(1)); w56.BottomAttach = ((uint)(2)); w56.LeftAttach = ((uint)(11)); w56.RightAttach = ((uint)(12)); w56.XOptions = ((global::Gtk.AttachOptions)(4)); w56.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._sEnz2 = new global::Gtk.Label (); this._sEnz2.Name = "_sEnz2"; this._sEnz2.Xalign = 0F; this._sEnz2.LabelProp = global::Mono.Unix.Catalog.GetString ("0"); this.table2.Add (this._sEnz2); global::Gtk.Table.TableChild w57 = ((global::Gtk.Table.TableChild)(this.table2 [this._sEnz2])); w57.TopAttach = ((uint)(2)); w57.BottomAttach = ((uint)(3)); w57.LeftAttach = ((uint)(11)); w57.RightAttach = ((uint)(12)); w57.XOptions = ((global::Gtk.AttachOptions)(4)); w57.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._state1 = new global::Gtk.Label (); this._state1.Name = "_state1"; this._state1.Xalign = 0F; this._state1.LabelProp = global::Mono.Unix.Catalog.GetString ("?"); this.table2.Add (this._state1); global::Gtk.Table.TableChild w58 = ((global::Gtk.Table.TableChild)(this.table2 [this._state1])); w58.TopAttach = ((uint)(1)); w58.BottomAttach = ((uint)(2)); w58.LeftAttach = ((uint)(2)); w58.RightAttach = ((uint)(3)); w58.XOptions = ((global::Gtk.AttachOptions)(4)); w58.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this._state2 = new global::Gtk.Label (); this._state2.Name = "_state2"; this._state2.Xalign = 0F; this._state2.LabelProp = global::Mono.Unix.Catalog.GetString ("?"); this.table2.Add (this._state2); global::Gtk.Table.TableChild w59 = ((global::Gtk.Table.TableChild)(this.table2 [this._state2])); w59.TopAttach = ((uint)(2)); w59.BottomAttach = ((uint)(3)); w59.LeftAttach = ((uint)(2)); w59.RightAttach = ((uint)(3)); w59.XOptions = ((global::Gtk.AttachOptions)(4)); w59.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label = new global::Gtk.Label (); this.label.Name = "label"; this.label.Xalign = 0F; this.label.LabelProp = global::Mono.Unix.Catalog.GetString ("Enzyme #"); this.table2.Add (this.label); global::Gtk.Table.TableChild w60 = ((global::Gtk.Table.TableChild)(this.table2 [this.label])); w60.LeftAttach = ((uint)(9)); w60.RightAttach = ((uint)(10)); w60.XOptions = ((global::Gtk.AttachOptions)(4)); w60.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label12 = new global::Gtk.Label (); this.label12.Name = "label12"; this.label12.Xalign = 0F; this.label12.LabelProp = global::Mono.Unix.Catalog.GetString ("Fitness"); this.table2.Add (this.label12); global::Gtk.Table.TableChild w61 = ((global::Gtk.Table.TableChild)(this.table2 [this.label12])); w61.LeftAttach = ((uint)(1)); w61.RightAttach = ((uint)(2)); w61.XOptions = ((global::Gtk.AttachOptions)(4)); w61.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label13 = new global::Gtk.Label (); this.label13.Name = "label13"; this.label13.Xalign = 0F; this.label13.LabelProp = global::Mono.Unix.Catalog.GetString ("Energy"); this.table2.Add (this.label13); global::Gtk.Table.TableChild w62 = ((global::Gtk.Table.TableChild)(this.table2 [this.label13])); w62.LeftAttach = ((uint)(4)); w62.RightAttach = ((uint)(5)); w62.XOptions = ((global::Gtk.AttachOptions)(4)); w62.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label14 = new global::Gtk.Label (); this.label14.Name = "label14"; this.label14.Xalign = 0F; this.label14.LabelProp = global::Mono.Unix.Catalog.GetString ("Max"); this.table2.Add (this.label14); global::Gtk.Table.TableChild w63 = ((global::Gtk.Table.TableChild)(this.table2 [this.label14])); w63.LeftAttach = ((uint)(5)); w63.RightAttach = ((uint)(6)); w63.XOptions = ((global::Gtk.AttachOptions)(4)); w63.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label15 = new global::Gtk.Label (); this.label15.Name = "label15"; this.label15.Xalign = 0F; this.label15.LabelProp = global::Mono.Unix.Catalog.GetString ("D Cost"); this.table2.Add (this.label15); global::Gtk.Table.TableChild w64 = ((global::Gtk.Table.TableChild)(this.table2 [this.label15])); w64.LeftAttach = ((uint)(6)); w64.RightAttach = ((uint)(7)); w64.XOptions = ((global::Gtk.AttachOptions)(4)); w64.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label16 = new global::Gtk.Label (); this.label16.Name = "label16"; this.label16.Xalign = 0F; this.label16.LabelProp = global::Mono.Unix.Catalog.GetString ("E Cost"); this.table2.Add (this.label16); global::Gtk.Table.TableChild w65 = ((global::Gtk.Table.TableChild)(this.table2 [this.label16])); w65.LeftAttach = ((uint)(7)); w65.RightAttach = ((uint)(8)); w65.XOptions = ((global::Gtk.AttachOptions)(4)); w65.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label17 = new global::Gtk.Label (); this.label17.Name = "label17"; this.label17.Xalign = 0F; this.label17.LabelProp = global::Mono.Unix.Catalog.GetString ("Ex %"); this.table2.Add (this.label17); global::Gtk.Table.TableChild w66 = ((global::Gtk.Table.TableChild)(this.table2 [this.label17])); w66.LeftAttach = ((uint)(8)); w66.RightAttach = ((uint)(9)); w66.XOptions = ((global::Gtk.AttachOptions)(4)); w66.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label18 = new global::Gtk.Label (); this.label18.Name = "label18"; this.label18.Xalign = 0F; this.label18.LabelProp = global::Mono.Unix.Catalog.GetString ("Method"); this.table2.Add (this.label18); global::Gtk.Table.TableChild w67 = ((global::Gtk.Table.TableChild)(this.table2 [this.label18])); w67.LeftAttach = ((uint)(3)); w67.RightAttach = ((uint)(4)); w67.XOptions = ((global::Gtk.AttachOptions)(4)); w67.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label25 = new global::Gtk.Label (); this.label25.Name = "label25"; this.label25.Xalign = 0F; this.label25.LabelProp = global::Mono.Unix.Catalog.GetString ("Enz # 1"); this.table2.Add (this.label25); global::Gtk.Table.TableChild w68 = ((global::Gtk.Table.TableChild)(this.table2 [this.label25])); w68.LeftAttach = ((uint)(10)); w68.RightAttach = ((uint)(11)); w68.XOptions = ((global::Gtk.AttachOptions)(4)); w68.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label26 = new global::Gtk.Label (); this.label26.Name = "label26"; this.label26.Xalign = 0F; this.label26.LabelProp = global::Mono.Unix.Catalog.GetString ("Enz # 2"); this.table2.Add (this.label26); global::Gtk.Table.TableChild w69 = ((global::Gtk.Table.TableChild)(this.table2 [this.label26])); w69.LeftAttach = ((uint)(11)); w69.RightAttach = ((uint)(12)); w69.XOptions = ((global::Gtk.AttachOptions)(4)); w69.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label27 = new global::Gtk.Label (); this.label27.Name = "label27"; this.label27.Xalign = 0F; this.label27.LabelProp = global::Mono.Unix.Catalog.GetString ("Eat Predicate"); this.table2.Add (this.label27); global::Gtk.Table.TableChild w70 = ((global::Gtk.Table.TableChild)(this.table2 [this.label27])); w70.LeftAttach = ((uint)(12)); w70.RightAttach = ((uint)(13)); w70.XOptions = ((global::Gtk.AttachOptions)(4)); w70.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label28 = new global::Gtk.Label (); this.label28.Name = "label28"; this.label28.Xalign = 0F; this.label28.LabelProp = global::Mono.Unix.Catalog.GetString ("State"); this.table2.Add (this.label28); global::Gtk.Table.TableChild w71 = ((global::Gtk.Table.TableChild)(this.table2 [this.label28])); w71.LeftAttach = ((uint)(2)); w71.RightAttach = ((uint)(3)); w71.XOptions = ((global::Gtk.AttachOptions)(4)); w71.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label4 = new global::Gtk.Label (); this.label4.Name = "label4"; this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Fittest 1"); this.table2.Add (this.label4); global::Gtk.Table.TableChild w72 = ((global::Gtk.Table.TableChild)(this.table2 [this.label4])); w72.TopAttach = ((uint)(1)); w72.BottomAttach = ((uint)(2)); w72.XOptions = ((global::Gtk.AttachOptions)(4)); w72.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table2.Gtk.Table+TableChild this.label5 = new global::Gtk.Label (); this.label5.Name = "label5"; this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("Fittest2"); this.table2.Add (this.label5); global::Gtk.Table.TableChild w73 = ((global::Gtk.Table.TableChild)(this.table2 [this.label5])); w73.TopAttach = ((uint)(2)); w73.BottomAttach = ((uint)(3)); w73.XOptions = ((global::Gtk.AttachOptions)(4)); w73.YOptions = ((global::Gtk.AttachOptions)(4)); this.notebook2.Add (this.table2); // Notebook tab this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Selection"); this.notebook2.SetTabLabel (this.table2, this.label2); this.label2.ShowAll (); // Container child notebook2.Gtk.Notebook+NotebookChild this.notebook3 = new global::Gtk.Notebook (); this.notebook3.CanFocus = true; this.notebook3.Name = "notebook3"; this.notebook3.CurrentPage = 0; // Container child notebook3.Gtk.Notebook+NotebookChild this.hbox3 = new global::Gtk.HBox (); this.hbox3.Name = "hbox3"; this.hbox3.Spacing = 6; // Container child hbox3.Gtk.Box+BoxChild this.vbox5 = new global::Gtk.VBox (); this.vbox5.Name = "vbox5"; this.vbox5.Spacing = 6; // Container child vbox5.Gtk.Box+BoxChild this._selection1rb = new global::Gtk.RadioButton ("Selection 1"); this._selection1rb.CanFocus = true; this._selection1rb.Name = "_selection1rb"; this._selection1rb.DrawIndicator = true; this._selection1rb.UseUnderline = true; this._selection1rb.Group = new global::GLib.SList (global::System.IntPtr.Zero); this.vbox5.Add (this._selection1rb); global::Gtk.Box.BoxChild w75 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this._selection1rb])); w75.Position = 0; w75.Expand = false; w75.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this._selection2rb = new global::Gtk.RadioButton (global::Mono.Unix.Catalog.GetString ("Selection 2")); this._selection2rb.CanFocus = true; this._selection2rb.Name = "_selection2rb"; this._selection2rb.DrawIndicator = true; this._selection2rb.UseUnderline = true; this._selection2rb.Group = this._selection1rb.Group; this.vbox5.Add (this._selection2rb); global::Gtk.Box.BoxChild w76 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this._selection2rb])); w76.Position = 1; w76.Expand = false; w76.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.hbox5 = new global::Gtk.HBox (); this.hbox5.Name = "hbox5"; this.hbox5.Spacing = 6; // Container child hbox5.Gtk.Box+BoxChild this.button2 = new global::Gtk.Button (); this.button2.CanFocus = true; this.button2.Name = "button2"; this.button2.UseUnderline = true; this.button2.Label = global::Mono.Unix.Catalog.GetString ("GtkButton"); this.hbox5.Add (this.button2); global::Gtk.Box.BoxChild w77 = ((global::Gtk.Box.BoxChild)(this.hbox5 [this.button2])); w77.Position = 0; w77.Expand = false; w77.Fill = false; this.vbox5.Add (this.hbox5); global::Gtk.Box.BoxChild w78 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.hbox5])); w78.PackType = ((global::Gtk.PackType)(1)); w78.Position = 2; w78.Expand = false; w78.Fill = false; // Container child vbox5.Gtk.Box+BoxChild this.fixed1 = new global::Gtk.Fixed (); this.fixed1.Name = "fixed1"; this.fixed1.HasWindow = false; this.vbox5.Add (this.fixed1); global::Gtk.Box.BoxChild w79 = ((global::Gtk.Box.BoxChild)(this.vbox5 [this.fixed1])); w79.PackType = ((global::Gtk.PackType)(1)); w79.Position = 3; w79.Expand = false; w79.Fill = false; this.hbox3.Add (this.vbox5); global::Gtk.Box.BoxChild w80 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.vbox5])); w80.Position = 0; w80.Expand = false; w80.Fill = false; // Container child hbox3.Gtk.Box+BoxChild this.GtkScrolledWindow = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow.Name = "GtkScrolledWindow"; this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow.Gtk.Container+ContainerChild this._eatDecisionText = new global::Gtk.TextView (); this._eatDecisionText.CanFocus = true; this._eatDecisionText.Name = "_eatDecisionText"; this._eatDecisionText.Editable = false; this.GtkScrolledWindow.Add (this._eatDecisionText); this.hbox3.Add (this.GtkScrolledWindow); global::Gtk.Box.BoxChild w82 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.GtkScrolledWindow])); w82.Position = 1; this.notebook3.Add (this.hbox3); // Notebook tab this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Eat"); this.notebook3.SetTabLabel (this.hbox3, this.label1); this.label1.ShowAll (); this.notebook2.Add (this.notebook3); global::Gtk.Notebook.NotebookChild w84 = ((global::Gtk.Notebook.NotebookChild)(this.notebook2 [this.notebook3])); w84.Position = 1; // Notebook tab this._decisionProcessing = new global::Gtk.Label (); this._decisionProcessing.Sensitive = false; this._decisionProcessing.Name = "_decisionProcessing"; this._decisionProcessing.LabelProp = global::Mono.Unix.Catalog.GetString ("Decision Processing"); this.notebook2.SetTabLabel (this.notebook3, this._decisionProcessing); this._decisionProcessing.ShowAll (); // Container child notebook2.Gtk.Notebook+NotebookChild this.hbox4 = new global::Gtk.HBox (); this.hbox4.Name = "hbox4"; this.hbox4.Spacing = 6; // Container child hbox4.Gtk.Box+BoxChild this.vbox6 = new global::Gtk.VBox (); this.vbox6.Name = "vbox6"; this.vbox6.Spacing = 6; // Container child vbox6.Gtk.Box+BoxChild this._loadSim1 = new global::Gtk.Button (); this._loadSim1.CanFocus = true; this._loadSim1.Name = "_loadSim1"; this._loadSim1.UseUnderline = true; this._loadSim1.Label = global::Mono.Unix.Catalog.GetString ("Load Selection 1"); this.vbox6.Add (this._loadSim1); global::Gtk.Box.BoxChild w85 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this._loadSim1])); w85.Position = 0; w85.Expand = false; w85.Fill = false; // Container child vbox6.Gtk.Box+BoxChild this._loadSim2 = new global::Gtk.Button (); this._loadSim2.CanFocus = true; this._loadSim2.Name = "_loadSim2"; this._loadSim2.UseUnderline = true; this._loadSim2.Label = global::Mono.Unix.Catalog.GetString ("Load Selection 2"); this.vbox6.Add (this._loadSim2); global::Gtk.Box.BoxChild w86 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this._loadSim2])); w86.Position = 1; w86.Expand = false; w86.Fill = false; // Container child vbox6.Gtk.Box+BoxChild this._loadedSimulatorLabel = new global::Gtk.Label (); this._loadedSimulatorLabel.Name = "_loadedSimulatorLabel"; this._loadedSimulatorLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("No Selection Loaded"); this.vbox6.Add (this._loadedSimulatorLabel); global::Gtk.Box.BoxChild w87 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this._loadedSimulatorLabel])); w87.Position = 2; w87.Expand = false; w87.Fill = false; // Container child vbox6.Gtk.Box+BoxChild this._simulate1Turn = new global::Gtk.Button (); this._simulate1Turn.Sensitive = false; this._simulate1Turn.CanFocus = true; this._simulate1Turn.Name = "_simulate1Turn"; this._simulate1Turn.UseUnderline = true; this._simulate1Turn.Label = global::Mono.Unix.Catalog.GetString ("Sim 1"); this.vbox6.Add (this._simulate1Turn); global::Gtk.Box.BoxChild w88 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this._simulate1Turn])); w88.PackType = ((global::Gtk.PackType)(1)); w88.Position = 3; w88.Expand = false; w88.Fill = false; this.hbox4.Add (this.vbox6); global::Gtk.Box.BoxChild w89 = ((global::Gtk.Box.BoxChild)(this.hbox4 [this.vbox6])); w89.Position = 0; w89.Expand = false; w89.Fill = false; // Container child hbox4.Gtk.Box+BoxChild this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow1.Name = "GtkScrolledWindow1"; this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow1.Gtk.Container+ContainerChild this._simDescription = new global::Gtk.TextView (); this._simDescription.CanFocus = true; this._simDescription.Name = "_simDescription"; this._simDescription.Editable = false; this.GtkScrolledWindow1.Add (this._simDescription); this.hbox4.Add (this.GtkScrolledWindow1); global::Gtk.Box.BoxChild w91 = ((global::Gtk.Box.BoxChild)(this.hbox4 [this.GtkScrolledWindow1])); w91.Position = 1; this.notebook2.Add (this.hbox4); global::Gtk.Notebook.NotebookChild w92 = ((global::Gtk.Notebook.NotebookChild)(this.notebook2 [this.hbox4])); w92.Position = 2; // Notebook tab this.label19 = new global::Gtk.Label (); this.label19.Name = "label19"; this.label19.LabelProp = global::Mono.Unix.Catalog.GetString ("Simulation"); this.notebook2.SetTabLabel (this.hbox4, this.label19); this.label19.ShowAll (); this.vbox3.Add (this.notebook2); global::Gtk.Box.BoxChild w93 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.notebook2])); w93.Position = 1; this.vbox1.Add (this.vbox3); global::Gtk.Box.BoxChild w94 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.vbox3])); w94.Position = 0; // Container child vbox1.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this._action = new global::Gtk.Button (); this._action.Sensitive = false; this._action.CanFocus = true; this._action.Name = "_action"; this._action.UseUnderline = true; this._action.Label = global::Mono.Unix.Catalog.GetString ("Go"); this.hbox2.Add (this._action); global::Gtk.Box.BoxChild w95 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this._action])); w95.Position = 0; w95.Expand = false; w95.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.alignment3 = new global::Gtk.Alignment (0.5F, 0.5F, 1F, 1F); this.alignment3.Name = "alignment3"; this.hbox2.Add (this.alignment3); global::Gtk.Box.BoxChild w96 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.alignment3])); w96.Position = 1; // Container child hbox2.Gtk.Box+BoxChild this.button5 = new global::Gtk.Button (); this.button5.CanFocus = true; this.button5.Name = "button5"; this.button5.UseUnderline = true; this.button5.Label = global::Mono.Unix.Catalog.GetString ("Close"); this.hbox2.Add (this.button5); global::Gtk.Box.BoxChild w97 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.button5])); w97.Position = 2; w97.Expand = false; w97.Fill = false; this.vbox1.Add (this.hbox2); global::Gtk.Box.BoxChild w98 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox2])); w98.Position = 1; w98.Expand = false; w98.Fill = false; this.vbox2.Add (this.vbox1); global::Gtk.Box.BoxChild w99 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.vbox1])); w99.Position = 2; this.Add (this.vbox2); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 1464; this.DefaultHeight = 499; this._resetWarning.Hide (); this.button2.Hide (); this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this._reset.Clicked += new global::System.EventHandler (this.OnResetClicked); this._save2.Clicked += new global::System.EventHandler (this.OnSave2Clicked); this._save1.Clicked += new global::System.EventHandler (this.OnSave1Clicked); this._inject2.Clicked += new global::System.EventHandler (this.OnInject2Clicked); this._inject1.Clicked += new global::System.EventHandler (this.OnInject1Clicked); this._selection1rb.Clicked += new global::System.EventHandler (this.OnSelection1rbClicked); this._selection2rb.Clicked += new global::System.EventHandler (this.OnSelection2rbClicked); this._loadSim1.Clicked += new global::System.EventHandler (this.OnLoadSim1Clicked); this._loadSim2.Clicked += new global::System.EventHandler (this.OnLoadSim2Clicked); this._simulate1Turn.Clicked += new global::System.EventHandler (this.OnButton1Clicked); this._action.Clicked += new global::System.EventHandler (this.OnActionClicked); } }
// // Created by Shopify. // Copyright (c) 2016 Shopify Inc. All rights reserved. // Copyright (c) 2016 Xamarin Inc. All rights reserved. // // 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 Android.App; using Android.Content; using Android.OS; using Android.Widget; using Square.Retrofit; using Shopify.Buy.DataProvider; using Shopify.Buy.Model; namespace ShopifyAndroidSample.Activities.Base { // Base class for all activities in the app. Manages the ProgressDialog that is displayed while network activity is occurring. public class SampleActivity : Activity { // The amount of time in milliseconds to delay between network calls when you are polling for Shipping Rates and Checkout Completion protected const long PollDelay = 500; protected Handler pollingHandler; private ProgressDialog progressDialog; private bool webCheckoutInProgress; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); pollingHandler = new Handler(); InitializeProgressDialog(); } protected override void OnResume() { base.OnResume(); // If we are being launched by a url scheme, check the scheme and retrieve the checkout token if provided var uri = Intent.Data; var scheme = GetString(Resource.String.web_return_to_scheme); if (uri != null && uri.Scheme == scheme) { webCheckoutInProgress = false; // If the app was launched using the scheme, we know we just successfully completed an order OnCheckoutComplete(); } else { // If a Web checkout was previously launched, we should check its status if (webCheckoutInProgress && SampleApplication.Checkout != null) { PollCheckoutCompletionStatus(SampleApplication.Checkout); } } } protected override void OnDestroy() { base.OnDestroy(); progressDialog?.Dismiss(); } protected SampleApplication SampleApplication { get { return (SampleApplication)Application; } } // Initializes a simple progress dialog that gets presented while the app is communicating with the server. private void InitializeProgressDialog() { progressDialog?.Dismiss(); progressDialog = new ProgressDialog(this); progressDialog.Indeterminate = true; progressDialog.SetTitle(GetString(Resource.String.please_wait)); progressDialog.SetCancelable(true); progressDialog.CancelEvent += delegate { Finish(); }; } // Present the progress dialog. protected void ShowLoadingDialog(int messageId) { RunOnUiThread(() => { progressDialog.SetMessage(GetString(messageId)); progressDialog.Show(); }); } protected void DismissLoadingDialog() { RunOnUiThread(() => { progressDialog.Dismiss(); }); } protected void OnError(RetrofitError error) { OnError(BuyClient.GetErrorBody(error)); } // When we encounter an error with one of our network calls, we abort and return to the previous activity. // In a production app, you'll want to handle these types of errors more gracefully. protected void OnError(string errorMessage) { progressDialog.Dismiss(); Console.WriteLine("Error: " + errorMessage); Toast.MakeText(this, Resource.String.error, ToastLength.Long).Show(); Finish(); } // Use the latest Checkout objects details to populate the text views in the order summary section. protected void UpdateOrderSummary() { var checkout = SampleApplication.Checkout; if (checkout == null) { return; } FindViewById<TextView>(Resource.Id.line_item_price_value).Text = checkout.Currency + " " + checkout.LineItems[0].Price; var totalDiscount = 0.0; var discount = checkout.Discount; if (discount != null && !string.IsNullOrEmpty(discount.Amount)) { totalDiscount += double.Parse(discount.Amount); } FindViewById<TextView>(Resource.Id.discount_value).Text = "-" + checkout.Currency + " " + totalDiscount; var totalGiftCards = 0.0; var giftCards = checkout.GiftCards; if (giftCards != null) { foreach (var giftCard in giftCards) { if (!string.IsNullOrEmpty(giftCard.AmountUsed)) { totalGiftCards += double.Parse(giftCard.AmountUsed); } } } FindViewById<TextView>(Resource.Id.gift_card_value).Text = "-" + checkout.Currency + " " + totalGiftCards; FindViewById<TextView>(Resource.Id.taxes_value).Text = checkout.Currency + " " + checkout.TotalTax; FindViewById<TextView>(Resource.Id.total_value).Text = checkout.Currency + " " + checkout.PaymentDue; if (checkout.ShippingRate != null) { FindViewById<TextView>(Resource.Id.shipping_value).Text = checkout.Currency + " " + checkout.ShippingRate.Price; } else { FindViewById<TextView>(Resource.Id.shipping_value).Text = "N/A"; } } // Polls until the web checkout has completed. protected void PollCheckoutCompletionStatus(Checkout checkout) { ShowLoadingDialog(Resource.String.getting_checkout_status); SampleApplication.GetCheckoutCompletionStatus( (complete, response) => { if (complete) { DismissLoadingDialog(); OnCheckoutComplete(); } else { pollingHandler.PostDelayed(() => { PollCheckoutCompletionStatus(checkout); }, PollDelay); } }, OnError); } // When our polling determines that the checkout is completely processed, show a toast. private void OnCheckoutComplete() { DismissLoadingDialog(); webCheckoutInProgress = false; RunOnUiThread(() => { Toast.MakeText(this, Resource.String.checkout_complete, ToastLength.Long).Show(); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** Purpose: An array implementation of a generic stack. ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Collections.Generic { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(StackDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Stack<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; // Storage for stack elements. Do not rename (binary serialization) private int _size; // Number of items in the stack. Do not rename (binary serialization) private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization) private const int DefaultCapacity = 4; public Stack() { _array = Array.Empty<T>(); } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _array = new T[capacity]; } // 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(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } public int Count { get { return _size; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot => this; // Removes all Objects from the Stack. public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { 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 bool Contains(T item) { // Compare items using the default equality comparer // PERF: Internally Array.LastIndexOf calls // EqualityComparer<T>.Default.LastIndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.LastIndexOf. return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1; } // Copies the stack into an array. public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Debug.Assert(array != _array); int srcIndex = 0; int dstIndex = arrayIndex + _size; while(srcIndex < _size) { array[--dstIndex] = _array[srcIndex++]; } } void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Returns an IEnumerator for this Stack. public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { Array.Resize(ref _array, _size); _version++; } } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public T Peek() { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { ThrowForEmptyStack(); } return array[size]; } public bool TryPeek([MaybeNullWhen(false)] out T result) { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { result = default!; return false; } result = array[size]; return true; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public T Pop() { int size = _size - 1; T[] array = _array; // if (_size == 0) is equivalent to if (size == -1), and this case // is covered with (uint)size, thus allowing bounds check elimination // https://github.com/dotnet/coreclr/pull/9773 if ((uint)size >= (uint)array.Length) { ThrowForEmptyStack(); } _version++; _size = size; T item = array[size]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { array[size] = default!; // Free memory quicker. } return item; } public bool TryPop([MaybeNullWhen(false)] out T result) { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { result = default!; return false; } _version++; _size = size; result = array[size]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { array[size] = default!; } return true; } // Pushes an item to the top of the stack. public void Push(T item) { int size = _size; T[] array = _array; if ((uint)size < (uint)array.Length) { array[size] = item; _version++; _size = size + 1; } else { PushWithResize(item); } } // Non-inline from Stack.Push to improve its code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void PushWithResize(T item) { Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); _array[_size] = item; _version++; _size++; } // Copies the Stack to an array, in the same order Pop would return the items. public T[] ToArray() { if (_size == 0) return Array.Empty<T>(); T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private void ThrowForEmptyStack() { Debug.Assert(_size == 0); throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private readonly Stack<T> _stack; private readonly int _version; private int _index; [AllowNull] private T _currentElement; internal Enumerator(Stack<T> stack) { _stack = stack; _version = stack._version; _index = -2; _currentElement = default; } public void Dispose() { _index = -1; } public 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 = default; return retval; } public T Current { get { if (_index < 0) ThrowEnumerationNotStartedOrEnded(); return _currentElement; } } private void ThrowEnumerationNotStartedOrEnded() { Debug.Assert(_index == -1 || _index == -2); throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded); } object? System.Collections.IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = default; } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Google.ProtocolBuffers.Collections; namespace Google.ProtocolBuffers { /// <summary> /// Represents a single field in an UnknownFieldSet. /// /// An UnknownField consists of five lists of values. The lists correspond /// to the five "wire types" used in the protocol buffer binary format. /// The wire type of each field can be determined from the encoded form alone, /// without knowing the field's declared type. So, we are able to parse /// unknown values at least this far and separate them. Normally, only one /// of the five lists will contain any values, since it is impossible to /// define a valid message type that declares two different types for the /// same field number. However, the code is designed to allow for the case /// where the same unknown field number is encountered using multiple different /// wire types. /// /// UnknownField is an immutable class. To construct one, you must use an /// UnknownField.Builder. /// </summary> public sealed class UnknownField { public const string UnknownFieldName = "unknown_field"; private static readonly UnknownField defaultInstance = CreateBuilder().Build(); private readonly ReadOnlyCollection<ulong> varintList; private readonly ReadOnlyCollection<uint> fixed32List; private readonly ReadOnlyCollection<ulong> fixed64List; private readonly ReadOnlyCollection<ByteString> lengthDelimitedList; private readonly ReadOnlyCollection<UnknownFieldSet> groupList; private UnknownField(ReadOnlyCollection<ulong> varintList, ReadOnlyCollection<uint> fixed32List, ReadOnlyCollection<ulong> fixed64List, ReadOnlyCollection<ByteString> lengthDelimitedList, ReadOnlyCollection<UnknownFieldSet> groupList) { this.varintList = varintList; this.fixed32List = fixed32List; this.fixed64List = fixed64List; this.lengthDelimitedList = lengthDelimitedList; this.groupList = groupList; } public static UnknownField DefaultInstance { get { return defaultInstance; } } /// <summary> /// The list of varint values for this field. /// </summary> public IList<ulong> VarintList { get { return varintList; } } /// <summary> /// The list of fixed32 values for this field. /// </summary> public IList<uint> Fixed32List { get { return fixed32List; } } /// <summary> /// The list of fixed64 values for this field. /// </summary> public IList<ulong> Fixed64List { get { return fixed64List; } } /// <summary> /// The list of length-delimited values for this field. /// </summary> public IList<ByteString> LengthDelimitedList { get { return lengthDelimitedList; } } /// <summary> /// The list of embedded group values for this field. These /// are represented using UnknownFieldSets rather than Messages /// since the group's type is presumably unknown. /// </summary> public IList<UnknownFieldSet> GroupList { get { return groupList; } } public override bool Equals(object other) { if (ReferenceEquals(this, other)) { return true; } UnknownField otherField = other as UnknownField; return otherField != null && Lists.Equals(varintList, otherField.varintList) && Lists.Equals(fixed32List, otherField.fixed32List) && Lists.Equals(fixed64List, otherField.fixed64List) && Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList) && Lists.Equals(groupList, otherField.groupList); } public override int GetHashCode() { int hash = 43; hash = hash*47 + Lists.GetHashCode(varintList); hash = hash*47 + Lists.GetHashCode(fixed32List); hash = hash*47 + Lists.GetHashCode(fixed64List); hash = hash*47 + Lists.GetHashCode(lengthDelimitedList); hash = hash*47 + Lists.GetHashCode(groupList); return hash; } /// <summary> /// Constructs a new Builder. /// </summary> public static Builder CreateBuilder() { return new Builder(); } /// <summary> /// Constructs a new Builder and initializes it to a copy of <paramref name="copyFrom"/>. /// </summary> public static Builder CreateBuilder(UnknownField copyFrom) { return new Builder().MergeFrom(copyFrom); } /// <summary> /// Serializes the field, including the field number, and writes it to /// <paramref name="output"/>. /// </summary> public void WriteTo(int fieldNumber, ICodedOutputStream output) { foreach (ulong value in varintList) { output.WriteUnknownField(fieldNumber, WireFormat.WireType.Varint, value); } foreach (uint value in fixed32List) { output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed32, value); } foreach (ulong value in fixed64List) { output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed64, value); } foreach (ByteString value in lengthDelimitedList) { output.WriteUnknownBytes(fieldNumber, value); } foreach (UnknownFieldSet value in groupList) { #pragma warning disable 0612 output.WriteUnknownGroup(fieldNumber, value); #pragma warning restore 0612 } } /// <summary> /// Computes the number of bytes required to encode this field, including field /// number. /// </summary> public int GetSerializedSize(int fieldNumber) { int result = 0; foreach (ulong value in varintList) { result += CodedOutputStream.ComputeUInt64Size(fieldNumber, value); } foreach (uint value in fixed32List) { result += CodedOutputStream.ComputeFixed32Size(fieldNumber, value); } foreach (ulong value in fixed64List) { result += CodedOutputStream.ComputeFixed64Size(fieldNumber, value); } foreach (ByteString value in lengthDelimitedList) { result += CodedOutputStream.ComputeBytesSize(fieldNumber, value); } foreach (UnknownFieldSet value in groupList) { #pragma warning disable 0612 result += CodedOutputStream.ComputeUnknownGroupSize(fieldNumber, value); #pragma warning restore 0612 } return result; } /// <summary> /// Serializes the length-delimited values of the field, including field /// number, and writes them to <paramref name="output"/> using the MessageSet wire format. /// </summary> /// <param name="fieldNumber"></param> /// <param name="output"></param> public void WriteAsMessageSetExtensionTo(int fieldNumber, ICodedOutputStream output) { foreach (ByteString value in lengthDelimitedList) { output.WriteMessageSetExtension(fieldNumber, UnknownFieldName, value); } } /// <summary> /// Get the number of bytes required to encode this field, incuding field number, /// using the MessageSet wire format. /// </summary> public int GetSerializedSizeAsMessageSetExtension(int fieldNumber) { int result = 0; foreach (ByteString value in lengthDelimitedList) { result += CodedOutputStream.ComputeRawMessageSetExtensionSize(fieldNumber, value); } return result; } /// <summary> /// Used to build instances of UnknownField. /// </summary> public sealed class Builder { private List<ulong> varintList; private List<uint> fixed32List; private List<ulong> fixed64List; private List<ByteString> lengthDelimitedList; private List<UnknownFieldSet> groupList; /// <summary> /// Builds the field. After building, the builder is reset to an empty /// state. (This is actually easier than making it unusable.) /// </summary> public UnknownField Build() { return new UnknownField(MakeReadOnly(ref varintList), MakeReadOnly(ref fixed32List), MakeReadOnly(ref fixed64List), MakeReadOnly(ref lengthDelimitedList), MakeReadOnly(ref groupList)); } /// <summary> /// Merge the values in <paramref name="other" /> into this field. For each list /// of values, <paramref name="other"/>'s values are append to the ones in this /// field. /// </summary> public Builder MergeFrom(UnknownField other) { varintList = AddAll(varintList, other.VarintList); fixed32List = AddAll(fixed32List, other.Fixed32List); fixed64List = AddAll(fixed64List, other.Fixed64List); lengthDelimitedList = AddAll(lengthDelimitedList, other.LengthDelimitedList); groupList = AddAll(groupList, other.GroupList); return this; } /// <summary> /// Returns a new list containing all of the given specified values from /// both the <paramref name="current"/> and <paramref name="extras"/> lists. /// If <paramref name="current" /> is null and <paramref name="extras"/> is empty, /// null is returned. Otherwise, either a new list is created (if <paramref name="current" /> /// is null) or the elements of <paramref name="extras"/> are added to <paramref name="current" />. /// </summary> private static List<T> AddAll<T>(List<T> current, IList<T> extras) { if (extras.Count == 0) { return current; } if (current == null) { current = new List<T>(extras); } else { current.AddRange(extras); } return current; } /// <summary> /// Clears the contents of this builder. /// </summary> public Builder Clear() { varintList = null; fixed32List = null; fixed64List = null; lengthDelimitedList = null; groupList = null; return this; } /// <summary> /// Adds a varint value. /// </summary> [CLSCompliant(false)] public Builder AddVarint(ulong value) { varintList = Add(varintList, value); return this; } /// <summary> /// Adds a fixed32 value. /// </summary> [CLSCompliant(false)] public Builder AddFixed32(uint value) { fixed32List = Add(fixed32List, value); return this; } /// <summary> /// Adds a fixed64 value. /// </summary> [CLSCompliant(false)] public Builder AddFixed64(ulong value) { fixed64List = Add(fixed64List, value); return this; } /// <summary> /// Adds a length-delimited value. /// </summary> public Builder AddLengthDelimited(ByteString value) { lengthDelimitedList = Add(lengthDelimitedList, value); return this; } /// <summary> /// Adds an embedded group. /// </summary> /// <param name="value"></param> /// <returns></returns> public Builder AddGroup(UnknownFieldSet value) { groupList = Add(groupList, value); return this; } /// <summary> /// Adds <paramref name="value"/> to the <paramref name="list"/>, creating /// a new list if <paramref name="list"/> is null. The list is returned - either /// the original reference or the new list. /// </summary> private static List<T> Add<T>(List<T> list, T value) { if (list == null) { list = new List<T>(); } list.Add(value); return list; } /// <summary> /// Returns a read-only version of the given IList, and clears /// the field used for <paramref name="list"/>. If the value /// is null, an empty list is produced using Lists.Empty. /// </summary> /// <returns></returns> private static ReadOnlyCollection<T> MakeReadOnly<T>(ref List<T> list) { ReadOnlyCollection<T> ret = list == null ? Lists<T>.Empty : new ReadOnlyCollection<T>(list); list = null; return ret; } } } }
#if UNITY_EDITOR using System.Collections; using System.IO; using System.Text; using System.Xml; using UnityEditor.Android; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using UnityEditor; using UnityEngine; #if UNITY_2018_1_OR_NEWER public class UnityWebViewPostprocessBuild : IPostGenerateGradleAndroidProject #else public class UnityWebViewPostprocessBuild #endif { //// for android/unity 2018.1 or newer //// cf. https://forum.unity.com/threads/android-hardwareaccelerated-is-forced-false-in-all-activities.532786/ //// cf. https://github.com/Over17/UnityAndroidManifestCallback #if UNITY_2018_1_OR_NEWER public void OnPostGenerateGradleAndroidProject(string basePath) { var changed = false; var androidManifest = new AndroidManifest(GetManifestPath(basePath)); changed = (androidManifest.SetHardwareAccelerated(true) || changed); #if UNITYWEBVIEW_ANDROID_USES_CLEARTEXT_TRAFFIC changed = (androidManifest.SetUsesCleartextTraffic(true) || changed); #endif #if UNITYWEBVIEW_ANDROID_ENABLE_CAMERA changed = (androidManifest.AddCamera() || changed); #endif #if UNITYWEBVIEW_ANDROID_ENABLE_MICROPHONE changed = (androidManifest.AddMicrophone() || changed); #endif if (changed) { androidManifest.Save(); Debug.Log("unitywebview: adjusted AndroidManifest.xml."); } } #endif public int callbackOrder { get { return 1; } } private string GetManifestPath(string basePath) { var pathBuilder = new StringBuilder(basePath); pathBuilder.Append(Path.DirectorySeparatorChar).Append("src"); pathBuilder.Append(Path.DirectorySeparatorChar).Append("main"); pathBuilder.Append(Path.DirectorySeparatorChar).Append("AndroidManifest.xml"); return pathBuilder.ToString(); } //// for others [PostProcessBuild(100)] public static void OnPostprocessBuild(BuildTarget buildTarget, string path) { #if !UNITY_2018_1_OR_NEWER if (buildTarget == BuildTarget.Android) { string manifest = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"); if (!File.Exists(manifest)) { string manifest0 = Path.Combine(Application.dataPath, "../Temp/StagingArea/AndroidManifest-main.xml"); if (!File.Exists(manifest0)) { Debug.LogError("unitywebview: cannot find both Assets/Plugins/Android/AndroidManifest.xml and Temp/StagingArea/AndroidManifest-main.xml. please build the app to generate Assets/Plugins/Android/AndroidManifest.xml and then rebuild it again."); return; } else { File.Copy(manifest0, manifest); } } var changed = false; var androidManifest = new AndroidManifest(manifest); changed = (androidManifest.SetHardwareAccelerated(true) || changed); #if UNITYWEBVIEW_ANDROID_USES_CLEARTEXT_TRAFFIC changed = (androidManifest.SetUsesCleartextTraffic(true) || changed); #endif #if UNITYWEBVIEW_ANDROID_ENABLE_CAMERA changed = (androidManifest.AddCamera() || changed); #endif #if UNITYWEBVIEW_ANDROID_ENABLE_MICROPHONE changed = (androidManifest.AddMicrophone() || changed); #endif #if UNITY_5_6_0 || UNITY_5_6_1 changed = (androidManifest.SetActivityName("net.gree.unitywebview.CUnityPlayerActivity") || changed); #endif if (changed) { androidManifest.Save(); Debug.LogError("unitywebview: adjusted AndroidManifest.xml. Please rebuild the app."); } } #endif if (buildTarget == BuildTarget.iOS) { string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj"; PBXProject proj = new PBXProject(); proj.ReadFromString(File.ReadAllText(projPath)); #if UNITY_2019_3_OR_NEWER proj.AddFrameworkToProject(proj.GetUnityFrameworkTargetGuid(), "WebKit.framework", false); #else proj.AddFrameworkToProject(proj.TargetGuidByName("Unity-iPhone"), "WebKit.framework", false); #endif File.WriteAllText(projPath, proj.WriteToString()); } } } internal class AndroidXmlDocument : XmlDocument { private string m_Path; protected XmlNamespaceManager nsMgr; public readonly string AndroidXmlNamespace = "http://schemas.android.com/apk/res/android"; public AndroidXmlDocument(string path) { m_Path = path; using (var reader = new XmlTextReader(m_Path)) { reader.Read(); Load(reader); } nsMgr = new XmlNamespaceManager(NameTable); nsMgr.AddNamespace("android", AndroidXmlNamespace); } public string Save() { return SaveAs(m_Path); } public string SaveAs(string path) { using (var writer = new XmlTextWriter(path, new UTF8Encoding(false))) { writer.Formatting = Formatting.Indented; Save(writer); } return path; } } internal class AndroidManifest : AndroidXmlDocument { private readonly XmlElement ManifestElement; private readonly XmlElement ApplicationElement; public AndroidManifest(string path) : base(path) { ManifestElement = SelectSingleNode("/manifest") as XmlElement; ApplicationElement = SelectSingleNode("/manifest/application") as XmlElement; } private XmlAttribute CreateAndroidAttribute(string key, string value) { XmlAttribute attr = CreateAttribute("android", key, AndroidXmlNamespace); attr.Value = value; return attr; } internal XmlNode GetActivityWithLaunchIntent() { return SelectSingleNode( "/manifest/application/activity[intent-filter/action/@android:name='android.intent.action.MAIN' and " + "intent-filter/category/@android:name='android.intent.category.LAUNCHER']", nsMgr); } internal bool SetUsesCleartextTraffic(bool enabled) { // android:usesCleartextTraffic bool changed = false; if (ApplicationElement.GetAttribute("usesCleartextTraffic", AndroidXmlNamespace) != ((enabled) ? "true" : "false")) { ApplicationElement.SetAttribute("usesCleartextTraffic", AndroidXmlNamespace, (enabled) ? "true" : "false"); changed = true; } return changed; } internal bool SetHardwareAccelerated(bool enabled) { bool changed = false; var activity = GetActivityWithLaunchIntent() as XmlElement; if (activity.GetAttribute("hardwareAccelerated", AndroidXmlNamespace) != ((enabled) ? "true" : "false")) { activity.SetAttribute("hardwareAccelerated", AndroidXmlNamespace, (enabled) ? "true" : "false"); changed = true; } return changed; } internal bool SetActivityName(string name) { bool changed = false; var activity = GetActivityWithLaunchIntent() as XmlElement; if (activity.GetAttribute("name", AndroidXmlNamespace) != name) { activity.SetAttribute("name", AndroidXmlNamespace, name); changed = true; } return changed; } internal bool AddCamera() { bool changed = false; if (SelectNodes("/manifest/uses-permission[@android:name='android.permission.CAMERA']", nsMgr).Count == 0) { var elem = CreateElement("uses-permission"); elem.Attributes.Append(CreateAndroidAttribute("name", "android.permission.CAMERA")); ManifestElement.AppendChild(elem); changed = true; } if (SelectNodes("/manifest/uses-feature[@android:name='android.hardware.camera']", nsMgr).Count == 0) { var elem = CreateElement("uses-feature"); elem.Attributes.Append(CreateAndroidAttribute("name", "android.hardware.camera")); ManifestElement.AppendChild(elem); changed = true; } return changed; } internal bool AddMicrophone() { bool changed = false; if (SelectNodes("/manifest/uses-permission[@android:name='android.permission.MICROPHONE']", nsMgr).Count == 0) { var elem = CreateElement("uses-permission"); elem.Attributes.Append(CreateAndroidAttribute("name", "android.permission.MICROPHONE")); ManifestElement.AppendChild(elem); changed = true; } if (SelectNodes("/manifest/uses-feature[@android:name='android.hardware.microphone']", nsMgr).Count == 0) { var elem = CreateElement("uses-feature"); elem.Attributes.Append(CreateAndroidAttribute("name", "android.hardware.microphone")); ManifestElement.AppendChild(elem); changed = true; } return changed; } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // The GroupCollection lists the captured Capture numbers // contained in a compiled Regex. using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions { /// <summary> /// Represents a sequence of capture substrings. The object is used /// to return the set of captures done by a single capturing group. /// </summary> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Group>))] public class GroupCollection : IList<Group>, IReadOnlyList<Group>, IList { private readonly Match _match; private readonly Hashtable _captureMap; // cache of Group objects fed to the user private Group[] _groups; internal GroupCollection(Match match, Hashtable caps) { _match = match; _captureMap = caps; } public bool IsReadOnly => true; /// <summary> /// Returns the number of groups. /// </summary> public int Count => _match._matchcount.Length; public Group this[int groupnum] => GetGroup(groupnum); public Group this[string groupname] => _match._regex == null ? Group.s_emptyGroup : GetGroup(_match._regex.GroupNumberFromName(groupname)); /// <summary> /// Provides an enumerator in the same order as Item[]. /// </summary> public IEnumerator GetEnumerator() => new Enumerator(this); IEnumerator<Group> IEnumerable<Group>.GetEnumerator() => new Enumerator(this); private Group GetGroup(int groupnum) { if (_captureMap != null) { int groupNumImpl; if (_captureMap.TryGetValue(groupnum, out groupNumImpl)) { return GetGroupImpl(groupNumImpl); } } else if (groupnum < _match._matchcount.Length && groupnum >= 0) { return GetGroupImpl(groupnum); } return Group.s_emptyGroup; } /// <summary> /// Caches the group objects /// </summary> private Group GetGroupImpl(int groupnum) { if (groupnum == 0) return _match; // Construct all the Group objects the first time GetGroup is called if (_groups == null) { _groups = new Group[_match._matchcount.Length - 1]; for (int i = 0; i < _groups.Length; i++) { string groupname = _match._regex.GroupNameFromNumber(i + 1); _groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1], groupname); } } return _groups[groupnum - 1]; } public bool IsSynchronized => false; public object SyncRoot => _match; public void CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); for (int i = arrayIndex, j = 0; j < Count; i++, j++) { array.SetValue(this[j], i); } } public void CopyTo(Group[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (array.Length - arrayIndex < Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); for (int i = arrayIndex, j = 0; j < Count; i++, j++) { array[i] = this[j]; } } int IList<Group>.IndexOf(Group item) { var comparer = EqualityComparer<Group>.Default; for (int i = 0; i < Count; i++) { if (comparer.Equals(this[i], item)) return i; } return -1; } void IList<Group>.Insert(int index, Group item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList<Group>.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } Group IList<Group>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } void ICollection<Group>.Add(Group item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<Group>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<Group>.Contains(Group item) => ((IList<Group>)this).IndexOf(item) >= 0; bool ICollection<Group>.Remove(Group item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } int IList.Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IList.Contains(object value) => value is Group && ((ICollection<Group>)this).Contains((Group)value); int IList.IndexOf(object value) => value is Group ? ((IList<Group>)this).IndexOf((Group)value) : -1; void IList.Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IList.IsFixedSize => true; void IList.Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } private sealed class Enumerator : IEnumerator<Group> { private readonly GroupCollection _collection; private int _index; internal Enumerator(GroupCollection collection) { Debug.Assert(collection != null, "collection cannot be null."); _collection = collection; _index = -1; } public bool MoveNext() { int size = _collection.Count; if (_index >= size) return false; _index++; return _index < size; } public Group Current { get { if (_index < 0 || _index >= _collection.Count) throw new InvalidOperationException(SR.EnumNotStarted); return _collection[_index]; } } object IEnumerator.Current => Current; void IEnumerator.Reset() { _index = -1; } void IDisposable.Dispose() { } } } }
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. namespace System.Data.Services.Client { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; #if !ASTORIA_LIGHT using System.Net; #else using System.Data.Services.Http; #endif using System.Reflection; using System.Collections; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "required for this feature")] public class DataServiceQuery<TElement> : DataServiceQuery, IQueryable<TElement> { #region Private fields. private readonly Expression queryExpression; private readonly DataServiceQueryProvider queryProvider; private QueryComponents queryComponents; #endregion Private fields. private DataServiceQuery(Expression expression, DataServiceQueryProvider provider) { Debug.Assert(null != provider.Context, "null context"); Debug.Assert(expression != null, "null expression"); Debug.Assert(provider is DataServiceQueryProvider, "Currently only support Web Query Provider"); this.queryExpression = expression; this.queryProvider = provider; } #region IQueryable implementation public override Type ElementType { get { return typeof(TElement); } } public override Expression Expression { get { return this.queryExpression; } } public override IQueryProvider Provider { get { return this.queryProvider; } } #endregion public override Uri RequestUri { get { return this.Translate().Uri; } } internal override ProjectionPlan Plan { get { return null; } } internal override QueryComponents QueryComponents { get { return this.Translate(); } } public new IAsyncResult BeginExecute(AsyncCallback callback, object state) { return base.BeginExecute(this, this.queryProvider.Context, callback, state); } public new IEnumerable<TElement> EndExecute(IAsyncResult asyncResult) { return DataServiceRequest.EndExecute<TElement>(this, this.queryProvider.Context, asyncResult); } #if !ASTORIA_LIGHT public new IEnumerable<TElement> Execute() { return this.Execute<TElement>(this.queryProvider.Context, this.Translate()); } #endif public DataServiceQuery<TElement> Expand(string path) { Util.CheckArgumentNull(path, "path"); Util.CheckArgumentNotEmpty(path, "path"); MethodInfo mi = typeof(DataServiceQuery<TElement>).GetMethod("Expand"); return (DataServiceQuery<TElement>)this.Provider.CreateQuery<TElement>( Expression.Call( Expression.Convert(this.Expression, typeof(DataServiceQuery<TElement>.DataServiceOrderedQuery)), mi, new Expression[] { Expression.Constant(path) })); } public DataServiceQuery<TElement> IncludeTotalCount() { MethodInfo mi = typeof(DataServiceQuery<TElement>).GetMethod("IncludeTotalCount"); return (DataServiceQuery<TElement>)this.Provider.CreateQuery<TElement>( Expression.Call( Expression.Convert(this.Expression, typeof(DataServiceQuery<TElement>.DataServiceOrderedQuery)), mi)); } public DataServiceQuery<TElement> AddQueryOption(string name, object value) { Util.CheckArgumentNull(name, "name"); Util.CheckArgumentNull(value, "value"); MethodInfo mi = typeof(DataServiceQuery<TElement>).GetMethod("AddQueryOption"); return (DataServiceQuery<TElement>)this.Provider.CreateQuery<TElement>( Expression.Call( Expression.Convert(this.Expression, typeof(DataServiceQuery<TElement>.DataServiceOrderedQuery)), mi, new Expression[] { Expression.Constant(name), Expression.Constant(value, typeof(object)) })); } #if !ASTORIA_LIGHT public IEnumerator<TElement> GetEnumerator() { return this.Execute().GetEnumerator(); } #else IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator() { throw Error.NotSupported(Strings.DataServiceQuery_EnumerationNotSupportedInSL); } #endif public override string ToString() { try { return base.ToString(); } catch (NotSupportedException e) { return Strings.ALinq_TranslationError(e.Message); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { #if !ASTORIA_LIGHT return this.GetEnumerator(); #else throw Error.NotSupported(); #endif } #if !ASTORIA_LIGHT internal override IEnumerable ExecuteInternal() { return this.Execute(); } #endif internal override IAsyncResult BeginExecuteInternal(AsyncCallback callback, object state) { return this.BeginExecute(callback, state); } internal override IEnumerable EndExecuteInternal(IAsyncResult asyncResult) { return this.EndExecute(asyncResult); } private QueryComponents Translate() { if (this.queryComponents == null) { this.queryComponents = this.queryProvider.Translate(this.queryExpression); } return this.queryComponents; } internal class DataServiceOrderedQuery : DataServiceQuery<TElement>, IOrderedQueryable<TElement>, IOrderedQueryable { internal DataServiceOrderedQuery(Expression expression, DataServiceQueryProvider provider) : base(expression, provider) { } } } }
// 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! namespace Google.Cloud.Retail.V2.Snippets { using Google.Api.Gax; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedProductServiceClientSnippets { /// <summary>Snippet for CreateProduct</summary> public void CreateProductRequestObject() { // Snippet: CreateProduct(CreateProductRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "", }; // Make the request Product response = productServiceClient.CreateProduct(request); // End snippet } /// <summary>Snippet for CreateProductAsync</summary> public async Task CreateProductRequestObjectAsync() { // Snippet: CreateProductAsync(CreateProductRequest, CallSettings) // Additional: CreateProductAsync(CreateProductRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) CreateProductRequest request = new CreateProductRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Product = new Product(), ProductId = "", }; // Make the request Product response = await productServiceClient.CreateProductAsync(request); // End snippet } /// <summary>Snippet for CreateProduct</summary> public void CreateProduct() { // Snippet: CreateProduct(string, Product, string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]"; Product product = new Product(); string productId = ""; // Make the request Product response = productServiceClient.CreateProduct(parent, product, productId); // End snippet } /// <summary>Snippet for CreateProductAsync</summary> public async Task CreateProductAsync() { // Snippet: CreateProductAsync(string, Product, string, CallSettings) // Additional: CreateProductAsync(string, Product, string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]"; Product product = new Product(); string productId = ""; // Make the request Product response = await productServiceClient.CreateProductAsync(parent, product, productId); // End snippet } /// <summary>Snippet for CreateProduct</summary> public void CreateProductResourceNames() { // Snippet: CreateProduct(BranchName, Product, string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); Product product = new Product(); string productId = ""; // Make the request Product response = productServiceClient.CreateProduct(parent, product, productId); // End snippet } /// <summary>Snippet for CreateProductAsync</summary> public async Task CreateProductResourceNamesAsync() { // Snippet: CreateProductAsync(BranchName, Product, string, CallSettings) // Additional: CreateProductAsync(BranchName, Product, string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); Product product = new Product(); string productId = ""; // Make the request Product response = await productServiceClient.CreateProductAsync(parent, product, productId); // End snippet } /// <summary>Snippet for GetProduct</summary> public void GetProductRequestObject() { // Snippet: GetProduct(GetProductRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; // Make the request Product response = productServiceClient.GetProduct(request); // End snippet } /// <summary>Snippet for GetProductAsync</summary> public async Task GetProductRequestObjectAsync() { // Snippet: GetProductAsync(GetProductRequest, CallSettings) // Additional: GetProductAsync(GetProductRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) GetProductRequest request = new GetProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; // Make the request Product response = await productServiceClient.GetProductAsync(request); // End snippet } /// <summary>Snippet for GetProduct</summary> public void GetProduct() { // Snippet: GetProduct(string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Product response = productServiceClient.GetProduct(name); // End snippet } /// <summary>Snippet for GetProductAsync</summary> public async Task GetProductAsync() { // Snippet: GetProductAsync(string, CallSettings) // Additional: GetProductAsync(string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Product response = await productServiceClient.GetProductAsync(name); // End snippet } /// <summary>Snippet for GetProduct</summary> public void GetProductResourceNames() { // Snippet: GetProduct(ProductName, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ProductName name = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Product response = productServiceClient.GetProduct(name); // End snippet } /// <summary>Snippet for GetProductAsync</summary> public async Task GetProductResourceNamesAsync() { // Snippet: GetProductAsync(ProductName, CallSettings) // Additional: GetProductAsync(ProductName, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ProductName name = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Product response = await productServiceClient.GetProductAsync(name); // End snippet } /// <summary>Snippet for ListProducts</summary> public void ListProductsRequestObject() { // Snippet: ListProducts(ListProductsRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ListProductsRequest request = new ListProductsRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Filter = "", ReadMask = new FieldMask(), }; // Make the request PagedEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProducts(request); // Iterate over all response items, lazily performing RPCs as required foreach (Product item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProductsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProductsAsync</summary> public async Task ListProductsRequestObjectAsync() { // Snippet: ListProductsAsync(ListProductsRequest, CallSettings) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ListProductsRequest request = new ListProductsRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Filter = "", ReadMask = new FieldMask(), }; // Make the request PagedAsyncEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProductsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Product item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProductsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProducts</summary> public void ListProducts() { // Snippet: ListProducts(string, string, int?, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]"; // Make the request PagedEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProducts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Product item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProductsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProductsAsync</summary> public async Task ListProductsAsync() { // Snippet: ListProductsAsync(string, string, int?, CallSettings) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]"; // Make the request PagedAsyncEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProductsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Product item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProductsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProducts</summary> public void ListProductsResourceNames() { // Snippet: ListProducts(BranchName, string, int?, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); // Make the request PagedEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProducts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Product item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProductsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProductsAsync</summary> public async Task ListProductsResourceNamesAsync() { // Snippet: ListProductsAsync(BranchName, string, int?, CallSettings) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) BranchName parent = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"); // Make the request PagedAsyncEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProductsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Product item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProductsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Product item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Product> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Product item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateProduct</summary> public void UpdateProductRequestObject() { // Snippet: UpdateProduct(UpdateProductRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new FieldMask(), AllowMissing = false, }; // Make the request Product response = productServiceClient.UpdateProduct(request); // End snippet } /// <summary>Snippet for UpdateProductAsync</summary> public async Task UpdateProductRequestObjectAsync() { // Snippet: UpdateProductAsync(UpdateProductRequest, CallSettings) // Additional: UpdateProductAsync(UpdateProductRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) UpdateProductRequest request = new UpdateProductRequest { Product = new Product(), UpdateMask = new FieldMask(), AllowMissing = false, }; // Make the request Product response = await productServiceClient.UpdateProductAsync(request); // End snippet } /// <summary>Snippet for UpdateProduct</summary> public void UpdateProduct() { // Snippet: UpdateProduct(Product, FieldMask, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) Product product = new Product(); FieldMask updateMask = new FieldMask(); // Make the request Product response = productServiceClient.UpdateProduct(product, updateMask); // End snippet } /// <summary>Snippet for UpdateProductAsync</summary> public async Task UpdateProductAsync() { // Snippet: UpdateProductAsync(Product, FieldMask, CallSettings) // Additional: UpdateProductAsync(Product, FieldMask, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) Product product = new Product(); FieldMask updateMask = new FieldMask(); // Make the request Product response = await productServiceClient.UpdateProductAsync(product, updateMask); // End snippet } /// <summary>Snippet for DeleteProduct</summary> public void DeleteProductRequestObject() { // Snippet: DeleteProduct(DeleteProductRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; // Make the request productServiceClient.DeleteProduct(request); // End snippet } /// <summary>Snippet for DeleteProductAsync</summary> public async Task DeleteProductRequestObjectAsync() { // Snippet: DeleteProductAsync(DeleteProductRequest, CallSettings) // Additional: DeleteProductAsync(DeleteProductRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) DeleteProductRequest request = new DeleteProductRequest { ProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), }; // Make the request await productServiceClient.DeleteProductAsync(request); // End snippet } /// <summary>Snippet for DeleteProduct</summary> public void DeleteProduct() { // Snippet: DeleteProduct(string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request productServiceClient.DeleteProduct(name); // End snippet } /// <summary>Snippet for DeleteProductAsync</summary> public async Task DeleteProductAsync() { // Snippet: DeleteProductAsync(string, CallSettings) // Additional: DeleteProductAsync(string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request await productServiceClient.DeleteProductAsync(name); // End snippet } /// <summary>Snippet for DeleteProduct</summary> public void DeleteProductResourceNames() { // Snippet: DeleteProduct(ProductName, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ProductName name = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request productServiceClient.DeleteProduct(name); // End snippet } /// <summary>Snippet for DeleteProductAsync</summary> public async Task DeleteProductResourceNamesAsync() { // Snippet: DeleteProductAsync(ProductName, CallSettings) // Additional: DeleteProductAsync(ProductName, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ProductName name = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request await productServiceClient.DeleteProductAsync(name); // End snippet } /// <summary>Snippet for ImportProducts</summary> public void ImportProductsRequestObject() { // Snippet: ImportProducts(ImportProductsRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ImportProductsRequest request = new ImportProductsRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), InputConfig = new ProductInputConfig(), ErrorsConfig = new ImportErrorsConfig(), UpdateMask = new FieldMask(), ReconciliationMode = ImportProductsRequest.Types.ReconciliationMode.Unspecified, RequestId = "", NotificationPubsubTopic = "", }; // Make the request Operation<ImportProductsResponse, ImportMetadata> response = productServiceClient.ImportProducts(request); // Poll until the returned long-running operation is complete Operation<ImportProductsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result ImportProductsResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ImportProductsResponse, ImportMetadata> retrievedResponse = productServiceClient.PollOnceImportProducts(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ImportProductsResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ImportProductsAsync</summary> public async Task ImportProductsRequestObjectAsync() { // Snippet: ImportProductsAsync(ImportProductsRequest, CallSettings) // Additional: ImportProductsAsync(ImportProductsRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ImportProductsRequest request = new ImportProductsRequest { ParentAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), InputConfig = new ProductInputConfig(), ErrorsConfig = new ImportErrorsConfig(), UpdateMask = new FieldMask(), ReconciliationMode = ImportProductsRequest.Types.ReconciliationMode.Unspecified, RequestId = "", NotificationPubsubTopic = "", }; // Make the request Operation<ImportProductsResponse, ImportMetadata> response = await productServiceClient.ImportProductsAsync(request); // Poll until the returned long-running operation is complete Operation<ImportProductsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result ImportProductsResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ImportProductsResponse, ImportMetadata> retrievedResponse = await productServiceClient.PollOnceImportProductsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ImportProductsResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetInventory</summary> public void SetInventoryRequestObject() { // Snippet: SetInventory(SetInventoryRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) SetInventoryRequest request = new SetInventoryRequest { Inventory = new Product(), SetMask = new FieldMask(), SetTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<SetInventoryResponse, SetInventoryMetadata> response = productServiceClient.SetInventory(request); // Poll until the returned long-running operation is complete Operation<SetInventoryResponse, SetInventoryMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result SetInventoryResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<SetInventoryResponse, SetInventoryMetadata> retrievedResponse = productServiceClient.PollOnceSetInventory(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result SetInventoryResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetInventoryAsync</summary> public async Task SetInventoryRequestObjectAsync() { // Snippet: SetInventoryAsync(SetInventoryRequest, CallSettings) // Additional: SetInventoryAsync(SetInventoryRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) SetInventoryRequest request = new SetInventoryRequest { Inventory = new Product(), SetMask = new FieldMask(), SetTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<SetInventoryResponse, SetInventoryMetadata> response = await productServiceClient.SetInventoryAsync(request); // Poll until the returned long-running operation is complete Operation<SetInventoryResponse, SetInventoryMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result SetInventoryResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<SetInventoryResponse, SetInventoryMetadata> retrievedResponse = await productServiceClient.PollOnceSetInventoryAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result SetInventoryResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetInventory</summary> public void SetInventory() { // Snippet: SetInventory(Product, FieldMask, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) Product inventory = new Product(); FieldMask setMask = new FieldMask(); // Make the request Operation<SetInventoryResponse, SetInventoryMetadata> response = productServiceClient.SetInventory(inventory, setMask); // Poll until the returned long-running operation is complete Operation<SetInventoryResponse, SetInventoryMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result SetInventoryResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<SetInventoryResponse, SetInventoryMetadata> retrievedResponse = productServiceClient.PollOnceSetInventory(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result SetInventoryResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetInventoryAsync</summary> public async Task SetInventoryAsync() { // Snippet: SetInventoryAsync(Product, FieldMask, CallSettings) // Additional: SetInventoryAsync(Product, FieldMask, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) Product inventory = new Product(); FieldMask setMask = new FieldMask(); // Make the request Operation<SetInventoryResponse, SetInventoryMetadata> response = await productServiceClient.SetInventoryAsync(inventory, setMask); // Poll until the returned long-running operation is complete Operation<SetInventoryResponse, SetInventoryMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result SetInventoryResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<SetInventoryResponse, SetInventoryMetadata> retrievedResponse = await productServiceClient.PollOnceSetInventoryAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result SetInventoryResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlaces</summary> public void AddFulfillmentPlacesRequestObject() { // Snippet: AddFulfillmentPlaces(AddFulfillmentPlacesRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) AddFulfillmentPlacesRequest request = new AddFulfillmentPlacesRequest { ProductAsProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Type = "", PlaceIds = { "", }, AddTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = productServiceClient.AddFulfillmentPlaces(request); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceAddFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlacesAsync</summary> public async Task AddFulfillmentPlacesRequestObjectAsync() { // Snippet: AddFulfillmentPlacesAsync(AddFulfillmentPlacesRequest, CallSettings) // Additional: AddFulfillmentPlacesAsync(AddFulfillmentPlacesRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) AddFulfillmentPlacesRequest request = new AddFulfillmentPlacesRequest { ProductAsProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Type = "", PlaceIds = { "", }, AddTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = await productServiceClient.AddFulfillmentPlacesAsync(request); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceAddFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlaces</summary> public void AddFulfillmentPlaces() { // Snippet: AddFulfillmentPlaces(string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string product = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = productServiceClient.AddFulfillmentPlaces(product); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceAddFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlacesAsync</summary> public async Task AddFulfillmentPlacesAsync() { // Snippet: AddFulfillmentPlacesAsync(string, CallSettings) // Additional: AddFulfillmentPlacesAsync(string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string product = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = await productServiceClient.AddFulfillmentPlacesAsync(product); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceAddFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlaces</summary> public void AddFulfillmentPlacesResourceNames() { // Snippet: AddFulfillmentPlaces(ProductName, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ProductName product = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = productServiceClient.AddFulfillmentPlaces(product); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceAddFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddFulfillmentPlacesAsync</summary> public async Task AddFulfillmentPlacesResourceNamesAsync() { // Snippet: AddFulfillmentPlacesAsync(ProductName, CallSettings) // Additional: AddFulfillmentPlacesAsync(ProductName, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ProductName product = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> response = await productServiceClient.AddFulfillmentPlacesAsync(product); // Poll until the returned long-running operation is complete Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AddFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddFulfillmentPlacesResponse, AddFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceAddFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlaces</summary> public void RemoveFulfillmentPlacesRequestObject() { // Snippet: RemoveFulfillmentPlaces(RemoveFulfillmentPlacesRequest, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) RemoveFulfillmentPlacesRequest request = new RemoveFulfillmentPlacesRequest { ProductAsProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Type = "", PlaceIds = { "", }, RemoveTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = productServiceClient.RemoveFulfillmentPlaces(request); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceRemoveFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlacesAsync</summary> public async Task RemoveFulfillmentPlacesRequestObjectAsync() { // Snippet: RemoveFulfillmentPlacesAsync(RemoveFulfillmentPlacesRequest, CallSettings) // Additional: RemoveFulfillmentPlacesAsync(RemoveFulfillmentPlacesRequest, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) RemoveFulfillmentPlacesRequest request = new RemoveFulfillmentPlacesRequest { ProductAsProductName = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"), Type = "", PlaceIds = { "", }, RemoveTime = new Timestamp(), AllowMissing = false, }; // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = await productServiceClient.RemoveFulfillmentPlacesAsync(request); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceRemoveFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlaces</summary> public void RemoveFulfillmentPlaces() { // Snippet: RemoveFulfillmentPlaces(string, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) string product = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = productServiceClient.RemoveFulfillmentPlaces(product); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceRemoveFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlacesAsync</summary> public async Task RemoveFulfillmentPlacesAsync() { // Snippet: RemoveFulfillmentPlacesAsync(string, CallSettings) // Additional: RemoveFulfillmentPlacesAsync(string, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) string product = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]/products/[PRODUCT]"; // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = await productServiceClient.RemoveFulfillmentPlacesAsync(product); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceRemoveFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlaces</summary> public void RemoveFulfillmentPlacesResourceNames() { // Snippet: RemoveFulfillmentPlaces(ProductName, CallSettings) // Create client ProductServiceClient productServiceClient = ProductServiceClient.Create(); // Initialize request argument(s) ProductName product = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = productServiceClient.RemoveFulfillmentPlaces(product); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = productServiceClient.PollOnceRemoveFulfillmentPlaces(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemoveFulfillmentPlacesAsync</summary> public async Task RemoveFulfillmentPlacesResourceNamesAsync() { // Snippet: RemoveFulfillmentPlacesAsync(ProductName, CallSettings) // Additional: RemoveFulfillmentPlacesAsync(ProductName, CancellationToken) // Create client ProductServiceClient productServiceClient = await ProductServiceClient.CreateAsync(); // Initialize request argument(s) ProductName product = ProductName.FromProjectLocationCatalogBranchProduct("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]", "[PRODUCT]"); // Make the request Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> response = await productServiceClient.RemoveFulfillmentPlacesAsync(product); // Poll until the returned long-running operation is complete Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result RemoveFulfillmentPlacesResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemoveFulfillmentPlacesResponse, RemoveFulfillmentPlacesMetadata> retrievedResponse = await productServiceClient.PollOnceRemoveFulfillmentPlacesAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemoveFulfillmentPlacesResponse retrievedResult = retrievedResponse.Result; } // End snippet } } }
using System; using System.Collections.Generic; using System.Reflection; using Orleans.Runtime; namespace Orleans.Streams { [Serializable] internal class ImplicitStreamSubscriberTable { private readonly Dictionary<string, HashSet<int>> table; internal ImplicitStreamSubscriberTable() { table = new Dictionary<string, HashSet<int>>(); } /// <summary>Initializes any implicit stream subscriptions specified for a grain class type. If the grain class specified does not have any associated namespaces, then nothing is done.</summary> /// <param name="grainClasses">A grain class type.</param> /// <exception cref="System.ArgumentException"> /// Duplicate specification of namespace "...". /// </exception> internal void InitImplicitStreamSubscribers(IEnumerable<Type> grainClasses) { foreach (var grainClass in grainClasses) { if (!TypeUtils.IsGrainClass(grainClass)) { continue; } // we collect all namespaces that the specified grain class should implicitly subscribe to. ISet<string> namespaces = GetNamespacesFromAttributes(grainClass); if (null == namespaces) continue; if (namespaces.Count > 0) { // the grain class is subscribed to at least one namespace. in order to create a grain reference later, we need a qualifying interface but it doesn't matter which (because we'll be creating references to extensions), so we'll take the first interface in the sequence. AddImplicitSubscriber(grainClass, namespaces); } } } /// <summary> /// Retrieve a map of implicit subscriptionsIds to implicit subscribers, given a stream ID. This method throws an exception if there's no namespace associated with the stream ID. /// </summary> /// <param name="streamId">A stream ID.</param> /// <returns>A set of references to implicitly subscribed grains. They are expected to support the streaming consumer extension.</returns> /// <exception cref="System.ArgumentException">The stream ID doesn't have an associated namespace.</exception> /// <exception cref="System.InvalidOperationException">Internal invariant violation.</exception> internal IDictionary<Guid, IStreamConsumerExtension> GetImplicitSubscribers(StreamId streamId) { if (String.IsNullOrWhiteSpace(streamId.Namespace)) { throw new ArgumentException("The stream ID doesn't have an associated namespace.", "streamId"); } HashSet<int> entry; var result = new Dictionary<Guid, IStreamConsumerExtension>(); if (table.TryGetValue(streamId.Namespace, out entry)) { foreach (var i in entry) { IStreamConsumerExtension consumer = MakeConsumerReference(streamId.Guid, i); Guid subscriptionGuid = MakeSubscriptionGuid(i, streamId); if (result.ContainsKey(subscriptionGuid)) { throw new InvalidOperationException(string.Format("Internal invariant violation: generated duplicate subscriber reference: {0}, subscriptionId: {1}", consumer, subscriptionGuid)); } result.Add(subscriptionGuid, consumer); } return result; } return result; } /// <summary> /// Determines whether the specified grain is an implicit subscriber of a given stream. /// </summary> /// <param name="grainId">The grain identifier.</param> /// <param name="streamId">The stream identifier.</param> /// <returns>true if the grain id describes an implicit subscriber of the stream described by the stream id.</returns> internal bool IsImplicitSubscriber(GrainId grainId, StreamId streamId) { return HasImplicitSubscription(streamId.Namespace, grainId.GetTypeCode()); } /// <summary> /// Try to get the implicit subscriptionId. /// If an implicit subscription exists, return a subscription Id that is unique per grain type, grainId, namespace combination. /// </summary> /// <param name="grainId"></param> /// <param name="streamId"></param> /// <param name="subscriptionId"></param> /// <returns></returns> internal bool TryGetImplicitSubscriptionGuid(GrainId grainId, StreamId streamId, out Guid subscriptionId) { subscriptionId = Guid.Empty; if (!HasImplicitSubscription(streamId.Namespace, grainId.GetTypeCode())) { return false; } // make subscriptionId subscriptionId = MakeSubscriptionGuid(grainId, streamId); return true; } /// <summary> /// Create a subscriptionId that is unique per grainId, grainType, namespace combination. /// </summary> /// <param name="grainId"></param> /// <param name="streamId"></param> /// <returns></returns> private Guid MakeSubscriptionGuid(GrainId grainId, StreamId streamId) { // first int in guid is grain type code int grainIdTypeCode = grainId.GetTypeCode(); return MakeSubscriptionGuid(grainIdTypeCode, streamId); } /// <summary> /// Create a subscriptionId that is unique per grainId, grainType, namespace combination. /// </summary> /// <param name="grainIdTypeCode"></param> /// <param name="streamId"></param> /// <returns></returns> private Guid MakeSubscriptionGuid(int grainIdTypeCode, StreamId streamId) { JenkinsHash jenkinsHash = JenkinsHash.Factory.GetHashGenerator(); // next 2 shorts ing guid are from namespace hash uint namespaceHash = jenkinsHash.ComputeHash(streamId.Namespace); byte[] namespaceHashByes = BitConverter.GetBytes(namespaceHash); short s1 = BitConverter.ToInt16(namespaceHashByes, 0); short s2 = BitConverter.ToInt16(namespaceHashByes, 2); // Tailing 8 bytes of the guid are from the hash of the streamId Guid and a hash of the provider name. // get streamId guid hash code uint streamIdGuidHash = jenkinsHash.ComputeHash(streamId.Guid.ToByteArray()); // get provider name hash code uint providerHash = jenkinsHash.ComputeHash(streamId.ProviderName); // build guid tailing 8 bytes from grainIdHash and the hash of the provider name. var tail = new List<byte>(); tail.AddRange(BitConverter.GetBytes(streamIdGuidHash)); tail.AddRange(BitConverter.GetBytes(providerHash)); // make guid. // - First int is grain type // - Two shorts from namespace hash // - 8 byte tail from streamId Guid and provider name hash. return SubscriptionMarker.MarkAsImplictSubscriptionId(new Guid(grainIdTypeCode, s1, s2, tail.ToArray())); } private bool HasImplicitSubscription(string streamNamespace, int grainIdTypeCode) { if (String.IsNullOrWhiteSpace(streamNamespace)) { return false; } HashSet<int> entry; return (table.TryGetValue(streamNamespace, out entry) && // if we don't have implictit subscriptions for this namespace, fail out entry.Contains(grainIdTypeCode)); // if we don't have an implicit subscription for this type of grain on this namespace, fail out } /// <summary> /// Add an implicit subscriber to the table. /// </summary> /// <param name="grainClass">Type of the grain class whose instances subscribe to the specified namespaces.</param> /// <param name="namespaces">Namespaces instances of the grain class should subscribe to.</param> /// <exception cref="System.ArgumentException"> /// No namespaces specified. /// or /// Duplicate specification of namespace "...". /// </exception> private void AddImplicitSubscriber(Type grainClass, ISet<string> namespaces) { // convert IEnumerable<> to an array without copying, if possible. if (namespaces.Count == 0) { throw new ArgumentException("no namespaces specified", "namespaces"); } // we'll need the class type code. int implTypeCode = CodeGeneration.GrainInterfaceUtils.GetGrainClassTypeCode(grainClass); foreach (string s in namespaces) { // first, we trim whitespace off of the namespace string. leaving these would lead to misleading log messages. string key = s.Trim(); // if the table already holds the namespace we're looking at, then we don't need to create a new entry. each entry is a dictionary that holds associations between class names and interface ids. e.g.: // // "namespace0" -> HashSet {implTypeCode.0, implTypeCode.1, ..., implTypeCode.n} // // each class in the entry used the ImplicitStreamSubscriptionAtrribute with the associated namespace. this information will be used later to create grain references on-demand. we must use string representations to ensure that this information is serializable. if (table.ContainsKey(key)) { // an entry already exists. we append a class/interface association to the current set. HashSet<int> entries = table[key]; if (!entries.Add(implTypeCode)) { throw new InvalidOperationException(String.Format("attempt to initialize implicit subscriber more than once (key={0}, implTypeCode={1}).", key, implTypeCode)); } } else { // an entry does not already exist. we create a new one with one class/interface association. table[key] = new HashSet<int> { implTypeCode }; } } } /// <summary> /// Create a reference to a grain that we expect to support the stream consumer extension. /// </summary> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="implTypeCode">The type code of the grain interface.</param> /// <returns></returns> private IStreamConsumerExtension MakeConsumerReference(Guid primaryKey, int implTypeCode) { GrainId grainId = GrainId.GetGrainId(implTypeCode, primaryKey); IAddressable addressable = GrainReference.FromGrainId(grainId); return addressable.Cast<IStreamConsumerExtension>(); } /// <summary> /// Collects the namespaces associated with a grain class type through the use of ImplicitStreamSubscriptionAttribute. /// </summary> /// <param name="grainClass">A grain class type that might have ImplicitStreamSubscriptionAttributes associated with it.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">grainType does not describe a grain class.</exception> /// <exception cref="System.InvalidOperationException">duplicate specification of ImplicitConsumerActivationAttribute(...).</exception> private static ISet<string> GetNamespacesFromAttributes(Type grainClass) { if (!TypeUtils.IsGrainClass(grainClass)) { throw new ArgumentException(string.Format("{0} is not a grain class.", grainClass.FullName), "grainClass"); } var attribs = grainClass.GetTypeInfo().GetCustomAttributes<ImplicitStreamSubscriptionAttribute>(inherit: false); // otherwise, we'll consider all of them and aggregate the specifications. duplicates will not be permitted. var result = new HashSet<string>(); foreach (var attrib in attribs) { if (string.IsNullOrWhiteSpace(attrib.Namespace)) { throw new InvalidOperationException("ImplicitConsumerActivationAttribute argument cannot be null nor whitespace"); } string trimmed = attrib.Namespace; if (!result.Add(trimmed)) { throw new InvalidOperationException(string.Format("duplicate specification of attribute ImplicitConsumerActivationAttribute({0}).", attrib.Namespace)); } } return result; } } }
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Security; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Threading.Tasks; using UIKit; namespace TokenSecuredChallenge { public partial class TokenSecuredChallenge : UIViewController { // Constants for the public and secured map service URLs private const string PublicMapServiceUrl = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"; private const string SecureMapServiceUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA_secure_user1/MapServer"; // Constants for the public and secured layer names private const string PublicLayerName = "World Street Map - Public"; private const string SecureLayerName = "USA - Secure"; // Use a TaskCompletionSource to store the result of a login task TaskCompletionSource<Credential> _loginTaskCompletionSource; // Store the map view displayed in the app MapView _myMapView; // Labels to show layer load status UILabel _publicLayerLabel; UILabel _secureLayerLabel; // View containing login controls to display over the map view LoginOverlay _loginUI; // Default constructor public TokenSecuredChallenge() : base("TokenSecuredChallenge", null) { } // Constructor overload public TokenSecuredChallenge(IntPtr p) : base(p) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Call a function to create the user interface CreateLayout(); // Call a function to initialize the app Initialize(); } private void CreateLayout() { // Create a label for showing the load status for the public service var label1ViewFrame = new CoreGraphics.CGRect(10, 30, View.Bounds.Width-10, 20); _publicLayerLabel = new UILabel(label1ViewFrame); _publicLayerLabel.TextColor = UIColor.Gray; _publicLayerLabel.Font = _publicLayerLabel.Font.WithSize(12); _publicLayerLabel.Text = PublicLayerName; // Create a label to show the load status of the secured layer var label2ViewFrame = new CoreGraphics.CGRect(10, 55, View.Bounds.Width-10, 20); _secureLayerLabel = new UILabel(label2ViewFrame); _secureLayerLabel.TextColor = UIColor.Gray; _secureLayerLabel.Font = _secureLayerLabel.Font.WithSize(12); _secureLayerLabel.Text = SecureLayerName; // Setup the visual frame for the MapView var mapViewRect = new CoreGraphics.CGRect(0, 80, View.Bounds.Width, View.Bounds.Height - 80); // Create a map view with a basemap _myMapView = new MapView(); _myMapView.Frame = mapViewRect; // Add the map view and button to the page View.AddSubviews(_publicLayerLabel, _secureLayerLabel, _myMapView); } private void Initialize() { // Define a challenge handler method for the AuthenticationManager // (this method handles getting credentials when a secured resource is encountered) AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync); // Create the public layer and provide a name var publicLayer = new ArcGISTiledLayer(new Uri(PublicMapServiceUrl)); publicLayer.Name = PublicLayerName; // Create the secured layer and provide a name var tokenSecuredLayer = new ArcGISMapImageLayer(new Uri(SecureMapServiceUrl)); tokenSecuredLayer.Name = SecureLayerName; // Track the load status of each layer with a LoadStatusChangedEvent handler publicLayer.LoadStatusChanged += LayerLoadStatusChanged; tokenSecuredLayer.LoadStatusChanged += LayerLoadStatusChanged; // Create a new map and add the layers var myMap = new Map(); myMap.OperationalLayers.Add(publicLayer); myMap.OperationalLayers.Add(tokenSecuredLayer); // Add the map to the map view _myMapView.Map = myMap; } // Handle the load status changed event for the public and token-secured layers private void LayerLoadStatusChanged(object sender, Esri.ArcGISRuntime.LoadStatusEventArgs e) { // Get the layer that triggered the event var layer = sender as Layer; // Get the label for this layer UILabel labelToUpdate = null; if(layer.Name == PublicLayerName) { labelToUpdate = _publicLayerLabel; } else { labelToUpdate = _secureLayerLabel; } // Create the text string and font color to describe the current load status var updateText = layer.Name; var textColor = UIColor.Gray; switch (e.Status) { case Esri.ArcGISRuntime.LoadStatus.FailedToLoad: updateText = layer.Name + " (Load failed)"; textColor = UIColor.Red; break; case Esri.ArcGISRuntime.LoadStatus.Loaded: updateText = layer.Name + " (Loaded)"; textColor = UIColor.Green; break; case Esri.ArcGISRuntime.LoadStatus.Loading: updateText = layer.Name + " (Loading ...)"; textColor = UIColor.Gray; break; case Esri.ArcGISRuntime.LoadStatus.NotLoaded: updateText = layer.Name + " (Not loaded)"; textColor = UIColor.LightGray; break; } // Update the layer label on the UI thread this.BeginInvokeOnMainThread(() => { labelToUpdate.Text = updateText; labelToUpdate.TextColor = textColor; }); } // AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential private async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info) { // Return if authentication is already in process if (_loginTaskCompletionSource != null && !_loginTaskCompletionSource.Task.IsCanceled) { return null; } // Create a new TaskCompletionSource for the login operation // (passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property) _loginTaskCompletionSource = new TaskCompletionSource<Credential>(info); // Show the login controls on the UI thread // OnLoginInfoEntered event will return the values entered (username, password, and domain) InvokeOnMainThread(() => ShowLoginUI()); // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button) return await _loginTaskCompletionSource.Task; } private void ShowLoginUI() { // Get the URL for the service being requested var info = _loginTaskCompletionSource.Task.AsyncState as CredentialRequestInfo; var serviceUrl = info.ServiceUri.GetLeftPart(UriPartial.Path); // Create a view to show login controls over the map view var ovBounds = new CoreGraphics.CGRect(0,80, _myMapView.Bounds.Width, _myMapView.Bounds.Height - 80); _loginUI = new LoginOverlay(ovBounds, 0.75f, UIColor.White, serviceUrl); // Handle the login event to get the login entered by the user _loginUI.OnLoginInfoEntered += LoginEntered; // Handle the cancel event when the user closes the dialog without entering a login _loginUI.OnCanceled += LoginCanceled; // Add the login UI view (will display semi-transparent over the map view) View.Add(_loginUI); } // Handle the OnLoginEntered event from the login UI // LoginEventArgs contains the username and password that were entered private async void LoginEntered(object sender, LoginEventArgs e) { // Make sure the task completion source has all the information needed if (_loginTaskCompletionSource == null || _loginTaskCompletionSource.Task == null || _loginTaskCompletionSource.Task.AsyncState == null) { return; } try { // Get the associated CredentialRequestInfo (will need the URI of the service being accessed) CredentialRequestInfo requestInfo = _loginTaskCompletionSource.Task.AsyncState as CredentialRequestInfo; // Create a token credential using the provided username and password TokenCredential userCredentials = await AuthenticationManager.Current.GenerateCredentialAsync (requestInfo.ServiceUri, e.Username, e.Password, requestInfo.GenerateTokenOptions); // Set the result on the task completion source _loginTaskCompletionSource.TrySetResult(userCredentials); } catch (Exception ex) { // Unable to create credential, set the exception on the task completion source _loginTaskCompletionSource.TrySetException(ex); } finally { // Get rid of the login controls _loginUI.Hide(); _loginUI = null; } } private void LoginCanceled(object sender, EventArgs e) { // Remove the login UI _loginUI.Hide(); _loginUI = null; // Cancel the task completion source task _loginTaskCompletionSource.TrySetCanceled(); } } }
// 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.Text; /// <summary> /// GetBytes(System.String,System.Int32,System.Int32,System.Byte[],System.Int32) /// </summary> public class EncodingGetBytes5 { #region Private Fields private const string c_TEST_STR = "za\u0306\u01FD\u03B2\uD8FF\uDCFF"; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; return retVal; } #region Positive Test Cases public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(System.String) with UTF8."); try { Encoding u8 = Encoding.UTF8; byte[] bytes = new byte[u8.GetMaxByteCount(3)]; if (u8.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6) { TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method GetBytes(System.String) with Unicode."); try { Encoding u16LE = Encoding.Unicode; byte[] bytes = new byte[u16LE.GetMaxByteCount(3)]; if (u16LE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6) { TestLibrary.TestFramework.LogError("003.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method GetBytes(System.String) with BigEndianUnicode."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; if (u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6) { TestLibrary.TestFramework.LogError("004.1", "Method GetBytes Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown."); try { string testNullStr = null; Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(testNullStr, 4, 3, bytes, bytes.GetLowerBound(0)); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = null; int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, 1); TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(c_TEST_STR, -1, 3, bytes, bytes.GetLowerBound(0)); TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(c_TEST_STR, 4, -1, bytes, bytes.GetLowerBound(0)); TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, -1); TestLibrary.TestFramework.LogError("105.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("105.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(c_TEST_STR, c_TEST_STR.Length - 1, 3, bytes, bytes.GetLowerBound(0)); TestLibrary.TestFramework.LogError("106.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException is not thrown."); try { Encoding u16BE = Encoding.BigEndianUnicode; byte[] bytes = new byte[u16BE.GetMaxByteCount(3)]; int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.Length - 1); TestLibrary.TestFramework.LogError("107.1", "ArgumentException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("107.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EncodingGetBytes5 test = new EncodingGetBytes5(); TestLibrary.TestFramework.BeginTestCase("EncodingGetBytes5"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Method private bool VerifyByteItemValue(byte[] getBytes, byte[] actualBytes) { if (getBytes.Length != actualBytes.Length) return false; else { for (int i = 0; i < getBytes.Length; i++) if (getBytes[i] != actualBytes[i]) return false; } return true; } #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.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Data.OleDb { public sealed class OleDbCommand : DbCommand, ICloneable, IDbCommand { // command data private string _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; private OleDbConnection _connection; private OleDbTransaction _transaction; private OleDbParameterCollection _parameters; // native information private UnsafeNativeMethods.ICommandText _icommandText; // if executing with a different CommandBehavior.KeyInfo behavior // original ICommandText must be released and a new ICommandText generated private CommandBehavior commandBehavior; private Bindings _dbBindings; internal bool canceling; private bool _isPrepared; private bool _executeQuery; private bool _trackingForClose; private bool _hasDataReader; private IntPtr _recordsAffected; private int _changeID; private int _lastChangeID; public OleDbCommand() : base() { GC.SuppressFinalize(this); } public OleDbCommand(string cmdText) : this() { CommandText = cmdText; } public OleDbCommand(string cmdText, OleDbConnection connection) : this() { CommandText = cmdText; Connection = connection; } public OleDbCommand(string cmdText, OleDbConnection connection, OleDbTransaction transaction) : this() { CommandText = cmdText; Connection = connection; Transaction = transaction; } private OleDbCommand(OleDbCommand from) : this() { // Clone CommandText = from.CommandText; CommandTimeout = from.CommandTimeout; CommandType = from.CommandType; Connection = from.Connection; DesignTimeVisible = from.DesignTimeVisible; UpdatedRowSource = from.UpdatedRowSource; Transaction = from.Transaction; OleDbParameterCollection parameters = Parameters; foreach (object parameter in from.Parameters) { parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter); } } private Bindings ParameterBindings { get { return _dbBindings; } set { Bindings bindings = _dbBindings; _dbBindings = value; if ((null != bindings) && (value != bindings)) { bindings.Dispose(); } } } [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] override public string CommandText { get { string value = _commandText; return ((null != value) ? value : string.Empty); } set { if (0 != ADP.SrcCompare(_commandText, value)) { PropertyChanging(); _commandText = value; } } } override public int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000 get { return _commandTimeout; } set { if (value < 0) { throw ADP.InvalidCommandTimeout(value); } if (value != _commandTimeout) { PropertyChanging(); _commandTimeout = value; } } } public void ResetCommandTimeout() { // V1.2.3300 if (ADP.DefaultCommandTimeout != _commandTimeout) { PropertyChanging(); _commandTimeout = ADP.DefaultCommandTimeout; } } [DefaultValue(System.Data.CommandType.Text)] [RefreshProperties(RefreshProperties.All)] override public CommandType CommandType { get { CommandType cmdType = _commandType; return ((0 != cmdType) ? cmdType : CommandType.Text); } set { switch (value) { // @perfnote: Enum.IsDefined case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: PropertyChanging(); _commandType = value; break; default: throw ADP.InvalidCommandType(value); } } } [DefaultValue(null)] new public OleDbConnection Connection { get { return _connection; } set { OleDbConnection connection = _connection; if (value != connection) { PropertyChanging(); ResetConnection(); _connection = value; if (null != value) { _transaction = OleDbTransaction.TransactionUpdate(_transaction); } } } } private void ResetConnection() { OleDbConnection connection = _connection; if (null != connection) { PropertyChanging(); CloseInternal(); if (_trackingForClose) { connection.RemoveWeakReference(this); _trackingForClose = false; } } _connection = null; } override protected DbConnection DbConnection { // V1.2.3300 get { return Connection; } set { Connection = (OleDbConnection)value; } } override protected DbParameterCollection DbParameterCollection { // V1.2.3300 get { return Parameters; } } override protected DbTransaction DbTransaction { // V1.2.3300 get { return Transaction; } set { Transaction = (OleDbTransaction)value; } } // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray) // to limit the number of components that clutter the design surface, // when the DataAdapter design wizard generates the insert/update/delete commands it will // set the DesignTimeVisible property to false so that cmds won't appear as individual objects [ DefaultValue(true), DesignOnly(true), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), ] public override bool DesignTimeVisible { // V1.2.3300, XXXCommand V1.0.5000 get { return !_designTimeInvisible; } set { _designTimeInvisible = !value; TypeDescriptor.Refresh(this); } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] new public OleDbParameterCollection Parameters { get { OleDbParameterCollection value = _parameters; if (null == value) { // delay the creation of the OleDbParameterCollection // until user actually uses the Parameters property value = new OleDbParameterCollection(); _parameters = value; } return value; } } private bool HasParameters() { OleDbParameterCollection value = _parameters; return (null != value) && (0 < value.Count); } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] new public OleDbTransaction Transaction { get { // find the last non-zombied local transaction object, but not transactions // that may have been started after the current local transaction OleDbTransaction transaction = _transaction; while ((null != transaction) && (null == transaction.Connection)) { transaction = transaction.Parent; _transaction = transaction; } return transaction; } set { _transaction = value; } } [ DefaultValue(System.Data.UpdateRowSource.Both) ] override public UpdateRowSource UpdatedRowSource { // V1.2.3300, XXXCommand V1.0.5000 get { return _updatedRowSource; } set { switch (value) { // @perfnote: Enum.IsDefined case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: _updatedRowSource = value; break; default: throw ADP.InvalidUpdateRowSource(value); } } } // required interface, safe cast private UnsafeNativeMethods.IAccessor IAccessor() { Debug.Assert(null != _icommandText, "IAccessor: null ICommandText"); return (UnsafeNativeMethods.IAccessor)_icommandText; } // required interface, safe cast internal UnsafeNativeMethods.ICommandProperties ICommandProperties() { Debug.Assert(null != _icommandText, "ICommandProperties: null ICommandText"); return (UnsafeNativeMethods.ICommandProperties)_icommandText; } // optional interface, unsafe cast private UnsafeNativeMethods.ICommandPrepare ICommandPrepare() { Debug.Assert(null != _icommandText, "ICommandPrepare: null ICommandText"); return (_icommandText as UnsafeNativeMethods.ICommandPrepare); } // optional interface, unsafe cast private UnsafeNativeMethods.ICommandWithParameters ICommandWithParameters() { Debug.Assert(null != _icommandText, "ICommandWithParameters: null ICommandText"); UnsafeNativeMethods.ICommandWithParameters value = (_icommandText as UnsafeNativeMethods.ICommandWithParameters); if (null == value) { throw ODB.NoProviderSupportForParameters(_connection.Provider, (Exception)null); } return value; } private void CreateAccessor() { Debug.Assert(System.Data.CommandType.Text == CommandType || System.Data.CommandType.StoredProcedure == CommandType, "CreateAccessor: incorrect CommandType"); Debug.Assert(null == _dbBindings, "CreateAccessor: already has dbBindings"); Debug.Assert(HasParameters(), "CreateAccessor: unexpected, no parameter collection"); // do this first in-case the command doesn't support parameters UnsafeNativeMethods.ICommandWithParameters commandWithParameters = ICommandWithParameters(); OleDbParameterCollection collection = _parameters; OleDbParameter[] parameters = new OleDbParameter[collection.Count]; collection.CopyTo(parameters, 0); // _dbBindings is used as a switch during ExecuteCommand, so don't set it until everything okay Bindings bindings = new Bindings(parameters, collection.ChangeID); for (int i = 0; i < parameters.Length; ++i) { bindings.ForceRebind |= parameters[i].BindParameter(i, bindings); } bindings.AllocateForAccessor(null, 0, 0); ApplyParameterBindings(commandWithParameters, bindings.BindInfo); UnsafeNativeMethods.IAccessor iaccessor = IAccessor(); OleDbHResult hr = bindings.CreateAccessor(iaccessor, ODB.DBACCESSOR_PARAMETERDATA); if (hr < 0) { ProcessResults(hr); } _dbBindings = bindings; } private void ApplyParameterBindings(UnsafeNativeMethods.ICommandWithParameters commandWithParameters, tagDBPARAMBINDINFO[] bindInfo) { IntPtr[] ordinals = new IntPtr[bindInfo.Length]; for (int i = 0; i < ordinals.Length; ++i) { ordinals[i] = (IntPtr)(i + 1); } OleDbHResult hr = commandWithParameters.SetParameterInfo((IntPtr)bindInfo.Length, ordinals, bindInfo); if (hr < 0) { ProcessResults(hr); } } override public void Cancel() { unchecked { _changeID++; } UnsafeNativeMethods.ICommandText icmdtxt = _icommandText; if (null != icmdtxt) { OleDbHResult hr = OleDbHResult.S_OK; lock (icmdtxt) { // lock the object to avoid race conditions between using the object and releasing the object // after we acquire the lock, if the class has moved on don't actually call Cancel if (icmdtxt == _icommandText) { hr = icmdtxt.Cancel(); } } if (OleDbHResult.DB_E_CANTCANCEL != hr) { // if the provider can't cancel the command - don't cancel the DataReader this.canceling = true; } // since cancel is allowed to occur at anytime we can't check the connection status // since if it returns as closed then the connection will close causing the reader to close // and that would introduce the possilbility of one thread reading and one thread closing at the same time ProcessResultsNoReset(hr); } else { this.canceling = true; } } public OleDbCommand Clone() { OleDbCommand clone = new OleDbCommand(this); return clone; } object ICloneable.Clone() { return Clone(); } // Connection.Close & Connection.Dispose(true) notification internal void CloseCommandFromConnection(bool canceling) { this.canceling = canceling; CloseInternal(); _trackingForClose = false; _transaction = null; //GC.SuppressFinalize(this); } internal void CloseInternal() { Debug.Assert(null != _connection, "no connection, CloseInternal"); CloseInternalParameters(); CloseInternalCommand(); } // may be called from either // OleDbDataReader.Close/Dispose // via OleDbCommand.Dispose or OleDbConnection.Close internal void CloseFromDataReader(Bindings bindings) { if (null != bindings) { if (canceling) { bindings.Dispose(); Debug.Assert(_dbBindings == bindings, "bindings with two owners"); } else { bindings.ApplyOutputParameters(); ParameterBindings = bindings; } } _hasDataReader = false; } private void CloseInternalCommand() { unchecked { _changeID++; } this.commandBehavior = CommandBehavior.Default; _isPrepared = false; UnsafeNativeMethods.ICommandText ict = Interlocked.Exchange<UnsafeNativeMethods.ICommandText>(ref _icommandText, null); if (null != ict) { lock (ict) { // lock the object to avoid race conditions between using the object and releasing the object Marshal.ReleaseComObject(ict); } } } private void CloseInternalParameters() { Debug.Assert(null != _connection, "no connection, CloseInternalParameters"); Bindings bindings = _dbBindings; _dbBindings = null; if (null != bindings) { bindings.Dispose(); } } new public OleDbParameter CreateParameter() { return new OleDbParameter(); } override protected DbParameter CreateDbParameter() { return CreateParameter(); } override protected void Dispose(bool disposing) { if (disposing) { // release mananged objects // the DataReader takes ownership of the parameter Bindings // this way they don't get destroyed when user calls OleDbCommand.Dispose // when there is an open DataReader unchecked { _changeID++; } // in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset ResetConnection(); _transaction = null; _parameters = null; CommandText = null; } // release unmanaged objects base.Dispose(disposing); // notify base classes } new public OleDbDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } IDataReader IDbCommand.ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } new public OleDbDataReader ExecuteReader(CommandBehavior behavior) { _executeQuery = true; return ExecuteReaderInternal(behavior, ADP.ExecuteReader); } IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior) { return ExecuteReader(behavior); } override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method) { OleDbDataReader dataReader = null; OleDbException nextResultsFailure = null; int state = ODB.InternalStateClosed; try { ValidateConnectionAndTransaction(method); if (0 != (CommandBehavior.SingleRow & behavior)) { // CommandBehavior.SingleRow implies CommandBehavior.SingleResult behavior |= CommandBehavior.SingleResult; } object executeResult; int resultType; switch (CommandType) { case 0: // uninitialized CommandType.Text case CommandType.Text: case CommandType.StoredProcedure: resultType = ExecuteCommand(behavior, out executeResult); break; case CommandType.TableDirect: resultType = ExecuteTableDirect(behavior, out executeResult); break; default: throw ADP.InvalidCommandType(CommandType); } if (_executeQuery) { try { dataReader = new OleDbDataReader(_connection, this, 0, this.commandBehavior); switch (resultType) { case ODB.ExecutedIMultipleResults: dataReader.InitializeIMultipleResults(executeResult); dataReader.NextResult(); break; case ODB.ExecutedIRowset: dataReader.InitializeIRowset(executeResult, ChapterHandle.DB_NULL_HCHAPTER, _recordsAffected); dataReader.BuildMetaInfo(); dataReader.HasRowsRead(); break; case ODB.ExecutedIRow: dataReader.InitializeIRow(executeResult, _recordsAffected); dataReader.BuildMetaInfo(); break; case ODB.PrepareICommandText: if (!_isPrepared) { PrepareCommandText(2); } OleDbDataReader.GenerateSchemaTable(dataReader, _icommandText, behavior); break; default: Debug.Assert(false, "ExecuteReaderInternal: unknown result type"); break; } executeResult = null; _hasDataReader = true; _connection.AddWeakReference(dataReader, OleDbReferenceCollection.DataReaderTag); // command stays in the executing state until the connection // has a datareader to track for it being closed state = ODB.InternalStateOpen; } finally { if (ODB.InternalStateOpen != state) { this.canceling = true; if (null != dataReader) { ((IDisposable)dataReader).Dispose(); dataReader = null; } } } Debug.Assert(null != dataReader, "ExecuteReader should never return a null DataReader"); } else { // optimized code path for ExecuteNonQuery to not create a OleDbDataReader object try { if (ODB.ExecutedIMultipleResults == resultType) { UnsafeNativeMethods.IMultipleResults multipleResults = (UnsafeNativeMethods.IMultipleResults)executeResult; // may cause a Connection.ResetState which closes connection nextResultsFailure = OleDbDataReader.NextResults(multipleResults, _connection, this, out _recordsAffected); } } finally { try { if (null != executeResult) { Marshal.ReleaseComObject(executeResult); executeResult = null; } CloseFromDataReader(ParameterBindings); } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } if (null != nextResultsFailure) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } else { throw; } } } } } finally { // finally clear executing state try { if ((null == dataReader) && (ODB.InternalStateOpen != state)) { ParameterCleanup(); } } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } if (null != nextResultsFailure) { nextResultsFailure = new OleDbException(nextResultsFailure, e); } else { throw; } } if (null != nextResultsFailure) { throw nextResultsFailure; } } return dataReader; } private int ExecuteCommand(CommandBehavior behavior, out object executeResult) { if (InitializeCommand(behavior, false)) { if (0 != (CommandBehavior.SchemaOnly & this.commandBehavior)) { executeResult = null; return ODB.PrepareICommandText; } return ExecuteCommandText(out executeResult); } return ExecuteTableDirect(behavior, out executeResult); } // dbindings handle can't be freed until the output parameters // have been filled in which occurs after the last rowset is released // dbbindings.FreeDataHandle occurs in Cloe private int ExecuteCommandText(out object executeResult) { int retcode; tagDBPARAMS dbParams = null; RowBinding rowbinding = null; Bindings bindings = ParameterBindings; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { if (null != bindings) { // parameters may be suppressed rowbinding = bindings.RowBinding(); rowbinding.DangerousAddRef(ref mustRelease); // bindings can't be released until after last rowset is released // that is when output parameters are populated // initialize the input parameters to the input databuffer bindings.ApplyInputParameters(); dbParams = new tagDBPARAMS(); dbParams.pData = rowbinding.DangerousGetDataPtr(); dbParams.cParamSets = 1; dbParams.hAccessor = rowbinding.DangerousGetAccessorHandle(); } if ((0 == (CommandBehavior.SingleResult & this.commandBehavior)) && _connection.SupportMultipleResults()) { retcode = ExecuteCommandTextForMultpleResults(dbParams, out executeResult); } else if (0 == (CommandBehavior.SingleRow & this.commandBehavior) || !_executeQuery) { retcode = ExecuteCommandTextForSingleResult(dbParams, out executeResult); } else { retcode = ExecuteCommandTextForSingleRow(dbParams, out executeResult); } } finally { if (mustRelease) { rowbinding.DangerousRelease(); } } return retcode; } private int ExecuteCommandTextForMultpleResults(tagDBPARAMS dbParams, out object executeResult) { Debug.Assert(0 == (CommandBehavior.SingleRow & this.commandBehavior), "SingleRow implies SingleResult"); OleDbHResult hr; hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IMultipleResults, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.E_NOINTERFACE != hr) { ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIMultipleResults; } SafeNativeMethods.Wrapper.ClearErrorInfo(); return ExecuteCommandTextForSingleResult(dbParams, out executeResult); } private int ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, out object executeResult) { OleDbHResult hr; // (Microsoft.Jet.OLEDB.4.0 returns 0 for recordsAffected instead of -1) if (_executeQuery) { hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRowset, dbParams, out _recordsAffected, out executeResult); } else { hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_NULL, dbParams, out _recordsAffected, out executeResult); } ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIRowset; } private int ExecuteCommandTextForSingleRow(tagDBPARAMS dbParams, out object executeResult) { Debug.Assert(_executeQuery, "ExecuteNonQuery should always use ExecuteCommandTextForSingleResult"); if (_connection.SupportIRow(this)) { OleDbHResult hr; hr = _icommandText.Execute(ADP.PtrZero, ref ODB.IID_IRow, dbParams, out _recordsAffected, out executeResult); if (OleDbHResult.DB_E_NOTFOUND == hr) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return ODB.ExecutedIRow; } else if (OleDbHResult.E_NOINTERFACE != hr) { ExecuteCommandTextErrorHandling(hr); return ODB.ExecutedIRow; } } SafeNativeMethods.Wrapper.ClearErrorInfo(); return ExecuteCommandTextForSingleResult(dbParams, out executeResult); } private void ExecuteCommandTextErrorHandling(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { e = ExecuteCommandTextSpecialErrorHandling(hr, e); throw e; } } private Exception ExecuteCommandTextSpecialErrorHandling(OleDbHResult hr, Exception e) { if (((OleDbHResult.DB_E_ERRORSOCCURRED == hr) || (OleDbHResult.DB_E_BADBINDINFO == hr)) && (null != _dbBindings)) { // // this code exist to try for a better user error message by post-morten detection // of invalid parameter types being passed to a provider that doesn't understand // the user specified parameter OleDbType Debug.Assert(null != e, "missing inner exception"); StringBuilder builder = new StringBuilder(); ParameterBindings.ParameterStatus(builder); e = ODB.CommandParameterStatus(builder.ToString(), e); } return e; } override public int ExecuteNonQuery() { _executeQuery = false; ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteNonQuery); return ADP.IntPtrToInt32(_recordsAffected); } override public object ExecuteScalar() { object value = null; _executeQuery = true; using (OleDbDataReader reader = ExecuteReaderInternal(CommandBehavior.Default, ADP.ExecuteScalar)) { if (reader.Read() && (0 < reader.FieldCount)) { value = reader.GetValue(0); } } return value; } private int ExecuteTableDirect(CommandBehavior behavior, out object executeResult) { this.commandBehavior = behavior; executeResult = null; OleDbHResult hr = OleDbHResult.S_OK; StringMemHandle sptr = null; bool mustReleaseStringHandle = false; RuntimeHelpers.PrepareConstrainedRegions(); try { sptr = new StringMemHandle(ExpandCommandText()); sptr.DangerousAddRef(ref mustReleaseStringHandle); if (mustReleaseStringHandle) { tagDBID tableID = new tagDBID(); tableID.uGuid = Guid.Empty; tableID.eKind = ODB.DBKIND_NAME; tableID.ulPropid = sptr.DangerousGetHandle(); using (IOpenRowsetWrapper iopenRowset = _connection.IOpenRowset()) { using (DBPropSet propSet = CommandPropertySets()) { if (null != propSet) { bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { propSet.DangerousAddRef(ref mustRelease); hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, propSet.PropertySetCount, propSet.DangerousGetHandle(), out executeResult); } finally { if (mustRelease) { propSet.DangerousRelease(); } } if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult); } } else { hr = iopenRowset.Value.OpenRowset(ADP.PtrZero, tableID, ADP.PtrZero, ref ODB.IID_IRowset, 0, IntPtr.Zero, out executeResult); } } } } } finally { if (mustReleaseStringHandle) { sptr.DangerousRelease(); } } ProcessResults(hr); _recordsAffected = ADP.RecordsUnaffected; return ODB.ExecutedIRowset; } private string ExpandCommandText() { string cmdtxt = CommandText; if (ADP.IsEmpty(cmdtxt)) { return string.Empty; } CommandType cmdtype = CommandType; switch (cmdtype) { case System.Data.CommandType.Text: // do nothing, already expanded by user return cmdtxt; case System.Data.CommandType.StoredProcedure: // { ? = CALL SPROC (? ?) }, { ? = CALL SPROC }, { CALL SPRC (? ?) }, { CALL SPROC } return ExpandStoredProcedureToText(cmdtxt); case System.Data.CommandType.TableDirect: // @devnote: Provider=Jolt4.0 doesn't like quoted table names, SQOLEDB requires them // Providers should not require table names to be quoted and should guarantee that // unquoted table names correctly open the specified table, even if the table name // contains special characters, as long as the table can be unambiguously identified // without quoting. return cmdtxt; default: throw ADP.InvalidCommandType(cmdtype); } } private string ExpandOdbcMaximumToText(string sproctext, int parameterCount) { StringBuilder builder = new StringBuilder(); if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) { parameterCount--; builder.Append("{ ? = CALL "); } else { builder.Append("{ CALL "); } builder.Append(sproctext); switch (parameterCount) { case 0: builder.Append(" }"); break; case 1: builder.Append("( ? ) }"); break; default: builder.Append("( ?, ?"); for (int i = 2; i < parameterCount; ++i) { builder.Append(", ?"); } builder.Append(" ) }"); break; } return builder.ToString(); } private string ExpandOdbcMinimumToText(string sproctext, int parameterCount) { //if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) { // Debug.Assert("doesn't support ReturnValue parameters"); //} StringBuilder builder = new StringBuilder(); builder.Append("exec "); builder.Append(sproctext); if (0 < parameterCount) { builder.Append(" ?"); for (int i = 1; i < parameterCount; ++i) { builder.Append(", ?"); } } return builder.ToString(); } private string ExpandStoredProcedureToText(string sproctext) { Debug.Assert(null != _connection, "ExpandStoredProcedureToText: null Connection"); int parameterCount = (null != _parameters) ? _parameters.Count : 0; if (0 == (ODB.DBPROPVAL_SQL_ODBC_MINIMUM & _connection.SqlSupport())) { return ExpandOdbcMinimumToText(sproctext, parameterCount); } return ExpandOdbcMaximumToText(sproctext, parameterCount); } private void ParameterCleanup() { Bindings bindings = ParameterBindings; if (null != bindings) { bindings.CleanupBindings(); } } private bool InitializeCommand(CommandBehavior behavior, bool throwifnotsupported) { Debug.Assert(null != _connection, "InitializeCommand: null OleDbConnection"); int changeid = _changeID; if ((0 != (CommandBehavior.KeyInfo & (this.commandBehavior ^ behavior))) || (_lastChangeID != changeid)) { CloseInternalParameters(); // could optimize out CloseInternalCommand(); } this.commandBehavior = behavior; changeid = _changeID; if (!PropertiesOnCommand(false)) { return false; } if ((null != _dbBindings) && _dbBindings.AreParameterBindingsInvalid(_parameters)) { CloseInternalParameters(); } // if we already having bindings - don't create the accessor // if _parameters is null - no parameters exist - don't create the collection // do we actually have parameters since the collection exists if ((null == _dbBindings) && HasParameters()) { // if we setup the parameters before setting cmdtxt then named parameters can happen CreateAccessor(); } if (_lastChangeID != changeid) { OleDbHResult hr; String commandText = ExpandCommandText(); hr = _icommandText.SetCommandText(ref ODB.DBGUID_DEFAULT, commandText); if (hr < 0) { ProcessResults(hr); } } _lastChangeID = changeid; return true; } private void PropertyChanging() { unchecked { _changeID++; } } override public void Prepare() { if (CommandType.TableDirect != CommandType) { ValidateConnectionAndTransaction(ADP.Prepare); _isPrepared = false; if (CommandType.TableDirect != CommandType) { InitializeCommand(0, true); PrepareCommandText(1); } } } private void PrepareCommandText(int expectedExecutionCount) { OleDbParameterCollection parameters = _parameters; if (null != parameters) { foreach (OleDbParameter parameter in parameters) { if (parameter.IsParameterComputed()) { // @devnote: use IsParameterComputed which is called in the normal case // only to call Prepare to throw the specialized error message // reducing the overall number of methods to actually jit parameter.Prepare(this); } } } UnsafeNativeMethods.ICommandPrepare icommandPrepare = ICommandPrepare(); if (null != icommandPrepare) { OleDbHResult hr; hr = icommandPrepare.Prepare(expectedExecutionCount); ProcessResults(hr); } // don't recompute bindings on prepared statements _isPrepared = true; } private void ProcessResults(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _connection, this); if (null != e) { throw e; } } private void ProcessResultsNoReset(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, null, this); if (null != e) { throw e; } } internal object GetPropertyValue(Guid propertySet, int propertyID) { if (null != _icommandText) { OleDbHResult hr; tagDBPROP[] dbprops; UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties(); using (PropertyIDSet propidset = new PropertyIDSet(propertySet, propertyID)) { using (DBPropSet propset = new DBPropSet(icommandProperties, propidset, out hr)) { if (hr < 0) { // OLEDB Data Reader masks provider specific errors by raising "Internal Data Provider error 30." // DBPropSet c-tor will register the exception and it will be raised at GetPropertySet call in case of failure SafeNativeMethods.Wrapper.ClearErrorInfo(); } dbprops = propset.GetPropertySet(0, out propertySet); } } if (OleDbPropertyStatus.Ok == dbprops[0].dwStatus) { return dbprops[0].vValue; } return dbprops[0].dwStatus; } return OleDbPropertyStatus.NotSupported; } private bool PropertiesOnCommand(bool throwNotSupported) { if (null != _icommandText) { return true; } Debug.Assert(!_isPrepared, "null command isPrepared"); OleDbConnection connection = _connection; if (null == connection) { connection.CheckStateOpen(ODB.Properties); } if (!_trackingForClose) { _trackingForClose = true; connection.AddWeakReference(this, OleDbReferenceCollection.CommandTag); } _icommandText = connection.ICommandText(); if (null == _icommandText) { if (throwNotSupported || HasParameters()) { throw ODB.CommandTextNotSupported(connection.Provider, null); } return false; } using (DBPropSet propSet = CommandPropertySets()) { if (null != propSet) { UnsafeNativeMethods.ICommandProperties icommandProperties = ICommandProperties(); OleDbHResult hr = icommandProperties.SetProperties(propSet.PropertySetCount, propSet); if (hr < 0) { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } return true; } private DBPropSet CommandPropertySets() { DBPropSet propSet = null; bool keyInfo = (0 != (CommandBehavior.KeyInfo & this.commandBehavior)); // always set the CommandTimeout value? int count = (_executeQuery ? (keyInfo ? 4 : 2) : 1); if (0 < count) { propSet = new DBPropSet(1); tagDBPROP[] dbprops = new tagDBPROP[count]; dbprops[0] = new tagDBPROP(ODB.DBPROP_COMMANDTIMEOUT, false, CommandTimeout); if (_executeQuery) { // 'Microsoft.Jet.OLEDB.4.0' default is DBPROPVAL_AO_SEQUENTIAL dbprops[1] = new tagDBPROP(ODB.DBPROP_ACCESSORDER, false, ODB.DBPROPVAL_AO_RANDOM); if (keyInfo) { // 'Unique Rows' property required for SQLOLEDB to retrieve things like 'BaseTableName' dbprops[2] = new tagDBPROP(ODB.DBPROP_UNIQUEROWS, false, keyInfo); // otherwise 'Microsoft.Jet.OLEDB.4.0' doesn't support IColumnsRowset dbprops[3] = new tagDBPROP(ODB.DBPROP_IColumnsRowset, false, true); } } propSet.SetPropertySet(0, OleDbPropertySetGuid.Rowset, dbprops); } return propSet; } internal Bindings TakeBindingOwnerShip() { Bindings bindings = _dbBindings; _dbBindings = null; return bindings; } private void ValidateConnection(string method) { if (null == _connection) { throw ADP.ConnectionRequired(method); } _connection.CheckStateOpen(method); // user attempting to execute the command while the first dataReader hasn't returned // use the connection reference collection to see if the dataReader referencing this // command has been garbage collected or not. if (_hasDataReader) { if (_connection.HasLiveReader(this)) { throw ADP.OpenReaderExists(); } _hasDataReader = false; } } private void ValidateConnectionAndTransaction(string method) { ValidateConnection(method); _transaction = _connection.ValidateTransaction(Transaction, method); this.canceling = false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if !NET_NATIVE using ExtensionDataObject = System.Object; #endif #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerReadContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { internal Attributes attributes; private HybridObjectCache _deserializedObjects; private XmlSerializableReader _xmlSerializableReader; private object _getOnlyCollectionValue; private bool _isGetOnlyCollection; private HybridObjectCache DeserializedObjects { get { if (_deserializedObjects == null) _deserializedObjects = new HybridObjectCache(); return _deserializedObjects; } } internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } #if USE_REFEMIT public object GetCollectionMember() #else internal object GetCollectionMember() #endif { return _getOnlyCollectionValue; } #if USE_REFEMIT public void StoreCollectionMemberInfo(object collectionMember) #else internal void StoreCollectionMemberInfo(object collectionMember) #endif { _getOnlyCollectionValue = collectionMember; _isGetOnlyCollection = true; } #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else internal static void ThrowArrayExceededSizeException(int arraySize, Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); } #if USE_REFEMIT public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #else internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #endif { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (_isGetOnlyCollection) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(declaredType)), SR.Format(SR.XmlStartElementExpected, Globals.RefLocalName)))); } else { retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } } else if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, ref DataContract dataContract) { object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract); if (dataContract == null) { if (DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (knownTypesAddedInCurrentScope) { object obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } else { return ReadDataContractValue(dataContract, reader); } } private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } #if USE_REFEMIT public static bool MoveToNextElement(XmlReaderDelegator xmlReader) #else internal static bool MoveToNextElement(XmlReaderDelegator xmlReader) #endif { return (xmlReader.MoveToContent() != XmlNodeType.EndElement); } #if USE_REFEMIT public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) return i; } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #else internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #endif { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) requiredIndex--; for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) stringBuilder.Append(" | "); stringBuilder.Append(memberNames[i].Value); } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } #if NET_NATIVE public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int missingMembersCount = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(memberNames[i]); missingMembersCount++; } } if (missingMembersCount == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } } public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); } [SecuritySafeCritical] private static bool IsBitSet(byte[] bytes, int bitIndex) { throw new NotImplementedException(); //return BitFlagsGenerator.IsBitSet(bytes, bitIndex); } #endif protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (IgnoreExtensionDataObject || extensionData == null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { } #if USE_REFEMIT public void SkipUnknownElement(XmlReaderDelegator xmlReader) #else internal void SkipUnknownElement(XmlReaderDelegator xmlReader) #endif { ReadAttributes(xmlReader); xmlReader.Skip(); } #if USE_REFEMIT public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #else internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #endif { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } else if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return Globals.NullObjectId; } return Globals.NewObjectId; } #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) #endif { if (attributes == null) attributes = new Attributes(); attributes.Read(xmlReader); } #if USE_REFEMIT public void ResetAttributes() #else internal void ResetAttributes() #endif { if (attributes != null) attributes.Reset(); } #if USE_REFEMIT public string GetObjectId() #else internal string GetObjectId() #endif { return attributes.Id; } #if USE_REFEMIT public virtual int GetArraySize() #else internal virtual int GetArraySize() #endif { return -1; } #if USE_REFEMIT public void AddNewObject(object obj) #else internal void AddNewObject(object obj) #endif { AddNewObjectWithId(attributes.Id, obj); } #if USE_REFEMIT public void AddNewObjectWithId(string id, object obj) #else internal void AddNewObjectWithId(string id, object obj) #endif { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; if (id != Globals.NewObjectId) { // In certain cases (IObjectReference, SerializationSurrogate or DataContractSurrogate), // an object can be replaced with a different object once it is deserialized. If the // object happens to be referenced from within itself, that reference needs to be updated // with the new instance. BinaryFormatter supports this by fixing up such references later. // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } } #if USE_REFEMIT public object GetExistingObject(string id, Type type, string name, string ns) #else internal object GetExistingObject(string id, Type type, string name, string ns) #endif { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } #if USE_REFEMIT public static void Read(XmlReaderDelegator xmlReader) #else internal static void Read(XmlReaderDelegator xmlReader) #endif { if (!xmlReader.Read()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile))); } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; if (colon >= 0) prefix = qname.Substring(0, colon); name = qname.Substring(colon + 1); ns = xmlReader.LookupNamespace(prefix); } #if USE_REFEMIT public static T[] EnsureArraySize<T>(T[] array, int index) #else internal static T[] EnsureArraySize<T>(T[] array, int index) #endif { if (array.Length <= index) { if (index == Int32.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException( SR.Format(SR.MaxArrayLengthExceeded, Int32.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } int newSize = (index < Int32.MaxValue / 2) ? index * 2 : Int32.MaxValue; T[] newArray = new T[newSize]; Array.Copy(array, 0, newArray, 0, array.Length); array = newArray; } return array; } #if USE_REFEMIT public static T[] TrimArraySize<T>(T[] array, int size) #else internal static T[] TrimArraySize<T>(T[] array, int size) #endif { if (size != array.Length) { T[] newArray = new T[size]; Array.Copy(array, 0, newArray, 0, size); array = newArray; } return array; } #if USE_REFEMIT public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #else internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #endif { if (xmlReader.NodeType == XmlNodeType.EndElement) return; while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, arraySize, itemName.Value, itemNamespace.Value))); SkipUnknownElement(xmlReader); } if (xmlReader.NodeType != XmlNodeType.EndElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (_xmlSerializableReader == null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } protected virtual DataContract ResolveDataContractFromTypeName() { return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/); } #if USE_REFEMIT public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #else internal static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #endif { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingState, expectedState), xmlReader); } //Silverlight only helper function to create SerializationException #if USE_REFEMIT public static Exception CreateSerializationException(string message) #else internal static Exception CreateSerializationException(string message) #endif { return XmlObjectSerializer.CreateSerializationException(message); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return (attributes.ArraySZSize != -1); } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } }
using System; using Eto.Forms; using System.Linq; using System.Collections.Generic; using Eto.GtkSharp.Forms.Cells; using Eto.GtkSharp.Forms.Menu; namespace Eto.GtkSharp.Forms.Controls { public abstract class GridHandler<TWidget, TCallback> : GtkControl<Gtk.ScrolledWindow, TWidget, TCallback>, Grid.IHandler, ICellDataSource, IGridHandler where TWidget : Grid where TCallback: Grid.ICallback { ColumnCollection columns; ContextMenu contextMenu; readonly Dictionary<int, int> columnMap = new Dictionary<int, int>(); protected bool SkipSelectedChange { get; set; } protected Gtk.TreeView Tree { get; private set; } protected Dictionary<int, int> ColumnMap { get { return columnMap; } } protected GridHandler() { Control = new Gtk.ScrolledWindow { ShadowType = Gtk.ShadowType.In }; } protected abstract ITreeModelImplementor CreateModelImplementor(); protected void UpdateModel() { SkipSelectedChange = true; var selected = SelectedRows; Tree.Model = new Gtk.TreeModelAdapter(CreateModelImplementor()); SetSelectedRows(selected); SkipSelectedChange = false; } protected override void Initialize() { base.Initialize(); Tree = new Gtk.TreeView(); UpdateModel(); Tree.HeadersVisible = true; Control.Add(Tree); Tree.Events |= Gdk.EventMask.ButtonPressMask; Tree.ButtonPressEvent += Connector.HandleTreeButtonPressEvent; columns = new ColumnCollection { Handler = this }; columns.Register(Widget.Columns); } protected new GridConnector Connector { get { return (GridConnector)base.Connector; } } protected override WeakConnector CreateConnector() { return new GridConnector(); } protected class GridConnector : GtkControlConnector { public new GridHandler<TWidget, TCallback> Handler { get { return (GridHandler<TWidget, TCallback>)base.Handler; } } [GLib.ConnectBefore] public void HandleTreeButtonPressEvent(object o, Gtk.ButtonPressEventArgs args) { var handler = Handler; if (handler.contextMenu != null && args.Event.Button == 3 && args.Event.Type == Gdk.EventType.ButtonPress) { var menu = ((ContextMenuHandler)handler.contextMenu.Handler).Control; menu.Popup(); menu.ShowAll(); } } int[] selectedRows; static bool ArraysEqual<T>(T[] a1, T[] a2) { if (ReferenceEquals(a1, a2)) return true; if (a1 == null || a2 == null) return false; if (a1.Length != a2.Length) return false; EqualityComparer<T> comparer = EqualityComparer<T>.Default; for (int i = 0; i < a1.Length; i++) { if (!comparer.Equals(a1[i], a2[i])) return false; } return true; } public void HandleGridSelectionChanged(object sender, EventArgs e) { if (!Handler.SkipSelectedChange) { var selected = Handler.SelectedRows.ToArray(); if (!ArraysEqual(selectedRows, selected)) { Handler.Callback.OnSelectionChanged(Handler.Widget, EventArgs.Empty); selectedRows = selected; } } } } public override void AttachEvent(string id) { switch (id) { case Grid.ColumnHeaderClickEvent: case Grid.CellEditingEvent: case Grid.CellEditedEvent: case Grid.CellFormattingEvent: SetupColumnEvents(); break; case Grid.CellClickEvent: Tree.ButtonPressEvent += OnTreeButtonPress; break; case Grid.CellDoubleClickEvent: Tree.RowActivated += (sender, e) => { var rowIndex = GetRowIndexOfPath(e.Path); var columnIndex = GetColumnOfItem(e.Column); var item = GetItem(e.Path); var column = columnIndex == -1 ? null : Widget.Columns[columnIndex]; Callback.OnCellDoubleClick(Widget, new GridViewCellEventArgs(column, rowIndex, columnIndex, item)); }; break; case Grid.SelectionChangedEvent: Tree.Selection.Changed += Connector.HandleGridSelectionChanged; break; default: base.AttachEvent(id); break; } } [GLib.ConnectBefore] protected virtual void OnTreeButtonPress (object sender, Gtk.ButtonPressEventArgs e) { // If clicked mouse button is not the primary button, return. if (e.Event.Button != 1 || e.Event.Type == Gdk.EventType.TwoButtonPress || e.Event.Type == Gdk.EventType.ThreeButtonPress) return; Gtk.TreePath path; Gtk.TreeViewColumn clickedColumn; // Get path and column from mouse position Tree.GetPathAtPos((int)e.Event.X, (int)e.Event.Y, out path, out clickedColumn); if (path == null || clickedColumn == null) return; var rowIndex = GetRowIndexOfPath(path); var columnIndex = GetColumnOfItem(clickedColumn); var item = GetItem(path); var column = columnIndex == -1 || columnIndex >= Widget.Columns.Count ? null : Widget.Columns[columnIndex]; Callback.OnCellClick(Widget, new GridViewCellEventArgs(column, rowIndex, columnIndex, item)); } public override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); Tree.AppendColumn(new Gtk.TreeViewColumn()); UpdateColumns(); } void SetupColumnEvents() { if (!Widget.Loaded) return; foreach (var col in Widget.Columns.Select(r => r.Handler).OfType<IGridColumnHandler>()) { col.SetupEvents(); } } protected virtual void UpdateColumns() { if (!Widget.Loaded) return; columnMap.Clear(); int columnIndex = 0; int dataIndex = 0; foreach (var col in Widget.Columns.Select(r => r.Handler).OfType<IGridColumnHandler>()) { col.BindCell(this, this, columnIndex++, ref dataIndex); col.SetupEvents(); } } class ColumnCollection : EnumerableChangedHandler<GridColumn, GridColumnCollection> { public GridHandler<TWidget, TCallback> Handler { get; set; } public override void AddItem(GridColumn item) { var colhandler = (GridColumnHandler)item.Handler; Handler.Tree.AppendColumn(colhandler.Control); Handler.UpdateColumns(); } public override void InsertItem(int index, GridColumn item) { var colhandler = (GridColumnHandler)item.Handler; if (Handler.Tree.Columns.Length > 0) Handler.Tree.InsertColumn(colhandler.Control, index); else Handler.Tree.AppendColumn(colhandler.Control); Handler.UpdateColumns(); } public override void RemoveItem(int index) { var colhandler = (GridColumnHandler)Handler.Widget.Columns[index].Handler; Handler.Tree.RemoveColumn(colhandler.Control); Handler.UpdateColumns(); } public override void RemoveAllItems() { foreach (var col in Handler.Tree.Columns) { Handler.Tree.RemoveColumn(col); } Handler.UpdateColumns(); } } public bool ShowHeader { get { return Tree.HeadersVisible; } set { Tree.HeadersVisible = value; } } public bool AllowColumnReordering { get { return Tree.Reorderable; } set { Tree.Reorderable = value; } } public int NumberOfColumns { get { return Widget.Columns.Count; } } public abstract object GetItem(Gtk.TreePath path); public int GetColumnOfItem(Gtk.TreeViewColumn item) { return Widget.Columns.Select(r => r.Handler as GridColumnHandler).Select(r => r.Control).ToList().IndexOf(item); } public virtual int GetRowIndexOfPath(Gtk.TreePath path) { int rowIndex = 0; if (path.Indices.Length > 0) { for (int i = 0; i < path.Depth; i++) rowIndex += path.Indices[i] + 1; rowIndex--; } else rowIndex = -1; return rowIndex; } public abstract Gtk.TreeIter GetIterAtRow(int row); public abstract Gtk.TreePath GetPathAtRow(int row); public void SetColumnMap(int dataIndex, int column) { columnMap[dataIndex] = column; } public ContextMenu ContextMenu { get { return contextMenu; } set { contextMenu = value; } } public void EndCellEditing(Gtk.TreePath path, int column) { var row = path.Indices.Length > 0 ? path.Indices[0] : -1; var item = GetItem(path); Callback.OnCellEdited(Widget, new GridViewCellEventArgs(Widget.Columns[column], row, column, item)); } public void BeginCellEditing(Gtk.TreePath path, int column) { var row = path.Indices.Length > 0 ? path.Indices[0] : -1; var item = GetItem(path); Callback.OnCellEditing(Widget, new GridViewCellEventArgs(Widget.Columns[column], row, column, item)); } public void ColumnClicked(GridColumnHandler column) { Callback.OnColumnHeaderClick(Widget, new GridColumnEventArgs(column.Widget)); } public bool AllowMultipleSelection { get { return Tree.Selection.Mode == Gtk.SelectionMode.Multiple; } set { Tree.Selection.Mode = value ? Gtk.SelectionMode.Multiple : Gtk.SelectionMode.Browse; } } public virtual IEnumerable<int> SelectedRows { get { return Tree.Selection.GetSelectedRows().Select(r => r.Indices[0]); } set { SkipSelectedChange = true; SetSelectedRows(value); SkipSelectedChange = false; Callback.OnSelectionChanged(Widget, EventArgs.Empty); } } protected abstract void SetSelectedRows(IEnumerable<int> value); public int RowHeight { get; set; } public void SelectAll() { Tree.Selection.SelectAll(); } public void SelectRow(int row) { Tree.Selection.SelectIter(GetIterAtRow(row)); } public void UnselectRow(int row) { Tree.Selection.UnselectIter(GetIterAtRow(row)); } public void UnselectAll() { Tree.Selection.UnselectAll(); } public void BeginEdit(int row, int column) { var nameColumn = Tree.Columns[column]; #if GTK2 var cellRenderer = nameColumn.CellRenderers[0]; #else var cellRenderer = nameColumn.Cells[0]; #endif var path = Tree.Model.GetPath(GetIterAtRow(row)); Tree.Model.IterNChildren(); Tree.SetCursorOnCell(path, nameColumn, cellRenderer, true); } public void OnCellFormatting(GridCellFormatEventArgs args) { Callback.OnCellFormatting(Widget, args); } public void ScrollToRow(int row) { var path = this.GetPathAtRow(row); var column = Tree.Columns.First(); Tree.ScrollToCell(path, column, false, 0, 0); } public GridLines GridLines { get { switch (Tree.EnableGridLines) { case Gtk.TreeViewGridLines.None: return GridLines.None; case Gtk.TreeViewGridLines.Horizontal: return GridLines.Horizontal; case Gtk.TreeViewGridLines.Vertical: return GridLines.Vertical; case Gtk.TreeViewGridLines.Both: return GridLines.Both; default: throw new NotSupportedException(); } } set { switch (value) { case GridLines.None: Tree.EnableGridLines = Gtk.TreeViewGridLines.None; break; case GridLines.Horizontal: Tree.EnableGridLines = Gtk.TreeViewGridLines.Horizontal; break; case GridLines.Vertical: Tree.EnableGridLines = Gtk.TreeViewGridLines.Vertical; break; case GridLines.Both: Tree.EnableGridLines = Gtk.TreeViewGridLines.Both; break; default: throw new NotSupportedException(); } } } } }
using AnlabMvc.Controllers; using AnlabMvc.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Moq; using Shouldly; using System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Test.TestsController { [Trait("Category", "ControllerTests")] public class FinancialServiceControllerTests { [Fact] public async Task TestGetAccountInfoCallsService() { // Arrange var mockService = new Mock<IFinancialService>(); mockService.Setup(a => a.GetAccountName(It.IsAny<string>())).ReturnsAsync("Fake"); var controller = new FinancialServiceController(mockService.Object); // Act var controllerResult = await controller.GetAccountInfo("test"); // Assert controllerResult.ShouldBe("Fake"); mockService.Verify(a => a.GetAccountName("test"), Times.Once); } } [Trait("Category", "Controller Reflection")] public class FinancialServiceControllerReflectionTests { private readonly ITestOutputHelper output; public FinancialServiceControllerReflectionTests(ITestOutputHelper output) { this.output = output; } protected readonly Type ControllerClass = typeof(FinancialServiceController); #region Controller Class Tests [Fact] public void TestControllerInheritsFromApplicationController() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act controllerClass.BaseType.ShouldNotBe(null); var result = controllerClass.BaseType.Name; #endregion Act #region Assert result.ShouldBe("ApplicationController"); #endregion Assert } [Fact] public void TestControllerExpectedNumberOfAttributes() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in result) { output.WriteLine(o.ToString()); //Output shows } result.Count().ShouldBe(3); #endregion Assert } /// <summary> /// #1 /// </summary> [Fact] public void TestControllerHasControllerAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<ControllerAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "ControllerAttribute not found."); #endregion Assert } /// <summary> /// #2 /// </summary> [Fact] public void TestControllerHasAuthorizeAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<AuthorizeAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "AuthorizeAttribute not found."); result.ElementAt(0).Roles.ShouldBeNull(); #endregion Assert } /// <summary> /// #3 /// </summary> [Fact] public void TestControllerHasAutoValidateAntiforgeryTokenAttribute() { #region Arrange var controllerClass = ControllerClass.GetTypeInfo(); #endregion Arrange #region Act var result = controllerClass.GetCustomAttributes(true).OfType<AutoValidateAntiforgeryTokenAttribute>(); #endregion Act #region Assert result.Count().ShouldBeGreaterThan(0, "AutoValidateAntiforgeryTokenAttribute not found."); #endregion Assert } #endregion Controller Class Tests #region Controller Method Tests [Fact]//(Skip = "Tests are still being written. When done, remove this line.")] public void TestControllerContainsExpectedNumberOfPublicMethods() { #region Arrange var controllerClass = ControllerClass; #endregion Arrange #region Act var result = controllerClass.GetMethods().Where(a => a.DeclaringType == controllerClass); #endregion Act #region Assert result.Count().ShouldBe(1); #endregion Assert } [Fact] public void TestControllerMethodGetAccountInfoContainsExpectedAttributes1() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("GetAccountInfo"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<HttpGetAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } #if DEBUG allAttributes.Count().ShouldBe(3, "No Attributes"); #else allAttributes.Count().ShouldBe(2, "No Attributes"); #endif expectedAttribute.Count().ShouldBe(1, "HttpGetAttribute not found"); expectedAttribute.ElementAt(0).Template.ShouldBe("financial/info"); #endregion Assert } [Fact] public void TestControllerMethodGetAccountInfoContainsExpectedAttributes2() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("GetAccountInfo"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<AsyncStateMachineAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } #if DEBUG allAttributes.Count().ShouldBe(3, "No Attributes"); #else allAttributes.Count().ShouldBe(2, "No Attributes"); #endif expectedAttribute.Count().ShouldBe(1, "AsyncStateMachineAttribute not found"); #endregion Assert } #if DEBUG [Fact] public void TestControllerMethodGetAccountInfoContainsExpectedAttributes3() { #region Arrange var controllerClass = ControllerClass; var controllerMethod = controllerClass.GetMethod("GetAccountInfo"); #endregion Arrange #region Act var expectedAttribute = controllerMethod.GetCustomAttributes(true).OfType<DebuggerStepThroughAttribute>(); var allAttributes = controllerMethod.GetCustomAttributes(true); #endregion Act #region Assert foreach (var o in allAttributes) { output.WriteLine(o.ToString()); //Output shows if the test fails } allAttributes.Count().ShouldBe(3, "No Attributes"); expectedAttribute.Count().ShouldBe(1, "DebuggerStepThroughAttribute not found"); #endregion Assert } #endif #endregion Controller Method Tests } }
using System; using System.Collections.Generic; using UnityEngine; using MessageStream2; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { //Damn you americans - You're making me spell 'colour' wrong! public class PlayerColorWorker { //As this worker is entirely event based, we need to register and unregister hooks in the workerEnabled accessor. private bool privateWorkerEnabled; //Services private Settings dmpSettings; private LockSystem lockSystem; private PlayerStatusWindow playerStatusWindow; private NetworkWorker networkWorker; public PlayerColorWorker(Settings dmpSettings, LockSystem lockSystem, NetworkWorker networkWorker) { this.dmpSettings = dmpSettings; this.lockSystem = lockSystem; this.networkWorker = networkWorker; } public void SetDependencies(PlayerStatusWindow playerStatusWindow) { this.playerStatusWindow = playerStatusWindow; } public bool workerEnabled { get { return privateWorkerEnabled; } set { if (!privateWorkerEnabled && value) { GameEvents.onVesselCreate.Add(this.SetVesselColor); lockSystem.RegisterAcquireHook(this.OnLockAcquire); lockSystem.RegisterReleaseHook(this.OnLockRelease); } if (privateWorkerEnabled && !value) { GameEvents.onVesselCreate.Remove(this.SetVesselColor); lockSystem.UnregisterAcquireHook(this.OnLockAcquire); lockSystem.UnregisterReleaseHook(this.OnLockRelease); } privateWorkerEnabled = value; } } private Dictionary<string, Color> playerColors = new Dictionary<string, Color>(); private object playerColorLock = new object(); //Can't declare const - But no touchy. public readonly Color DEFAULT_COLOR = Color.grey; private void SetVesselColor(Vessel colorVessel) { if (workerEnabled) { if (lockSystem.LockExists("control-" + colorVessel.id.ToString()) && !lockSystem.LockIsOurs("control-" + colorVessel.id.ToString())) { string vesselOwner = lockSystem.LockOwner("control-" + colorVessel.id.ToString()); DarkLog.Debug("Vessel " + colorVessel.id.ToString() + " owner is " + vesselOwner); colorVessel.orbitDriver.orbitColor = GetPlayerColor(vesselOwner); } else { colorVessel.orbitDriver.orbitColor = DEFAULT_COLOR; } } } private void OnLockAcquire(string playerName, string lockName, bool result) { if (workerEnabled) { UpdateVesselColorsFromLockName(lockName); } } private void OnLockRelease(string playerName, string lockName) { if (workerEnabled) { UpdateVesselColorsFromLockName(lockName); } } private void UpdateVesselColorsFromLockName(string lockName) { if (lockName.StartsWith("control-")) { string vesselID = lockName.Substring(8); foreach (Vessel findVessel in FlightGlobals.fetch.vessels) { if (findVessel.id.ToString() == vesselID) { SetVesselColor(findVessel); } } } } private void UpdateAllVesselColors() { foreach (Vessel updateVessel in FlightGlobals.fetch.vessels) { SetVesselColor(updateVessel); } } public Color GetPlayerColor(string playerName) { lock (playerColorLock) { if (playerName == dmpSettings.playerName) { return dmpSettings.playerColor; } if (playerColors.ContainsKey(playerName)) { return playerColors[playerName]; } return DEFAULT_COLOR; } } public void HandlePlayerColorMessage(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { PlayerColorMessageType messageType = (PlayerColorMessageType)mr.Read<int>(); switch (messageType) { case PlayerColorMessageType.LIST: { int numOfEntries = mr.Read<int>(); lock (playerColorLock) { playerColors = new Dictionary<string, Color>(); for (int i = 0; i < numOfEntries; i++) { string playerName = mr.Read<string>(); Color playerColor = ConvertFloatArrayToColor(mr.Read<float[]>()); playerColors.Add(playerName, playerColor); playerStatusWindow.colorEventHandled = false; } } } break; case PlayerColorMessageType.SET: { lock (playerColorLock) { string playerName = mr.Read<string>(); Color playerColor = ConvertFloatArrayToColor(mr.Read<float[]>()); DarkLog.Debug("Color message, name: " + playerName + " , color: " + playerColor.ToString()); playerColors[playerName] = playerColor; UpdateAllVesselColors(); playerStatusWindow.colorEventHandled = false; } } break; } } } public void SendPlayerColorToServer() { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)PlayerColorMessageType.SET); mw.Write<string>(dmpSettings.playerName); mw.Write<float[]>(ConvertColorToFloatArray(dmpSettings.playerColor)); networkWorker.SendPlayerColorMessage(mw.GetMessageBytes()); } } //Helpers public static float[] ConvertColorToFloatArray(Color convertColour) { float[] returnArray = new float[3]; returnArray[0] = convertColour.r; returnArray[1] = convertColour.g; returnArray[2] = convertColour.b; return returnArray; } public static Color ConvertFloatArrayToColor(float[] convertArray) { return new Color(convertArray[0], convertArray[1], convertArray[2]); } //Adapted from KMP public static Color GenerateRandomColor() { System.Random rand = new System.Random(); int seed = rand.Next(); Color returnColor = Color.white; switch (seed % 17) { case 0: return Color.red; case 1: return new Color(1, 0, 0.5f, 1); //Rosy pink case 2: return new Color(0.6f, 0, 0.5f, 1); //OU Crimson case 3: return new Color(1, 0.5f, 0, 1); //Orange case 4: return Color.yellow; case 5: return new Color(1, 0.84f, 0, 1); //Gold case 6: return Color.green; case 7: return new Color(0, 0.651f, 0.576f, 1); //Persian Green case 8: return new Color(0, 0.651f, 0.576f, 1); //Persian Green case 9: return new Color(0, 0.659f, 0.420f, 1); //Jade case 10: return new Color(0.043f, 0.855f, 0.318f, 1); //Malachite case 11: return Color.cyan; case 12: return new Color(0.537f, 0.812f, 0.883f, 1); //Baby blue; case 13: return new Color(0, 0.529f, 0.741f, 1); //NCS blue case 14: return new Color(0.255f, 0.412f, 0.882f, 1); //Royal Blue case 15: return new Color(0.5f, 0, 1, 1); //Violet default: return Color.magenta; } } public void Stop() { workerEnabled = false; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace KaoriStudio.Core.Helpers { /// <summary> /// Compatibility helper /// </summary> public static class CompatibilityHelper { /// <summary> /// Array compatibility helper /// </summary> public static class Array { /// <summary> /// An empty array /// </summary> /// <typeparam name="T">The array type</typeparam> /// <returns>An empty array</returns> public static T[] Empty<T>() { #if NETFX_46 return System.Array.Empty<T>(); #else return new T[0]; #endif } } /// <summary> /// Comparer compatibility helper /// </summary> /// <typeparam name="T">The comparer type</typeparam> public static class Comparer<T> { /// <summary> /// Creates a comparer by using the specified comparison. /// </summary> /// <param name="comparison">The comparison to use.</param> /// <returns>The new comparer.</returns> public static IComparer<T> Create(Comparison<T> comparison) { #if NETFX_45 return Comparer<T>.Create(comparison); #else return new ComparerCreator(comparison); #endif } #if !NETFX_45 struct ComparerCreator : IComparer<T> { Comparison<T> Comparison; public ComparerCreator(Comparison<T> Comparison) { this.Comparison = Comparison; } public int Compare(T x, T y) { return this.Comparison.Invoke(x, y); } } #endif } /// <summary> /// String compatibility helper. /// </summary> public static class String { /// <inheritdoc cref="string.Join(string, string[])" /> public static string Join(string separator, IEnumerable<string> values) { #if !NETFX_40 var sb = new StringBuilder(); var first = true; foreach (var s in values) { if (first) first = false; else sb.Append(separator); sb.Append(s); } return sb.ToString(); #else return string.Join(separator, values); #endif } /// <inheritdoc cref="string.Join(string, string[])" /> public static string Join(string separator, string[] values) { return string.Join(separator, values); } } #if !NETFX_45 /// <summary> /// Retrieves a custom attribute of a specified type that is applied to a specified member. /// </summary> /// <typeparam name="T">The attribute type</typeparam> /// <param name="element">The member to inspect.</param> /// <returns>A custom attribute that matches <typeparamref name="T"/>, or <c>null</c> if no such attribute is found.</returns> public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute { if (element == null) throw new ArgumentNullException("element"); switch (element.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: case MemberTypes.Property: case MemberTypes.Event: case MemberTypes.TypeInfo: case MemberTypes.NestedType: case MemberTypes.Field: break; default: throw new NotSupportedException("element is not a constructor, method, property, event, type, or field. "); } var cattr = element.GetCustomAttributes(typeof(T), false); if (cattr == null || cattr.Length == 0) return null; if (cattr.Length > 1) throw new AmbiguousMatchException("More than one of the requested attributes was found."); return (T)cattr[0]; } /// <summary> /// Retrieves a custom attribute of a specified type that is applied to a specified parameter. /// </summary> /// <typeparam name="T">The attribute type</typeparam> /// <param name="element">The parameter to inspect.</param> /// <returns>A custom attribute that matches <typeparamref name="T"/>, or <c>null</c> if no such attribute is found.</returns> public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute { if (element == null) throw new ArgumentNullException("element"); var cattr = element.GetCustomAttributes(typeof(T), false); if (cattr == null || cattr.Length == 0) return null; if (cattr.Length > 1) throw new AmbiguousMatchException("More than one of the requested attributes was found."); return (T)cattr[0]; } /// <summary> /// Gets a value that indicates whether this parameter has a default value. /// </summary> /// <param name="element">The parameter to inspect.</param> /// <returns><c>true</c> if this parameter has a default value; otherwise, <c>false</c>.</returns> public static bool HasDefaultValue(this ParameterInfo element) { return element.IsOptional; } /// <summary> /// Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member. /// </summary> /// <typeparam name="T">The attribute type</typeparam> /// <param name="element">An object derived from the MemberInfo class that describes a constructor, event, field, method, or property member of a class. </param> /// <param name="inherit">If true, specifies to also search the ancestors of element for custom attributes. </param> /// <returns>An Attribute array that contains the custom attributes applied to element, or an empty array if no such custom attributes exist.</returns> public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo element, bool inherit) where T : Attribute { if (element == null) throw new ArgumentNullException("element"); return element.GetCustomAttributes(typeof(T), inherit).Cast<T>(); } #else /// <summary> /// Gets a value that indicates whether this parameter has a default value. /// </summary> /// <param name="element">The parameter to inspect.</param> /// <returns><c>true</c> if this parameter has a default value; otherwise, <c>false</c>.</returns> public static bool HasDefaultValue(this ParameterInfo element) { return element.HasDefaultValue; } #endif #if !NETFX_40 /// <summary> /// Determines whether one or more bit fields are set in the current instance. /// </summary> /// <param name="value">The value being checked</param> /// <param name="flag">An enumeration value.</param> /// <returns><c>true</c> if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, <c>false</c>.</returns> public static bool HasFlag(this Enum value, Enum flag) { var a = Convert.ToInt32(value); var b = Convert.ToInt32(flag); return (a & b) == b; } /// <summary> /// Removes all characters from the current <see cref="StringBuilder"/> instance. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to clear</param> /// <returns>An object whose <see cref="StringBuilder.Length"/> is 0 (zero).</returns> public static StringBuilder Clear(this StringBuilder sb) { if (sb.Length != 0) sb.Remove(0, sb.Length); return sb; } /// <summary> /// Returns an enumerable collection of directory information in the current directory. /// </summary> /// <param name="di">The directory being enumerated</param> /// <returns>An enumerable collection of directories in the current directory.</returns> public static IEnumerable<DirectoryInfo> EnumerateDirectories(this DirectoryInfo di) { return di.GetDirectories(); } /// <summary> /// Returns an enumerable collection of file information in the current directory. /// </summary> /// <param name="di">The directory being enumerated</param> /// <returns>An enumerable collection of the files in the current directory.</returns> public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo di) { return di.GetFiles(); } /// <summary> /// Returns an enumerable collection of file system information in the current directory. /// </summary> /// <param name="di">The directory being enumerated</param> /// <returns>An enumerable collection of file system information in the current directory.</returns> public static IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(this DirectoryInfo di) { return di.GetFileSystemInfos(); } #endif #if !NETFX_40 /// <summary> /// Delegate for Func with ByRef /// </summary> /// <typeparam name="T1">The first argument type</typeparam> /// <typeparam name="TResult">The result type</typeparam> /// <param name="arg1">The first argument</param> /// <returns>The result</returns> public delegate TResult ByRefFunc1<T1, TResult>(ref T1 arg1); /// <summary> /// Delegate for Func with ByRef /// </summary> /// <typeparam name="T1">The first argument type</typeparam> /// <typeparam name="T2">The second argument type</typeparam> /// <typeparam name="TResult">The result type</typeparam> /// <param name="arg1">The first argument</param> /// <param name="arg2">The second argument</param> /// <returns>The result</returns> public delegate TResult ByRefFunc01<T1, T2, TResult>(T1 arg1, ref T2 arg2); /// <inheritdoc cref="ByRefFunc01{T1, T2, TResult}"/> public delegate TResult ByRefFunc10<T1, T2, TResult>(ref T1 arg1, T2 arg2); /// <inheritdoc cref="ByRefFunc01{T1, T2, TResult}"/> public delegate TResult ByRefFunc11<T1, T2, TResult>(ref T1 arg1, ref T2 arg2); /// <summary> /// Delegate for Action with ByRef /// </summary> /// <typeparam name="T1">The first argument type</typeparam> /// <typeparam name="T2">The second argument type</typeparam> /// <param name="arg1">The first argument</param> /// <param name="arg2">The second argument</param> public delegate void ByRefAction1<T1>(ref T1 arg1); /// <summary> /// Delegate for Action with ByRef /// </summary> /// <typeparam name="T1">The first argument type</typeparam> /// <typeparam name="T2">The second argument type</typeparam> /// <param name="arg1">The first argument</param> /// <param name="arg2">The second argument</param> public delegate void ByRefAction01<T1, T2>(T1 arg1, ref T2 arg2); /// <inheritdoc cref="ByRefAction01{T1, T2}"/> public delegate void ByRefAction10<T1, T2>(ref T1 arg1, T2 arg2); /// <inheritdoc cref="ByRefAction01{T1, T2}"/> public delegate void ByRefAction11<T1, T2>(ref T1 arg1, ref T2 arg2); static readonly Type[][] typeFunc = { new Type[] { typeof(ByRefFunc1<,>), }, new Type[] { typeof(ByRefFunc01<,,>), typeof(ByRefFunc10<,,>), typeof(ByRefFunc11<,,>), }, }; static readonly Type[][] typeAction = { new Type[] { typeof(ByRefAction1<>), }, new Type[] { typeof(ByRefAction01<,>), typeof(ByRefAction10<,>), typeof(ByRefAction11<,>), }, }; #endif /// <summary> /// Expressions compatibiltiy helper /// </summary> public static class Expression { /// <summary> /// Creates a delegate from a list of types /// </summary> /// <param name="typeArgs">The types</param> /// <returns>The delegate type</returns> public static Type GetDelegateType(params Type[] typeArgs) { #if NETFX_40 return System.Linq.Expressions.Expression.GetDelegateType(typeArgs); #else var isVoid = (typeArgs[typeArgs.Length - 1] == typeof(void)); if (typeArgs.Where(x => x.IsByRef).HasFirst()) { if (isVoid) { var newArgs = new Type[typeArgs.Length - 1]; var ind0 = typeArgs.Length - 2; int ind1 = 0; for (int i = 0; i <= ind0; i++) { ind1 <<= 1; var type = typeArgs[i]; if (type.IsByRef) { ind1++; newArgs[i] = type.GetElementType(); } else { newArgs[i] = type; } } ind1--; return typeAction[ind0][ind1].MakeGenericType(newArgs); } else { var newArgs = new Type[typeArgs.Length]; newArgs[typeArgs.Length - 1] = typeArgs[typeArgs.Length - 1]; var ind0 = typeArgs.Length - 2; int ind1 = 0; for (int i = 0; i <= ind0; i++) { ind1 <<= 1; var type = typeArgs[i]; if (type.IsByRef) { ind1++; newArgs[i] = type.GetElementType(); } else { newArgs[i] = type; } } ind1--; Console.WriteLine($"ind0: {ind0}, ind1: {ind1}"); return typeFunc[ind0][ind1].MakeGenericType(newArgs); } } else if (isVoid) return System.Linq.Expressions.Expression.GetActionType(typeArgs.Slice(0, typeArgs.Length - 1).ToArray()); else return System.Linq.Expressions.Expression.GetFuncType(typeArgs); #endif } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.SharePoint; namespace GSoft.Dynamite.Binding { /// <summary> /// An adapter class to convert a SPListItemVersion to an IDictionary&lt;string, object&gt;. /// </summary> [CLSCompliant(false)] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Adding Dictionnary would be harder to understand.")] public class ListItemVersionValuesAdapter : IDictionary<string, object>, ISharePointListItemValues { #region Fields private readonly SPListItemVersion _listItemVersion; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ListItemValuesAdapter"/> class. /// </summary> /// <param name="listItemVersion">The list item version.</param> public ListItemVersionValuesAdapter(SPListItemVersion listItemVersion) { this._listItemVersion = listItemVersion; } #endregion #region ISharePointListItemValues Members /// <summary> /// Returns the parent SPListItem of the underlying SPListItemVersion. /// </summary> public SPListItem ListItem { get { return this._listItemVersion.ListItem; } } #endregion #region IDictionary<string,object> Members /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public int Count { get { return this._listItemVersion.Fields.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<string> Keys { get { return this._listItemVersion.Fields.Cast<SPField>().Select(x => x.InternalName).ToList(); } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<object> Values { get { return this._listItemVersion.Fields.Cast<SPField>().Select(x => this._listItemVersion[x.InternalName]).ToList(); } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="key">The key to get or set.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> public object this[string key] { get { return this._listItemVersion[key]; } set { throw new InvalidOperationException("Cannot set values on a version."); } } /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="T:System.NotSupportedException">This method is not supported.</exception> public void Add(string key, object value) { throw new NotSupportedException(); } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException">This method is not supported.</exception> public void Add(KeyValuePair<string, object> item) { throw new InvalidOperationException("Cannot set values on a version."); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public void Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<string, object> item) { object value; return this.TryGetValue(item.Key, out value) && object.Equals(value, item.Value); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param> /// <returns> /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(string key) { return this._listItemVersion.Fields.GetFieldByInternalName(key) != null; } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { var pos = arrayIndex; foreach (var keyValue in this) { array[pos++] = keyValue; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return this._listItemVersion.Fields.Cast<SPField>().Select( x => new KeyValuePair<string, object>(x.InternalName, this._listItemVersion[x.InternalName])).GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool Remove(string key) { throw new NotSupportedException(); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(KeyValuePair<string, object> item) { throw new NotSupportedException(); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Try get value replaces the exception with null.")] public bool TryGetValue(string key, out object value) { try { value = this._listItemVersion[key]; return true; } catch { value = null; return false; } } #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. namespace System.Text { using System; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [Serializable] public sealed class EncoderExceptionFallback : EncoderFallback { // Construction public EncoderExceptionFallback() { } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderExceptionFallbackBuffer(); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 0; } } public override bool Equals(Object value) { EncoderExceptionFallback that = value as EncoderExceptionFallback; if (that != null) { return (true); } return (false); } public override int GetHashCode() { return 654; } } public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer { public EncoderExceptionFallbackBuffer(){} public override bool Fallback(char charUnknown, int index) { // Fall back our char throw new EncoderFallbackException( Environment.GetResourceString("Argument_InvalidCodePageConversionIndex", (int)charUnknown, index), charUnknown, index); } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!Char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); } if (!Char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("CharUnknownLow", Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); } Contract.EndContractBlock(); int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow); // Fall back our char throw new EncoderFallbackException( Environment.GetResourceString("Argument_InvalidCodePageConversionIndex", iTemp, index), charUnknownHigh, charUnknownLow, index); } public override char GetNextChar() { return (char)0; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. return false; } // Exceptions are always empty public override int Remaining { get { return 0; } } } [Serializable] public sealed class EncoderFallbackException : ArgumentException { char charUnknown; char charUnknownHigh; char charUnknownLow; int index; public EncoderFallbackException() : base(Environment.GetResourceString("Arg_ArgumentException")) { SetErrorCode(__HResults.COR_E_ARGUMENT); } public EncoderFallbackException(String message) : base(message) { SetErrorCode(__HResults.COR_E_ARGUMENT); } public EncoderFallbackException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_ARGUMENT); } internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal EncoderFallbackException( String message, char charUnknown, int index) : base(message) { this.charUnknown = charUnknown; this.index = index; } internal EncoderFallbackException( String message, char charUnknownHigh, char charUnknownLow, int index) : base(message) { if (!Char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); } if (!Char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException(nameof(CharUnknownLow), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); } Contract.EndContractBlock(); this.charUnknownHigh = charUnknownHigh; this.charUnknownLow = charUnknownLow; this.index = index; } public char CharUnknown { get { return (charUnknown); } } public char CharUnknownHigh { get { return (charUnknownHigh); } } public char CharUnknownLow { get { return (charUnknownLow); } } public int Index { get { return index; } } // Return true if the unknown character is a surrogate pair. public bool IsUnknownSurrogate() { return (this.charUnknownHigh != '\0'); } } }
// <copyright file="Requires.NumericTypesPositiveValidation.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Runtime.CompilerServices; namespace IX.StandardExtensions.Contracts; /// <summary> /// Methods for approximating the works of contract-oriented programming. /// </summary> public static partial class Requires { /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="byte" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in byte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="byte" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out byte field, in byte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="sbyte" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in sbyte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="sbyte" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in sbyte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="sbyte" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out sbyte field, in sbyte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="sbyte" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out sbyte field, in sbyte argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="short" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in short argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="short" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in short argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="short" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out short field, in short argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="short" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out short field, in short argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="ushort" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in ushort argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="ushort" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out ushort field, in ushort argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="char" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in char argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="char" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out char field, in char argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="int" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in int argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="int" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in int argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="int" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out int field, in int argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="int" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out int field, in int argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="uint" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in uint argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="uint" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out uint field, in uint argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="long" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in long argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="long" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in long argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="long" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out long field, in long argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="long" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out long field, in long argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="ulong" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in ulong argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="ulong" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveIntegerException"> /// The argument is equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out ulong field, in ulong argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument == 0) { throw new ArgumentNotPositiveIntegerException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="float" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in float argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="float" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in float argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="float" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out float field, in float argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="float" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out float field, in float argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="double" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in double argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="double" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in double argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="double" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out double field, in double argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="double" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out double field, in double argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="decimal" /> is /// positive (greater than zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( in decimal argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a contract requires that a numeric argument of type <see cref="decimal" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( in decimal argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="decimal" /> is /// positive (greater than zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than or equal to 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Positive( out decimal field, in decimal argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument <= 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } /// <summary> /// Called when a field initialization requires that a numeric argument of type <see cref="decimal" /> is /// non-negative (greater than or equal to zero). /// </summary> /// <param name="field"> /// The field that the argument is initializing. /// </param> /// <param name="argument"> /// The numeric argument. /// </param> /// <param name="argumentName"> /// The argument name. /// </param> /// <exception cref="ArgumentNotPositiveException"> /// The argument is less than 0. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void NonNegative( out decimal field, in decimal argument, [CallerArgumentExpression("argument")] string argumentName = "argument") { if (argument < 0) { throw new ArgumentNotPositiveException(argumentName); } field = argument; } }
// // CGContext.cs: Implements the managed CGContext // // Authors: Mono Team // // Copyright 2009 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreGraphics { public enum CGLineJoin { Miter, Round, Bevel } public enum CGLineCap { Butt, Round, Square } public enum CGPathDrawingMode { Fill, EOFill, Stroke, FillStroke, EOFillStroke } public enum CGTextDrawingMode { Fill, Stroke, FillStroke, Invisible, FillClip, StrokeClip, FillStrokeClip, Clip } public enum CGTextEncoding { FontSpecific, MacRoman } public enum CGInterpolationQuality { Default, None, Low, High, Medium /* Yes, in this order, since Medium was added in 4 */ } public enum CGBlendMode { Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, SoftLight, HardLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity, Clear, Copy, SourceIn, SourceOut, SourceAtop, DestinationOver, DestinationIn, DestinationOut, DestinationAtop, XOR, PlusDarker, PlusLighter } public class CGContext : INativeObject, IDisposable { internal IntPtr handle; public CGContext (IntPtr handle) { if (handle == IntPtr.Zero) throw new Exception ("Invalid parameters to context creation"); CGContextRetain (handle); this.handle = handle; } internal CGContext () { } [Preserve (Conditional=true)] internal CGContext (IntPtr handle, bool owns) { if (!owns) CGContextRetain (handle); if (handle == IntPtr.Zero) throw new Exception ("Invalid handle"); this.handle = handle; } ~CGContext () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRelease (IntPtr handle); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRetain (IntPtr handle); protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CGContextRelease (handle); handle = IntPtr.Zero; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSaveGState (IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRestoreGState (IntPtr context); public void SaveState () { CGContextSaveGState (handle); } public void RestoreState () { CGContextRestoreGState (handle); } // // Transformation matrix // [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextScaleCTM (IntPtr ctx, float sx, float sy); public void ScaleCTM (float sx, float sy) { CGContextScaleCTM (handle, sx, sy); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextTranslateCTM (IntPtr ctx, float tx, float ty); public void TranslateCTM (float tx, float ty) { CGContextTranslateCTM (handle, tx, ty); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextRotateCTM (IntPtr ctx, float angle); public void RotateCTM (float angle) { CGContextRotateCTM (handle, angle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextConcatCTM (IntPtr ctx, CGAffineTransform transform); public void ConcatCTM (CGAffineTransform transform) { CGContextConcatCTM (handle, transform); } // Settings [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineWidth(IntPtr c, float width); public void SetLineWidth (float w) { CGContextSetLineWidth (handle, w); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineCap(IntPtr c, CGLineCap cap); public void SetLineCap (CGLineCap cap) { CGContextSetLineCap (handle, cap); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineJoin(IntPtr c, CGLineJoin join); public void SetLineJoin (CGLineJoin join) { CGContextSetLineJoin (handle, join); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetMiterLimit(IntPtr c, float limit); public void SetMiterLimit (float limit) { CGContextSetMiterLimit (handle, limit); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetLineDash(IntPtr c, float phase, float [] lengths, int count); public void SetLineDash (float phase, float [] lengths) { int n = lengths == null ? 0 : lengths.Length; CGContextSetLineDash (handle, phase, lengths, n); } public void SetLineDash (float phase, float [] lengths, int n) { if (lengths == null) n = 0; else if (n < 0 || n > lengths.Length) throw new ArgumentException ("n"); CGContextSetLineDash (handle, phase, lengths, n); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFlatness(IntPtr c, float flatness); public void SetFlatness (float flatness) { CGContextSetFlatness (handle, flatness); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetAlpha(IntPtr c, float alpha); public void SetAlpha (float alpha) { CGContextSetAlpha (handle, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetBlendMode(IntPtr context, CGBlendMode mode); public void SetBlendMode (CGBlendMode mode) { CGContextSetBlendMode (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetCTM (IntPtr c); public CGAffineTransform GetCTM () { return CGContextGetCTM (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextBeginPath(IntPtr c); public void BeginPath () { CGContextBeginPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextMoveToPoint(IntPtr c, float x, float y); public void MoveTo (float x, float y) { CGContextMoveToPoint (handle, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddLineToPoint(IntPtr c, float x, float y); public void AddLineToPoint (float x, float y) { CGContextAddLineToPoint (handle, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddCurveToPoint(IntPtr c, float cp1x, float cp1y, float cp2x, float cp2y, float x, float y); public void AddCurveToPoint (float cp1x, float cp1y, float cp2x, float cp2y, float x, float y) { CGContextAddCurveToPoint (handle, cp1x, cp1y, cp2x, cp2y, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddQuadCurveToPoint(IntPtr c, float cpx, float cpy, float x, float y); public void AddQuadCurveToPoint (float cpx, float cpy, float x, float y) { CGContextAddQuadCurveToPoint (handle, cpx, cpy, x, y); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClosePath(IntPtr c); public void ClosePath () { CGContextClosePath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddRect(IntPtr c, RectangleF rect); public void AddRect (RectangleF rect) { CGContextAddRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddRects(IntPtr c, RectangleF [] rects, int size_t_count) ; public void AddRects (RectangleF [] rects) { CGContextAddRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddLines(IntPtr c, PointF [] points, int size_t_count) ; public void AddLines (PointF [] points) { CGContextAddLines (handle, points, points.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddEllipseInRect(IntPtr context, RectangleF rect); public void AddEllipseInRect (RectangleF rect) { CGContextAddEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddArc(IntPtr c, float x, float y, float radius, float startAngle, float endAngle, int clockwise); public void AddArc (float x, float y, float radius, float startAngle, float endAngle, bool clockwise) { CGContextAddArc (handle, x, y, radius, startAngle, endAngle, clockwise ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddArcToPoint(IntPtr c, float x1, float y1, float x2, float y2, float radius); public void AddArcToPoint (float x1, float y1, float x2, float y2, float radius) { CGContextAddArcToPoint (handle, x1, y1, x2, y2, radius); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextAddPath(IntPtr context, IntPtr path_ref); public void AddPath (CGPath path) { CGContextAddPath (handle, path.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextReplacePathWithStrokedPath(IntPtr c); public void ReplacePathWithStrokedPath () { CGContextReplacePathWithStrokedPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGContextIsPathEmpty(IntPtr c); public bool IsPathEmpty () { return CGContextIsPathEmpty (handle) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextGetPathCurrentPoint(IntPtr c); public PointF GetPathCurrentPoint () { return CGContextGetPathCurrentPoint (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextGetPathBoundingBox(IntPtr c); public RectangleF GetPathBoundingBox () { return CGContextGetPathBoundingBox (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGContextPathContainsPoint(IntPtr context, PointF point, CGPathDrawingMode mode); public bool PathContainsPoint (PointF point, CGPathDrawingMode mode) { return CGContextPathContainsPoint (handle, point, mode) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawPath(IntPtr c, CGPathDrawingMode mode); public void DrawPath (CGPathDrawingMode mode) { CGContextDrawPath (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillPath(IntPtr c); public void FillPath () { CGContextFillPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEOFillPath(IntPtr c); public void EOFillPath () { CGContextEOFillPath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokePath(IntPtr c); public void StrokePath () { CGContextStrokePath (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillRect(IntPtr c, RectangleF rect); public void FillRect (RectangleF rect) { CGContextFillRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillRects(IntPtr c, RectangleF [] rects, int size_t_count); public void ContextFillRects (RectangleF [] rects) { CGContextFillRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeRect(IntPtr c, RectangleF rect); public void StrokeRect (RectangleF rect) { CGContextStrokeRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeRectWithWidth(IntPtr c, RectangleF rect, float width); public void StrokeRectWithWidth (RectangleF rect, float width) { CGContextStrokeRectWithWidth (handle, rect, width); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClearRect(IntPtr c, RectangleF rect); public void ClearRect (RectangleF rect) { CGContextClearRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFillEllipseInRect(IntPtr context, RectangleF rect); public void FillEllipseInRect (RectangleF rect) { CGContextFillEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeEllipseInRect(IntPtr context, RectangleF rect); public void StrokeEllipseInRect (RectangleF rect) { CGContextStrokeEllipseInRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextStrokeLineSegments(IntPtr c, PointF [] points, int size_t_count); public void StrokeLineSegments (PointF [] points) { CGContextStrokeLineSegments (handle, points, points.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClip(IntPtr c); public void Clip () { CGContextClip (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEOClip(IntPtr c); public void EOClip () { CGContextEOClip (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToMask(IntPtr c, RectangleF rect, IntPtr mask); public void ClipToMask (RectangleF rect, CGImage mask) { CGContextClipToMask (handle, rect, mask.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextGetClipBoundingBox(IntPtr c); public RectangleF GetClipBoundingBox () { return CGContextGetClipBoundingBox (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToRect(IntPtr c, RectangleF rect); public void ClipToRect (RectangleF rect) { CGContextClipToRect (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextClipToRects(IntPtr c, RectangleF [] rects, int size_t_count); public void ClipToRects (RectangleF [] rects) { CGContextClipToRects (handle, rects, rects.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColorWithColor(IntPtr c, IntPtr color); public void SetFillColor (CGColor color) { CGContextSetFillColorWithColor (handle, color.handle); } [Advice ("Use SetFillColor() instead.")] public void SetFillColorWithColor (CGColor color) { CGContextSetFillColorWithColor (handle, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColorWithColor(IntPtr c, IntPtr color); public void SetStrokeColor (CGColor color) { CGContextSetStrokeColorWithColor (handle, color.handle); } [Advice ("Use SetStrokeColor() instead.")] public void SetStrokeColorWithColor (CGColor color) { CGContextSetStrokeColorWithColor (handle, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColorSpace(IntPtr context, IntPtr space); public void SetFillColorSpace (CGColorSpace space) { CGContextSetFillColorSpace (handle, space.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColorSpace(IntPtr context, IntPtr space); public void SetStrokeColorSpace (CGColorSpace space) { CGContextSetStrokeColorSpace (handle, space.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillColor(IntPtr context, float [] components); public void SetFillColor (float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetFillColor (handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokeColor(IntPtr context, float [] components); public void SetStrokeColor (float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetStrokeColor (handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFillPattern(IntPtr context, IntPtr pattern, float [] components); public void SetFillPattern (CGPattern pattern, float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetFillPattern (handle, pattern.handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetStrokePattern(IntPtr context, IntPtr pattern, float [] components); public void SetStrokePattern (CGPattern pattern, float [] components) { if (components == null) throw new ArgumentNullException ("components"); CGContextSetStrokePattern (handle, pattern.handle, components); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetPatternPhase(IntPtr context, SizeF phase); public void SetPatternPhase (SizeF phase) { CGContextSetPatternPhase (handle, phase); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetGrayFillColor(IntPtr context, float gray, float alpha); public void SetFillColor (float gray, float alpha) { CGContextSetGrayFillColor (handle, gray, alpha); } [Advice ("Use SetFillColor() instead.")] public void SetGrayFillColor (float gray, float alpha) { CGContextSetGrayFillColor (handle, gray, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetGrayStrokeColor(IntPtr context, float gray, float alpha); public void SetStrokeColor (float gray, float alpha) { CGContextSetGrayStrokeColor (handle, gray, alpha); } [Advice ("Use SetStrokeColor() instead.")] public void SetGrayStrokeColor (float gray, float alpha) { CGContextSetGrayStrokeColor (handle, gray, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRGBFillColor(IntPtr context, float red, float green, float blue, float alpha); public void SetFillColor (float red, float green, float blue, float alpha) { CGContextSetRGBFillColor (handle, red, green, blue, alpha); } [Advice ("Use SetFillColor() instead.")] public void SetRGBFillColor (float red, float green, float blue, float alpha) { CGContextSetRGBFillColor (handle, red, green, blue, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRGBStrokeColor(IntPtr context, float red, float green, float blue, float alpha); public void SetStrokeColor (float red, float green, float blue, float alpha) { CGContextSetRGBStrokeColor (handle, red, green, blue, alpha); } [Advice ("Use SetStrokeColor() instead.")] public void SetRGBStrokeColor (float red, float green, float blue, float alpha) { CGContextSetRGBStrokeColor (handle, red, green, blue, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCMYKFillColor(IntPtr context, float cyan, float magenta, float yellow, float black, float alpha); public void SetFillColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKFillColor (handle, cyan, magenta, yellow, black, alpha); } [Advice ("Use SetFillColor() instead.")] public void SetCMYKFillColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKFillColor (handle, cyan, magenta, yellow, black, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCMYKStrokeColor(IntPtr context, float cyan, float magenta, float yellow, float black, float alpha); public void SetStrokeColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKStrokeColor (handle, cyan, magenta, yellow, black, alpha); } [Advice ("Use SetStrokeColor() instead.")] public void SetCMYKStrokeColor (float cyan, float magenta, float yellow, float black, float alpha) { CGContextSetCMYKStrokeColor (handle, cyan, magenta, yellow, black, alpha); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetRenderingIntent(IntPtr context, CGColorRenderingIntent intent); public void SetRenderingIntent (CGColorRenderingIntent intent) { CGContextSetRenderingIntent (handle, intent); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawImage(IntPtr c, RectangleF rect, IntPtr image); public void DrawImage (RectangleF rect, CGImage image) { CGContextDrawImage (handle, rect, image.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawTiledImage(IntPtr c, RectangleF rect, IntPtr image); public void DrawTiledImage (RectangleF rect, CGImage image) { CGContextDrawTiledImage (handle, rect, image.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGInterpolationQuality CGContextGetInterpolationQuality(IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetInterpolationQuality(IntPtr context, CGInterpolationQuality quality); public CGInterpolationQuality InterpolationQuality { get { return CGContextGetInterpolationQuality (handle); } set { CGContextSetInterpolationQuality (handle, value); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShadowWithColor(IntPtr context, SizeF offset, float blur, IntPtr color); public void SetShadowWithColor (SizeF offset, float blur, CGColor color) { CGContextSetShadowWithColor (handle, offset, blur, color.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShadow(IntPtr context, SizeF offset, float blur); public void SetShadow (SizeF offset, float blur) { CGContextSetShadow (handle, offset, blur); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLinearGradient(IntPtr context, IntPtr gradient, PointF startPoint, PointF endPoint, CGGradientDrawingOptions options); public void DrawLinearGradient (CGGradient gradient, PointF startPoint, PointF endPoint, CGGradientDrawingOptions options) { CGContextDrawLinearGradient (handle, gradient.handle, startPoint, endPoint, options); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawRadialGradient (IntPtr context, IntPtr gradient, PointF startCenter, float startRadius, PointF endCenter, float endRadius, CGGradientDrawingOptions options); public void DrawRadialGradient (CGGradient gradient, PointF startCenter, float startRadius, PointF endCenter, float endRadius, CGGradientDrawingOptions options) { CGContextDrawRadialGradient (handle, gradient.handle, startCenter, startRadius, endCenter, endRadius, options); } #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawShading(IntPtr context, IntPtr shading); public void DrawShading (CGShading shading) { CGContextDrawShading (handle, shading.handle); } #endif [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetCharacterSpacing(IntPtr context, float spacing); public void SetCharacterSpacing (float spacing) { CGContextSetCharacterSpacing (handle, spacing); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextPosition(IntPtr c, float x, float y); [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextGetTextPosition(IntPtr context); public PointF TextPosition { get { return CGContextGetTextPosition (handle); } set { CGContextSetTextPosition (handle, value.X, value.Y); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextMatrix(IntPtr c, CGAffineTransform t); [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetTextMatrix(IntPtr c); public CGAffineTransform TextMatrix { get { return CGContextGetTextMatrix (handle); } set { CGContextSetTextMatrix (handle, value); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetTextDrawingMode(IntPtr c, CGTextDrawingMode mode); public void SetTextDrawingMode (CGTextDrawingMode mode) { CGContextSetTextDrawingMode (handle, mode); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFont(IntPtr c, IntPtr font); public void SetFont (CGFont font) { CGContextSetFont (handle, font.handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetFontSize(IntPtr c, float size); public void SetFontSize (float size) { CGContextSetFontSize (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSelectFont(IntPtr c, string name, float size, CGTextEncoding textEncoding); public void SelectFont (string name, float size, CGTextEncoding textEncoding) { if (name == null) throw new ArgumentNullException ("name"); CGContextSelectFont (handle, name, size, textEncoding); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsAtPositions(IntPtr context, ushort [] glyphs, PointF [] positions, int size_t_count); public void ShowGlyphsAtPositions (ushort [] glyphs, PointF [] positions, int size_t_count) { if (positions == null) throw new ArgumentNullException ("positions"); if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphsAtPositions (handle, glyphs, positions, size_t_count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowText(IntPtr c, string s, int size_t_length); public void ShowText (string str, int count) { if (str == null) throw new ArgumentNullException ("str"); if (count > str.Length) throw new ArgumentException ("count"); CGContextShowText (handle, str, count); } public void ShowText (string str) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowText (handle, str, str.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowText(IntPtr c, byte[] bytes, int size_t_length); public void ShowText (byte[] bytes, int count) { if (bytes == null) throw new ArgumentNullException ("bytes"); if (count > bytes.Length) throw new ArgumentException ("count"); CGContextShowText (handle, bytes, count); } public void ShowText (byte[] bytes) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowText (handle, bytes, bytes.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowTextAtPoint(IntPtr c, float x, float y, string str, int size_t_length); public void ShowTextAtPoint (float x, float y, string str, int length) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowTextAtPoint (handle, x, y, str, length); } public void ShowTextAtPoint (float x, float y, string str) { if (str == null) throw new ArgumentNullException ("str"); CGContextShowTextAtPoint (handle, x, y, str, str.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowTextAtPoint(IntPtr c, float x, float y, byte[] bytes, int size_t_length); public void ShowTextAtPoint (float x, float y, byte[] bytes, int length) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowTextAtPoint (handle, x, y, bytes, length); } public void ShowTextAtPoint (float x, float y, byte[] bytes) { if (bytes == null) throw new ArgumentNullException ("bytes"); CGContextShowTextAtPoint (handle, x, y, bytes, bytes.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphs(IntPtr c, ushort [] glyphs, int size_t_count); public void ShowGlyphs (ushort [] glyphs) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphs (handle, glyphs, glyphs.Length); } public void ShowGlyphs (ushort [] glyphs, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (count > glyphs.Length) throw new ArgumentException ("count"); CGContextShowGlyphs (handle, glyphs, count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsAtPoint(IntPtr context, float x, float y, ushort [] glyphs, int size_t_count); public void ShowGlyphsAtPoint (float x, float y, ushort [] glyphs, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (count > glyphs.Length) throw new ArgumentException ("count"); CGContextShowGlyphsAtPoint (handle, x, y, glyphs, count); } public void ShowGlyphsAtPoint (float x, float y, ushort [] glyphs) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); CGContextShowGlyphsAtPoint (handle, x, y, glyphs, glyphs.Length); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowGlyphsWithAdvances(IntPtr c, ushort [] glyphs, SizeF [] advances, int size_t_count); public void ShowGlyphsWithAdvances (ushort [] glyphs, SizeF [] advances, int count) { if (glyphs == null) throw new ArgumentNullException ("glyphs"); if (advances == null) throw new ArgumentNullException ("advances"); if (count > glyphs.Length || count > advances.Length) throw new ArgumentException ("count"); CGContextShowGlyphsWithAdvances (handle, glyphs, advances, count); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawPDFPage(IntPtr c, IntPtr page); public void DrawPDFPage (CGPDFPage page) { CGContextDrawPDFPage (handle, page.handle); } [DllImport (Constants.CoreGraphicsLibrary)] unsafe extern static void CGContextBeginPage(IntPtr c, ref RectangleF mediaBox); [DllImport (Constants.CoreGraphicsLibrary)] unsafe extern static void CGContextBeginPage(IntPtr c, IntPtr zero); public void BeginPage (RectangleF? rect) { if (rect.HasValue){ RectangleF v = rect.Value; CGContextBeginPage (handle, ref v); } else { CGContextBeginPage (handle, IntPtr.Zero); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextEndPage(IntPtr c); public void EndPage () { CGContextEndPage (handle); } //[DllImport (Constants.CoreGraphicsLibrary)] //extern static IntPtr CGContextRetain(IntPtr c); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextFlush(IntPtr c); public void Flush () { CGContextFlush (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSynchronize(IntPtr c); public void Synchronize () { CGContextSynchronize (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShouldAntialias(IntPtr c, int shouldAntialias); public void SetShouldAntialias (bool shouldAntialias) { CGContextSetShouldAntialias (handle, shouldAntialias ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetAllowsAntialiasing(IntPtr context, int allowsAntialiasing); public void SetAllowsAntialiasing (bool allowsAntialiasing) { CGContextSetAllowsAntialiasing (handle, allowsAntialiasing ? 1 : 0); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextSetShouldSmoothFonts(IntPtr c, int shouldSmoothFonts); public void SetShouldSmoothFonts (bool shouldSmoothFonts) { CGContextSetShouldSmoothFonts (handle, shouldSmoothFonts ? 1 : 0); } //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextBeginTransparencyLayer(IntPtr context, CFDictionaryRef auxiliaryInfo); //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextBeginTransparencyLayerWithRect(IntPtr context, RectangleF rect, CFDictionaryRef auxiliaryInfo) //[DllImport (Constants.CoreGraphicsLibrary)] //extern static void CGContextEndTransparencyLayer(IntPtr context); [DllImport (Constants.CoreGraphicsLibrary)] extern static CGAffineTransform CGContextGetUserSpaceToDeviceSpaceTransform(IntPtr context); public CGAffineTransform GetUserSpaceToDeviceSpaceTransform() { return CGContextGetUserSpaceToDeviceSpaceTransform (handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextConvertPointToDeviceSpace(IntPtr context, PointF point); public PointF PointToDeviceSpace (PointF point) { return CGContextConvertPointToDeviceSpace (handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static PointF CGContextConvertPointToUserSpace(IntPtr context, PointF point); public PointF ConvertPointToUserSpace (PointF point) { return CGContextConvertPointToUserSpace (handle, point); } [DllImport (Constants.CoreGraphicsLibrary)] extern static SizeF CGContextConvertSizeToDeviceSpace(IntPtr context, SizeF size); public SizeF ConvertSizeToDeviceSpace (SizeF size) { return CGContextConvertSizeToDeviceSpace (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static SizeF CGContextConvertSizeToUserSpace(IntPtr context, SizeF size); public SizeF ConvertSizeToUserSpace (SizeF size) { return CGContextConvertSizeToUserSpace (handle, size); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextConvertRectToDeviceSpace(IntPtr context, RectangleF rect); public RectangleF ConvertRectToDeviceSpace (RectangleF rect) { return CGContextConvertRectToDeviceSpace (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static RectangleF CGContextConvertRectToUserSpace(IntPtr context, RectangleF rect); public RectangleF ConvertRectToUserSpace (RectangleF rect) { return CGContextConvertRectToUserSpace (handle, rect); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLayerInRect (IntPtr context, RectangleF rect, IntPtr layer); public void DrawLayer (CGLayer layer, RectangleF rect) { if (layer == null) throw new ArgumentNullException ("layer"); CGContextDrawLayerInRect (handle, rect, layer.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextDrawLayerAtPoint (IntPtr context, PointF rect, IntPtr layer); public void DrawLayer (CGLayer layer, PointF point) { if (layer == null) throw new ArgumentNullException ("layer"); CGContextDrawLayerAtPoint (handle, point, layer.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextCopyPath (IntPtr context); [Since (4,0)] public CGPath CopyPath () { var r = CGContextCopyPath (handle); return new CGPath (r, true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSmoothing (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsFontSmoothing (bool allows) { CGContextSetAllowsFontSmoothing (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSubpixelPositioning (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsSubpixelPositioning (bool allows) { CGContextSetAllowsFontSubpixelPositioning (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetAllowsFontSubpixelQuantization (IntPtr context, bool allows); [Since (4,0)] public void SetAllowsFontSubpixelQuantization (bool allows) { CGContextSetAllowsFontSubpixelQuantization (handle, allows); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetShouldSubpixelPositionFonts (IntPtr context, bool should); [Since (4,0)] public void SetShouldSubpixelPositionFonts (bool shouldSubpixelPositionFonts) { CGContextSetShouldSubpixelPositionFonts (handle, shouldSubpixelPositionFonts); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextSetShouldSubpixelQuantizeFonts (IntPtr context, bool should); [Since (4,0)] public void ShouldSubpixelQuantizeFonts (bool shouldSubpixelQuantizeFonts) { CGContextSetShouldSubpixelQuantizeFonts (handle, shouldSubpixelQuantizeFonts); } #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextBeginTransparencyLayer (IntPtr context, IntPtr dictionary); public void BeginTransparencyLayer () { CGContextBeginTransparencyLayer (handle, IntPtr.Zero); } public void BeginTransparencyLayer (NSDictionary auxiliaryInfo = null) { CGContextBeginTransparencyLayer (handle, auxiliaryInfo == null ? IntPtr.Zero : auxiliaryInfo.Handle); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextBeginTransparencyLayerWithRect (IntPtr context, RectangleF rect, IntPtr dictionary); public void BeginTransparencyLayer (RectangleF rectangle, NSDictionary auxiliaryInfo = null) { CGContextBeginTransparencyLayerWithRect (handle, rectangle, auxiliaryInfo == null ? IntPtr.Zero : auxiliaryInfo.Handle); } public void BeginTransparencyLayer (RectangleF rectangle) { CGContextBeginTransparencyLayerWithRect (handle, rectangle, IntPtr.Zero); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGContextEndTransparencyLayer (IntPtr context); public void EndTransparencyLayer () { CGContextEndTransparencyLayer (handle); } #endif } }
// 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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1 { internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private readonly int _correlationId; private readonly MemberRangeMap _memberRangeMap; private readonly AnalyzerExecutor _executor; private readonly StateManager _stateManager; public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, HostAnalyzerManager analyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource) { _correlationId = correlationId; _memberRangeMap = new MemberRangeMap(); _executor = new AnalyzerExecutor(this); _stateManager = new StateManager(analyzerManager); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; } private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // events will be automatically serialized. ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None); } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken)) { return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken)) { // we don't need the info for closed file _memberRangeMap.Remove(document.Id); return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken)) { // clear states for re-analysis and raise events about it. otherwise, some states might not updated on re-analysis // due to our build-live de-duplication logic where we put all state in Documents state. return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } private Task ClearOnlyDocumentStates(Document document, bool raiseEvent, CancellationToken cancellationToken) { // we remove whatever information we used to have on document open/close and re-calculate diagnostics // we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not. // so we can't use cached information. ClearDocumentStates(document, _stateManager.GetStateSets(document.Project), raiseEvent, includeProjectState: false, cancellationToken: cancellationToken); return SpecializedTasks.EmptyTask; } private bool CheckOption(Workspace workspace, string language, bool documentOpened) { var optionService = workspace.Services.GetService<IOptionService>(); if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language)) { return true; } if (documentOpened) { return true; } return false; } internal IEnumerable<DiagnosticAnalyzer> GetAnalyzers(Project project) { return _stateManager.GetAnalyzers(project); } public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken); var openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds)) { var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreated(StateType.Syntax, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } var state = stateSet.GetState(StateType.Syntax); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion, projectVersion); if (bodyOpt == null) { await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false); } else { // only open file can go this route await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken) { try { // syntax facts service must exist, otherwise, this method won't have called. var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var memberId = syntaxFacts.GetMethodLevelMemberId(root, member); var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, cancellationToken); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document)) { var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis(); var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document); var data = await _executor.GetDocumentBodyAnalysisDataAsync( stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false); _memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges); var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken); bool openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds)) { var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } if (openedDocument) { _memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion); } var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false); } private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { try { // Compilation actions can report diagnostics on open files, so "documentOpened = true" if (!CheckOption(project.Solution.Workspace, project.Language, documentOpened: true)) { return; } var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, cancellationToken); var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(project)) { // Compilation actions can report diagnostics on open files, so we skipClosedFileChecks. if (SkipRunningAnalyzer(project.CompilationOptions, analyzerDriver, openedDocument: true, skipClosedFileChecks: true, stateSet: stateSet)) { await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null)) { var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseProjectDiagnosticsUpdated(project, stateSet, data.Items); continue; } var state = stateSet.GetState(StateType.Project); await PersistProjectData(project, state, data).ConfigureAwait(false); RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private bool SkipRunningAnalyzer( CompilationOptions compilationOptions, DiagnosticAnalyzerDriver userDiagnosticDriver, bool openedDocument, bool skipClosedFileChecks, StateSet stateSet) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, userDiagnosticDriver.Project)) { return true; } if (skipClosedFileChecks) { return false; } if (ShouldRunAnalyzerForClosedFile(compilationOptions, openedDocument, stateSet.Analyzer)) { return false; } return true; } private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data) { // TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to // things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough // more refactoring is required on project state. // clear all existing data state.Remove(project.Id); foreach (var document in project.Documents) { state.Remove(document.Id); } // quick bail out if (data.Items.Length == 0) { return; } // save new data var group = data.Items.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { // save project scope diagnostics await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); continue; } // save document scope diagnostics var document = project.GetDocument(kv.Key); if (document == null) { continue; } await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); } } public override void RemoveDocument(DocumentId documentId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None)) { _memberRangeMap.Remove(documentId); foreach (var stateSet in _stateManager.GetStateSets(documentId.ProjectId)) { stateSet.Remove(documentId); var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId); for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { RaiseDiagnosticsRemoved((StateType)stateType, documentId, stateSet, solutionArgs); } } } } public override void RemoveProject(ProjectId projectId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None)) { foreach (var stateSet in _stateManager.GetStateSets(projectId)) { stateSet.Remove(projectId); var solutionArgs = new SolutionArgument(null, projectId, null); RaiseDiagnosticsRemoved(StateType.Project, projectId, stateSet, solutionArgs); } } _stateManager.RemoveStateSet(projectId); } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); return await getter.TryGetAsync().ConfigureAwait(false); } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); var result = await getter.TryGetAsync().ConfigureAwait(false); Contract.Requires(result); return getter.Diagnostics; } private bool ShouldRunAnalyzerForClosedFile(CompilationOptions options, bool openedDocument, DiagnosticAnalyzer analyzer) { // we have opened document, doesn't matter if (openedDocument || analyzer.IsCompilerAnalyzer()) { return true; } // PERF: Don't query descriptors for compiler analyzer, always execute it. if (analyzer.IsCompilerAnalyzer()) { return true; } return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden); } private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? MapSeverityToReport(descriptor.DefaultSeverity) : descriptor.GetEffectiveSeverity(options); } private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.Unreachable; } } private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds) { return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors); } private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null) { // PERF: Don't query descriptors for compiler analyzer, always execute it for all state types. if (analyzer.IsCompilerAnalyzer()) { return true; } if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id))) { return false; } switch (stateTypeId) { case StateType.Syntax: return analyzer.SupportsSyntaxDiagnosticAnalysis(); case StateType.Document: return analyzer.SupportsSemanticDiagnosticAnalysis(); case StateType.Project: return analyzer.SupportsProjectDiagnosticAnalysis(); default: throw ExceptionUtilities.Unreachable; } } public override void LogAnalyzerCountSummary() { DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator); DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator); // reset the log aggregator ResetDiagnosticLogAggregator(); } private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) && project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private void RaiseDocumentDiagnosticsUpdatedIfNeeded( StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseDiagnosticsCreated(type, document.Id, stateSet, new SolutionArgument(document), newItems); } private void RaiseProjectDiagnosticsUpdatedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems); RaiseProjectDiagnosticsUpdated(project, stateSet, newItems); } private void RaiseProjectDiagnosticsRemovedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { if (existingItems.Length == 0) { return; } var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key)); foreach (var documentId in removedItems) { if (documentId == null) { RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project)); continue; } var document = project.GetDocument(documentId); var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document); RaiseDiagnosticsRemoved(StateType.Project, documentId, stateSet, argument); } } private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics) { var group = diagnostics.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty()); continue; } RaiseDiagnosticsCreated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty()); } } private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId) { return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty; } private void RaiseDiagnosticsCreated( StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics) { if (Owner == null) { return; } // get right arg id for the given analyzer var id = CreateArgumentKey(type, key, stateSet); Owner.RaiseDiagnosticsUpdated(this, DiagnosticsUpdatedArgs.DiagnosticsCreated(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics)); } private static ArgumentKey CreateArgumentKey(StateType type, object key, StateSet stateSet) { return stateSet.ErrorSourceName != null ? new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName) : new ArgumentKey(stateSet.Analyzer, type, key); } private void RaiseDiagnosticsRemoved( StateType type, object key, StateSet stateSet, SolutionArgument solution) { if (Owner == null) { return; } // get right arg id for the given analyzer var id = CreateArgumentKey(type, key, stateSet); Owner.RaiseDiagnosticsUpdated(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId)); } private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics( AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics, SyntaxTree tree, SyntaxNode member, int memberId) { // get old span var oldSpan = range[memberId]; // get old diagnostics var diagnostics = existingData.Items; // check quick exit cases if (diagnostics.Length == 0 && memberDiagnostics.Length == 0) { return diagnostics; } // simple case if (diagnostics.Length == 0 && memberDiagnostics.Length > 0) { return memberDiagnostics; } // regular case var result = new List<DiagnosticData>(); // update member location Contract.Requires(member.FullSpan.Start == oldSpan.Start); var delta = member.FullSpan.End - oldSpan.End; var replaced = false; foreach (var diagnostic in diagnostics) { if (diagnostic.TextSpan.Start < oldSpan.Start) { result.Add(diagnostic); continue; } if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } if (oldSpan.End <= diagnostic.TextSpan.Start) { result.Add(UpdatePosition(diagnostic, tree, delta)); continue; } } // if it haven't replaced, replace it now if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } return result.ToImmutableArray(); } private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta) { var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length); var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length); var mappedLineInfo = tree.GetMappedLineSpan(newSpan); var originalLineInfo = tree.GetLineSpan(newSpan); return new DiagnosticData( diagnostic.Id, diagnostic.Category, diagnostic.Message, diagnostic.ENUMessageForBingSearch, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.CustomTags, diagnostic.Properties, diagnostic.Workspace, diagnostic.ProjectId, new DiagnosticDataLocation(diagnostic.DocumentId, newSpan, originalFilePath: originalLineInfo.Path, originalStartLine: originalLineInfo.StartLinePosition.Line, originalStartColumn: originalLineInfo.StartLinePosition.Character, originalEndLine: originalLineInfo.EndLinePosition.Line, originalEndColumn: originalLineInfo.EndLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), mappedStartLine: mappedLineInfo.StartLinePosition.Line, mappedStartColumn: mappedLineInfo.StartLinePosition.Character, mappedEndLine: mappedLineInfo.EndLinePosition.Line, mappedEndColumn: mappedLineInfo.EndLinePosition.Character), description: diagnostic.Description, helpLink: diagnostic.HelpLink, isSuppressed: diagnostic.IsSuppressed); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null; } private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span) { if (diagnostic == null) { return false; } if (diagnostic.Location == null || diagnostic.Location == Location.None) { return false; } if (diagnostic.Location.SourceTree != tree) { return false; } if (span == null) { return true; } return span.Value.Contains(diagnostic.Location.SourceSpan); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { yield break; } foreach (var diagnostic in diagnostics) { if (diagnostic.Location == null || diagnostic.Location == Location.None) { yield return DiagnosticData.Create(project, diagnostic); continue; } var document = project.GetDocument(diagnostic.Location.SourceTree); if (document == null) { continue; } yield return DiagnosticData.Create(document, diagnostic); } } private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private void ClearDocumentStates( Document document, IEnumerable<StateSet> states, bool raiseEvent, bool includeProjectState, CancellationToken cancellationToken) { // Compiler + User diagnostics foreach (var state in states) { for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { if (!includeProjectState && stateType == (int)StateType.Project) { // don't re-set project state type continue; } cancellationToken.ThrowIfCancellationRequested(); ClearDocumentState(document, state, (StateType)stateType, raiseEvent); } } } private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent) { var state = stateSet.GetState(type); // remove saved info state.Remove(document.Id); if (raiseEvent) { // raise diagnostic updated event var documentId = document.Id; var solutionArgs = new SolutionArgument(document); RaiseDiagnosticsRemoved(type, document.Id, stateSet, solutionArgs); } } private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken) { foreach (var document in project.Documents) { ClearDocumentStates(document, states, raiseEvent: true, includeProjectState: true, cancellationToken: cancellationToken); } foreach (var stateSet in states) { cancellationToken.ThrowIfCancellationRequested(); ClearProjectState(project, stateSet); } } private void ClearProjectState(Project project, StateSet stateSet) { var state = stateSet.GetState(StateType.Project); // remove saved cache state.Remove(project.Id); // raise diagnostic updated event var solutionArgs = new SolutionArgument(project); RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, solutionArgs); } private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken) { var state = stateSet.GetState(type); var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearDocumentState(document, stateSet, type, raiseEvent: true); } } private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken) { var state = stateSet.GetState(StateType.Project); var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearProjectState(project, stateSet); } } private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer) { return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString()); } private static string GetResetLogMessage(Document document) { return string.Format("document reset: {0}", document.FilePath ?? document.Name); } private static string GetOpenLogMessage(Document document) { return string.Format("document open: {0}", document.FilePath ?? document.Name); } private static string GetRemoveLogMessage(DocumentId id) { return string.Format("document remove: {0}", id.ToString()); } private static string GetRemoveLogMessage(ProjectId id) { return string.Format("project remove: {0}", id.ToString()); } public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } } }
using Bridge.Test.NUnit; using System.Linq; namespace Bridge.ClientTest.Batch3.BridgeIssues { [Category(Constants.MODULE_ISSUES)] [TestFixture(TestNameFormat = "#1256 - {0}")] public class Bridge1256 { // "constructor", "__proto__" excluded private static readonly string[] reservedWords = new string[] { "abstract", "arguments", "as", "boolean", "break", "byte", "case", "catch", "char", "class", "continue", "const", /*"constructor",*/ "debugger", "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "namespace", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "use", "var", "void", "volatile", "window", "while", "with", "yield" }; private static bool IsReservedWord(string word) { { return reservedWords.Contains(word); } } private static void TestFields(object o) { if (o == null) { Assert.Fail("Object cannot be null"); return; } foreach (var name in reservedWords) { Assert.AreEqual(true, o[name], "Expected true for property " + name); } } private static void TestMethods(object o) { if (o == null) { Assert.Fail("Object cannot be null"); return; } foreach (var name in reservedWords) { Assert.NotNull(o[name], "Member " + name + " exists"); } } [Convention(Target = ConventionTarget.Member, Notation = Notation.CamelCase)] private class ReservedFields { #pragma warning disable 414 //CS0414 The field 'Bridge1256.ReservedProperties.Case' is assigned but its value is never used private bool Abstract = true; private bool Arguments = true; private bool As = true; private bool Boolean = true; private bool Break = true; private bool Byte = true; private bool Case = true; private bool Catch = true; private bool Char = true; private bool Class = true; private bool Continue = true; private bool Const = true; //private bool constructor = true; private bool Debugger = true; private bool Default = true; private bool Delete = true; private bool Do = true; private bool Double = true; private bool Else = true; private bool Enum = true; private bool Eval = true; private bool Export = true; private bool Extends = true; private bool False = true; private bool Final = true; private bool Finally = true; private bool Float = true; private bool For = true; private bool Function = true; private bool Goto = true; private bool If = true; private bool Implements = true; private bool Import = true; private bool In = true; private bool Instanceof = true; private bool Int = true; private bool Interface = true; private bool Let = true; private bool Long = true; private bool Namespace = true; private bool Native = true; private bool New = true; private bool Null = true; private bool Package = true; private bool Private = true; private bool Protected = true; private bool Public = true; private bool Return = true; private bool Short = true; private bool Static = true; private bool Super = true; private bool Switch = true; private bool Synchronized = true; private bool This = true; private bool Throw = true; private bool Throws = true; private bool Transient = true; private bool True = true; private bool Try = true; private bool Typeof = true; private bool Use = true; private bool Var = true; private bool Void = true; private bool Volatile = true; private bool Window = true; private bool While = true; private bool With = true; private bool Yield = true; } [Convention(Target = ConventionTarget.Member, Notation = Notation.CamelCase)] private class ReservedMethods { private int Abstract() { return 1; } private int Arguments() { return 2; } private int As() { return 3; } private int Boolean() { return 4; } private int Break() { return 5; } private int Byte() { return 6; } private int Case() { return 7; } private int Catch() { return 8; } private int Char() { return 9; } private int Class() { return 10; } private int Continue() { return 11; } private int Const() { return 12; } private int constructor() { return 13; } private int Debugger() { return 14; } private int Default() { return 15; } private int Delete() { return 16; } private int Do() { return 17; } private int Double() { return 18; } private int Else() { return 19; } private int Enum() { return 20; } private int Eval() { return 21; } private int Export() { return 22; } private int Extends() { return 23; } private int False() { return 24; } private int Final() { return 25; } private int Finally() { return 26; } private int Float() { return 27; } private int For() { return 28; } private int Function() { return 29; } private int Goto() { return 30; } private int If() { return 31; } private int Implements() { return 32; } private int Import() { return 33; } private int In() { return 34; } private int Instanceof() { return 35; } private int Int() { return 36; } private int Interface() { return 37; } private int Let() { return 38; } private int Long() { return 39; } private int Namespace() { return 40; } private int Native() { return 41; } private int New() { return 42; } private int Null() { return 43; } private int Package() { return 44; } private int Private() { return 45; } private int Protected() { return 46; } private int Public() { return 47; } private int Return() { return 48; } private int Short() { return 49; } private int Static() { return 50; } private int Super() { return 51; } private int Switch() { return 52; } private int Synchronized() { return 53; } private int This() { return 54; } private int Throw() { return 55; } private int Throws() { return 56; } private int Transient() { return 57; } private int True() { return 58; } private int Try() { return 59; } private int Typeof() { return 60; } private int Use() { return 61; } private int Var() { return 62; } private int Void() { return 63; } private int Volatile() { return 64; } private int Window() { return 65; } private int While() { return 65; } private int With() { return 66; } private int Yield() { return 67; } } private static bool boolean = true; [Convention(Notation.CamelCase)] private static bool Is = true; [Convention(Notation.CamelCase)] private static int Let() { return 5; } [Test(ExpectedCount = 7)] public static void TestCaseBooleanIsLet() { var let = 1; let = 2; dynamic scope = Script.Get("Bridge.ClientTest.Batch3.BridgeIssues.Bridge1256"); Assert.True(scope["boolean"]); Assert.True(scope["is"]); Assert.True(scope["let"]); Assert.True(boolean); Assert.True(Is); Assert.AreEqual(2, let); Assert.AreEqual(5, Let()); } [Test(ExpectedCount = 67)] public static void TestReservedFields() { var a = new ReservedFields(); TestFields(a); } [Test(ExpectedCount = 67)] public static void TestReservedMethods() { var a = new ReservedMethods(); TestMethods(a); } } }
using System; using Csla; namespace Invoices.Business { /// <summary> /// InvoiceCreatorGetter (creator and getter unit of work pattern).<br/> /// This is a generated base class of <see cref="InvoiceCreatorGetter"/> business object. /// This class is a root object that implements the Unit of Work pattern. /// </summary> [Serializable] public partial class InvoiceCreatorGetter : ReadOnlyBase<InvoiceCreatorGetter> { #region Business Properties /// <summary> /// Maintains metadata about unit of work (child) <see cref="Invoice"/> property. /// </summary> public static readonly PropertyInfo<InvoiceEdit> InvoiceProperty = RegisterProperty<InvoiceEdit>(p => p.Invoice, "Invoice"); /// <summary> /// Gets the Invoice object (unit of work child property). /// </summary> /// <value>The Invoice.</value> public InvoiceEdit Invoice { get { return GetProperty(InvoiceProperty); } private set { LoadProperty(InvoiceProperty, value); } } /// <summary> /// Maintains metadata about unit of work (child) <see cref="ProductTypes"/> property. /// </summary> public static readonly PropertyInfo<ProductTypeNVL> ProductTypesProperty = RegisterProperty<ProductTypeNVL>(p => p.ProductTypes, "Product Types"); /// <summary> /// Gets the Product Types object (unit of work child property). /// </summary> /// <value>The Product Types.</value> public ProductTypeNVL ProductTypes { get { return GetProperty(ProductTypesProperty); } private set { LoadProperty(ProductTypesProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="InvoiceCreatorGetter"/> unit of objects. /// </summary> /// <returns>A reference to the created <see cref="InvoiceCreatorGetter"/> unit of objects.</returns> public static InvoiceCreatorGetter NewInvoiceCreatorGetter() { // DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create. return DataPortal.Fetch<InvoiceCreatorGetter>(new Criteria1(true, new Guid())); } /// <summary> /// Factory method. Loads a <see cref="InvoiceCreatorGetter"/> unit of objects, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceCreatorGetter to fetch.</param> /// <returns>A reference to the fetched <see cref="InvoiceCreatorGetter"/> unit of objects.</returns> public static InvoiceCreatorGetter GetInvoiceCreatorGetter(Guid invoiceId) { return DataPortal.Fetch<InvoiceCreatorGetter>(new Criteria1(false, invoiceId)); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="InvoiceCreatorGetter"/> unit of objects. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewInvoiceCreatorGetter(EventHandler<DataPortalResult<InvoiceCreatorGetter>> callback) { // DataPortal_Fetch is used as ReadOnlyBase<T> doesn't allow the use of DataPortal_Create. DataPortal.BeginFetch<InvoiceCreatorGetter>(new Criteria1(true, new Guid()), (o, e) => { if (e.Error != null) throw e.Error; callback(o, e); }); } /// <summary> /// Factory method. Asynchronously loads a <see cref="InvoiceCreatorGetter"/> unit of objects, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceCreatorGetter to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetInvoiceCreatorGetter(Guid invoiceId, EventHandler<DataPortalResult<InvoiceCreatorGetter>> callback) { DataPortal.BeginFetch<InvoiceCreatorGetter>(new Criteria1(false, invoiceId), (o, e) => { if (e.Error != null) throw e.Error; callback(o, e); }); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="InvoiceCreatorGetter"/> class. /// </summary> /// <remarks> Do not use to create a Unit of Work. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public InvoiceCreatorGetter() { // Use factory methods and do not use direct creation. } #endregion #region Criteria /// <summary> /// Criteria1 criteria. /// </summary> [Serializable] protected class Criteria1 : CriteriaBase<Criteria1> { /// <summary> /// Maintains metadata about <see cref="CreateInvoiceEdit"/> property. /// </summary> public static readonly PropertyInfo<bool> CreateInvoiceEditProperty = RegisterProperty<bool>(p => p.CreateInvoiceEdit, "Create Invoice Edit"); /// <summary> /// Gets or sets the Create Invoice Edit. /// </summary> /// <value><c>true</c> if Create Invoice Edit; otherwise, <c>false</c>.</value> public bool CreateInvoiceEdit { get { return ReadProperty(CreateInvoiceEditProperty); } set { LoadProperty(CreateInvoiceEditProperty, value); } } /// <summary> /// Maintains metadata about <see cref="InvoiceId"/> property. /// </summary> public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id"); /// <summary> /// Gets or sets the Invoice Id. /// </summary> /// <value>The Invoice Id.</value> public Guid InvoiceId { get { return ReadProperty(InvoiceIdProperty); } set { LoadProperty(InvoiceIdProperty, value); } } /// <summary> /// Initializes a new instance of the <see cref="Criteria1"/> class. /// </summary> /// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public Criteria1() { } /// <summary> /// Initializes a new instance of the <see cref="Criteria1"/> class. /// </summary> /// <param name="createInvoiceEdit">The CreateInvoiceEdit.</param> /// <param name="invoiceId">The InvoiceId.</param> public Criteria1(bool createInvoiceEdit, Guid invoiceId) { CreateInvoiceEdit = createInvoiceEdit; InvoiceId = invoiceId; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is Criteria1) { var c = (Criteria1) obj; if (!CreateInvoiceEdit.Equals(c.CreateInvoiceEdit)) return false; if (!InvoiceId.Equals(c.InvoiceId)) return false; return true; } return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return string.Concat("Criteria1", CreateInvoiceEdit.ToString(), InvoiceId.ToString()).GetHashCode(); } } #endregion #region Data Access /// <summary> /// Creates or loads a <see cref="InvoiceCreatorGetter"/> unit of objects, based on given criteria. /// </summary> /// <param name="crit">The create/fetch criteria.</param> protected void DataPortal_Fetch(Criteria1 crit) { if (crit.CreateInvoiceEdit) LoadProperty(InvoiceProperty, InvoiceEdit.NewInvoiceEdit()); else LoadProperty(InvoiceProperty, InvoiceEdit.GetInvoiceEdit(crit.InvoiceId)); LoadProperty(ProductTypesProperty, ProductTypeNVL.GetProductTypeNVL()); } #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.Buffers; using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography { internal static class RSAKeyFormatHelper { private static readonly string[] s_validOids = { Oids.Rsa, }; internal static void FromPkcs1PrivateKey( ReadOnlyMemory<byte> keyData, in AlgorithmIdentifierAsn algId, out RSAParameters ret) { RSAPrivateKeyAsn key = RSAPrivateKeyAsn.Decode(keyData, AsnEncodingRules.BER); if (!algId.HasNullEquivalentParameters()) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } const int MaxSupportedVersion = 0; if (key.Version > MaxSupportedVersion) { throw new CryptographicException( SR.Format( SR.Cryptography_RSAPrivateKey_VersionTooNew, key.Version, MaxSupportedVersion)); } // The modulus size determines the encoded output size of the CRT parameters. byte[] n = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true); int halfModulusLength = (n.Length + 1) / 2; ret = new RSAParameters { Modulus = n, Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true), D = key.PrivateExponent.ExportKeyParameter(n.Length), P = key.Prime1.ExportKeyParameter(halfModulusLength), Q = key.Prime2.ExportKeyParameter(halfModulusLength), DP = key.Exponent1.ExportKeyParameter(halfModulusLength), DQ = key.Exponent2.ExportKeyParameter(halfModulusLength), InverseQ = key.Coefficient.ExportKeyParameter(halfModulusLength), }; } internal static void ReadRsaPublicKey( ReadOnlyMemory<byte> keyData, in AlgorithmIdentifierAsn algId, out RSAParameters ret) { RSAPublicKeyAsn key = RSAPublicKeyAsn.Decode(keyData, AsnEncodingRules.BER); ret = new RSAParameters { Modulus = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true), Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true), }; } internal static void ReadSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead, out RSAParameters key) { KeyFormatHelper.ReadSubjectPublicKeyInfo<RSAParameters>( s_validOids, source, ReadRsaPublicKey, out bytesRead, out key); } internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo( ReadOnlyMemory<byte> source, out int bytesRead) { return KeyFormatHelper.ReadSubjectPublicKeyInfo( s_validOids, source, out bytesRead); } public static void ReadPkcs8( ReadOnlySpan<byte> source, out int bytesRead, out RSAParameters key) { KeyFormatHelper.ReadPkcs8<RSAParameters>( s_validOids, source, FromPkcs1PrivateKey, out bytesRead, out key); } internal static ReadOnlyMemory<byte> ReadPkcs8( ReadOnlyMemory<byte> source, out int bytesRead) { return KeyFormatHelper.ReadPkcs8( s_validOids, source, out bytesRead); } internal static void ReadEncryptedPkcs8( ReadOnlySpan<byte> source, ReadOnlySpan<char> password, out int bytesRead, out RSAParameters key) { KeyFormatHelper.ReadEncryptedPkcs8<RSAParameters>( s_validOids, source, password, FromPkcs1PrivateKey, out bytesRead, out key); } internal static void ReadEncryptedPkcs8( ReadOnlySpan<byte> source, ReadOnlySpan<byte> passwordBytes, out int bytesRead, out RSAParameters key) { KeyFormatHelper.ReadEncryptedPkcs8<RSAParameters>( s_validOids, source, passwordBytes, FromPkcs1PrivateKey, out bytesRead, out key); } internal static AsnWriter WriteSubjectPublicKeyInfo(in ReadOnlySpan<byte> pkcs1PublicKey) { AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); try { writer.PushSequence(); WriteAlgorithmIdentifier(writer); writer.WriteBitString(pkcs1PublicKey); writer.PopSequence(); } catch { writer.Dispose(); throw; } return writer; } internal static AsnWriter WriteSubjectPublicKeyInfo(in RSAParameters rsaParameters) { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(rsaParameters)) { return WriteSubjectPublicKeyInfo(pkcs1PublicKey.EncodeAsSpan()); } } internal static AsnWriter WritePkcs8PrivateKey(in ReadOnlySpan<byte> pkcs1PrivateKey) { AsnWriter writer = new AsnWriter(AsnEncodingRules.BER); try { writer.PushSequence(); // Version 0 format (no attributes) writer.WriteInteger(0); WriteAlgorithmIdentifier(writer); writer.WriteOctetString(pkcs1PrivateKey); writer.PopSequence(); return writer; } catch { writer.Dispose(); throw; } } internal static AsnWriter WritePkcs8PrivateKey(in RSAParameters rsaParameters) { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(rsaParameters)) { return WritePkcs8PrivateKey(pkcs1PrivateKey.EncodeAsSpan()); } } private static void WriteAlgorithmIdentifier(AsnWriter writer) { writer.PushSequence(); // https://tools.ietf.org/html/rfc3447#appendix-C // // -- // -- When rsaEncryption is used in an AlgorithmIdentifier the // -- parameters MUST be present and MUST be NULL. // -- writer.WriteObjectIdentifier(Oids.Rsa); writer.WriteNull(); writer.PopSequence(); } internal static AsnWriter WritePkcs1PublicKey(in RSAParameters rsaParameters) { if (rsaParameters.Modulus == null || rsaParameters.Exponent == null) { throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); writer.PushSequence(); writer.WriteKeyParameterInteger(rsaParameters.Modulus); writer.WriteKeyParameterInteger(rsaParameters.Exponent); writer.PopSequence(); return writer; } internal static AsnWriter WritePkcs1PrivateKey(in RSAParameters rsaParameters) { if (rsaParameters.Modulus == null || rsaParameters.Exponent == null) { throw new CryptographicException(SR.Cryptography_InvalidRsaParameters); } if (rsaParameters.D == null || rsaParameters.P == null || rsaParameters.Q == null || rsaParameters.DP == null || rsaParameters.DQ == null || rsaParameters.InverseQ == null) { throw new CryptographicException(SR.Cryptography_NotValidPrivateKey); } AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); writer.PushSequence(); // Format version 0 writer.WriteInteger(0); writer.WriteKeyParameterInteger(rsaParameters.Modulus); writer.WriteKeyParameterInteger(rsaParameters.Exponent); writer.WriteKeyParameterInteger(rsaParameters.D); writer.WriteKeyParameterInteger(rsaParameters.P); writer.WriteKeyParameterInteger(rsaParameters.Q); writer.WriteKeyParameterInteger(rsaParameters.DP); writer.WriteKeyParameterInteger(rsaParameters.DQ); writer.WriteKeyParameterInteger(rsaParameters.InverseQ); writer.PopSequence(); return writer; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.StreamAnalytics.Models; namespace Microsoft.Azure.Management.StreamAnalytics.Models { /// <summary> /// The properties of the stream analytics job. /// </summary> public partial class JobProperties { private System.DateTime? _createdDate; /// <summary> /// Optional. Gets the created date of the stream analytics job. /// </summary> public System.DateTime? CreatedDate { get { return this._createdDate; } set { this._createdDate = value; } } private string _dataLocale; /// <summary> /// Optional. Gets or sets the data locale of the stream analytics job. /// Value should be the name of a supported .NET Culture from the set /// https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx. /// Defaults to "en-US" if none specified. /// </summary> public string DataLocale { get { return this._dataLocale; } set { this._dataLocale = value; } } private string _etag; /// <summary> /// Optional. Gets the etag of the stream analytics job. /// </summary> public string Etag { get { return this._etag; } set { this._etag = value; } } private int? _eventsLateArrivalMaxDelayInSeconds; /// <summary> /// Optional. Gets or sets the maximum tolerable delay in seconds where /// events arriving late could be included. Supported range is -1 to /// 1814399 (20.23:59:59 days) and -1 is used to specify wait /// indefinitely. If the property is absent, it is interpreted to have /// a value of -1. /// </summary> public int? EventsLateArrivalMaxDelayInSeconds { get { return this._eventsLateArrivalMaxDelayInSeconds; } set { this._eventsLateArrivalMaxDelayInSeconds = value; } } private int? _eventsOutOfOrderMaxDelayInSeconds; /// <summary> /// Optional. Gets or sets the maximum tolerable delay in seconds where /// out-of-order events can be adjusted to be back in order. /// </summary> public int? EventsOutOfOrderMaxDelayInSeconds { get { return this._eventsOutOfOrderMaxDelayInSeconds; } set { this._eventsOutOfOrderMaxDelayInSeconds = value; } } private string _eventsOutOfOrderPolicy; /// <summary> /// Optional. Gets or sets the out of order policy of the stream /// analytics job. Indicates the policy to apply to events that arrive /// out of order in the input event stream. /// </summary> public string EventsOutOfOrderPolicy { get { return this._eventsOutOfOrderPolicy; } set { this._eventsOutOfOrderPolicy = value; } } private IList<Input> _inputs; /// <summary> /// Optional. Gets or sets a list of one or more inputs. /// </summary> public IList<Input> Inputs { get { return this._inputs; } set { this._inputs = value; } } private string _jobId; /// <summary> /// Optional. Gets the id of the stream analytics job. /// </summary> public string JobId { get { return this._jobId; } set { this._jobId = value; } } private string _jobState; /// <summary> /// Optional. Gets the running state of the stream analytics job. /// </summary> public string JobState { get { return this._jobState; } set { this._jobState = value; } } private System.DateTime? _lastOutputEventTime; /// <summary> /// Optional. Gets the last output event time of the stream analytics /// job. /// </summary> public System.DateTime? LastOutputEventTime { get { return this._lastOutputEventTime; } set { this._lastOutputEventTime = value; } } private IList<Output> _outputs; /// <summary> /// Optional. Gets or sets a list of outputs. /// </summary> public IList<Output> Outputs { get { return this._outputs; } set { this._outputs = value; } } private string _outputStartMode; /// <summary> /// Optional. Gets or sets the output start mode of the stream /// analytics job. /// </summary> public string OutputStartMode { get { return this._outputStartMode; } set { this._outputStartMode = value; } } private System.DateTime? _outputStartTime; /// <summary> /// Optional. Gets or sets the output start time of the stream /// analytics job. /// </summary> public System.DateTime? OutputStartTime { get { return this._outputStartTime; } set { this._outputStartTime = value; } } private string _provisioningState; /// <summary> /// Optional. Gets the provisioning state of the stream analytics job. /// </summary> public string ProvisioningState { get { return this._provisioningState; } set { this._provisioningState = value; } } private Sku _sku; /// <summary> /// Optional. Gets or sets the Sku of the stream analytics job. /// </summary> public Sku Sku { get { return this._sku; } set { this._sku = value; } } private Transformation _transformation; /// <summary> /// Optional. Gets or sets the transformation definition, including the /// query and the streaming unit count. /// </summary> public Transformation Transformation { get { return this._transformation; } set { this._transformation = value; } } /// <summary> /// Initializes a new instance of the JobProperties class. /// </summary> public JobProperties() { this.Inputs = new LazyList<Input>(); this.Outputs = new LazyList<Output>(); } } }
// DeflaterEngine.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using ICSharpCode.SharpZipLib.Checksums; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// Strategies for deflater /// </summary> public enum DeflateStrategy { /// <summary> /// The default strategy /// </summary> Default = 0, /// <summary> /// This strategy will only allow longer string repetitions. It is /// useful for random data with a small character set. /// </summary> Filtered = 1, /// <summary> /// This strategy will not look for string repetitions at all. It /// only encodes with Huffman trees (which means, that more common /// characters get a smaller encoding. /// </summary> HuffmanOnly = 2 } // DEFLATE ALGORITHM: // // The uncompressed stream is inserted into the window array. When // the window array is full the first half is thrown away and the // second half is copied to the beginning. // // The head array is a hash table. Three characters build a hash value // and they the value points to the corresponding index in window of // the last string with this hash. The prev array implements a // linked list of matches with the same hash: prev[index & WMASK] points // to the previous index with the same hash. // /// <summary> /// Low level compression engine for deflate algorithm which uses a 32K sliding window /// with secondary compression from Huffman/Shannon-Fano codes. /// </summary> public class DeflaterEngine : DeflaterConstants { #region Constants const int TooFar = 4096; #endregion #region Constructors /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending"> /// Pending buffer to use /// </param>> public DeflaterEngine(DeflaterPending pending) { this.pending = pending; huffman = new DeflaterHuffman(pending); adler = new Adler32(); window = new byte[2 * WSIZE]; head = new short[HASH_SIZE]; prev = new short[WSIZE]; // We start at index 1, to avoid an implementation deficiency, that // we cannot build a repeat pattern at index 0. blockStart = strstart = 1; } #endregion /// <summary> /// Deflate drives actual compression of data /// </summary> /// <returns>Returns true if progress has been made.</returns> public bool Deflate(bool flush, bool finish) { bool progress; do { FillWindow(); bool canFlush = flush && (inputOff == inputEnd); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("window: [" + blockStart + "," + strstart + "," + lookahead + "], " + compressionFunction + "," + canFlush); } #endif switch (compressionFunction) { case DEFLATE_STORED: progress = DeflateStored(canFlush, finish); break; case DEFLATE_FAST: progress = DeflateFast(canFlush, finish); break; case DEFLATE_SLOW: progress = DeflateSlow(canFlush, finish); break; default: throw new InvalidOperationException("unknown compressionFunction"); } } while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made return progress; } /// <summary> /// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code> /// returns true /// </summary> /// <param name="buffer">The buffer containing input data.</param> /// <param name="offset">The offset of the first byte of data.</param> /// <param name="count">The number of bytes of data to use as input.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { throw new ArgumentOutOfRangeException("offset"); } if ( count < 0 ) { throw new ArgumentOutOfRangeException("count"); } if (inputOff < inputEnd) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; /* We want to throw an ArrayIndexOutOfBoundsException early. The * check is very tricky: it also handles integer wrap around. */ if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } inputBuf = buffer; inputOff = offset; inputEnd = end; } /// <summary> /// Return true if input is needed via <see cref="SetInput"> SetInput</see> /// </summary> public bool NeedsInput() { return (inputEnd == inputOff); } /// <summary> /// Set compression dictionary /// </summary> public void SetDictionary(byte[] buffer, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart != 1) ) { throw new InvalidOperationException("strstart not 1"); } #endif adler.Update(buffer, offset, length); if (length < MIN_MATCH) { return; } if (length > MAX_DIST) { offset += length - MAX_DIST; length = MAX_DIST; } System.Array.Copy(buffer, offset, window, strstart, length); UpdateHash(); --length; while (--length > 0) { InsertString(); strstart++; } strstart += 2; blockStart = strstart; } /// <summary> /// Reset internal state /// </summary> public void Reset() { huffman.Reset(); adler.Reset(); blockStart = strstart = 1; lookahead = 0; totalIn = 0; prevAvailable = false; matchLen = MIN_MATCH - 1; for (int i = 0; i < HASH_SIZE; i++) { head[i] = 0; } for (int i = 0; i < WSIZE; i++) { prev[i] = 0; } } /// <summary> /// Reset Adler checksum /// </summary> public void ResetAdler() { adler.Reset(); } /// <summary> /// Get current value of Adler checksum /// </summary> public int Adler { get { return unchecked((int)adler.Value); } } /// <summary> /// Total data processed /// </summary> public int TotalIn { get { return totalIn; } } /// <summary> /// Get/set the <see cref="DeflateStrategy">deflate strategy</see> /// </summary> public DeflateStrategy Strategy { get { return strategy; } set { strategy = value; } } /// <summary> /// Set the deflate level (0-9) /// </summary> /// <param name="level">The value to set the level to.</param> public void SetLevel(int level) { if ( (level < 0) || (level > 9) ) { throw new ArgumentOutOfRangeException("level"); } goodLength = DeflaterConstants.GOOD_LENGTH[level]; max_lazy = DeflaterConstants.MAX_LAZY[level]; niceLength = DeflaterConstants.NICE_LENGTH[level]; max_chain = DeflaterConstants.MAX_CHAIN[level]; if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("Change from " + compressionFunction + " to " + DeflaterConstants.COMPR_FUNC[level]); } #endif switch (compressionFunction) { case DEFLATE_STORED: if (strstart > blockStart) { huffman.FlushStoredBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } UpdateHash(); break; case DEFLATE_FAST: if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } break; case DEFLATE_SLOW: if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } prevAvailable = false; matchLen = MIN_MATCH - 1; break; } compressionFunction = COMPR_FUNC[level]; } } /// <summary> /// Fill the window /// </summary> public void FillWindow() { /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (strstart >= WSIZE + MAX_DIST) { SlideWindow(); } /* If there is not enough lookahead, but still some input left, * read in the input */ while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd) { int more = 2 * WSIZE - lookahead - strstart; if (more > inputEnd - inputOff) { more = inputEnd - inputOff; } System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more); adler.Update(inputBuf, inputOff, more); inputOff += more; totalIn += more; lookahead += more; } if (lookahead >= MIN_MATCH) { UpdateHash(); } } void UpdateHash() { /* if (DEBUGGING) { Console.WriteLine("updateHash: "+strstart); } */ ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1]; } /// <summary> /// Inserts the current string in the head hash and returns the previous /// value for this hash. /// </summary> /// <returns>The previous hash value</returns> int InsertString() { short match; int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK; #if DebugDeflation if (DeflaterConstants.DEBUGGING) { if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^ (window[strstart + 1] << HASH_SHIFT) ^ (window[strstart + 2])) & HASH_MASK)) { throw new SharpZipBaseException("hash inconsistent: " + hash + "/" +window[strstart] + "," +window[strstart + 1] + "," +window[strstart + 2] + "," + HASH_SHIFT); } } #endif prev[strstart & WMASK] = match = head[hash]; head[hash] = unchecked((short)strstart); ins_h = hash; return match & 0xffff; } void SlideWindow() { Array.Copy(window, WSIZE, window, 0, WSIZE); matchStart -= WSIZE; strstart -= WSIZE; blockStart -= WSIZE; // Slide the hash table (could be avoided with 32 bit values // at the expense of memory usage). for (int i = 0; i < HASH_SIZE; ++i) { int m = head[i] & 0xffff; head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } // Slide the prev table. for (int i = 0; i < WSIZE; i++) { int m = prev[i] & 0xffff; prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } } /// <summary> /// Find the best (longest) string in the window matching the /// string starting at strstart. /// /// Preconditions: /// <code> /// strstart + MAX_MATCH &lt;= window.length.</code> /// </summary> /// <param name="curMatch"></param> /// <returns>True if a match greater than the minimum length is found</returns> bool FindLongestMatch(int curMatch) { int chainLength = this.max_chain; int niceLength = this.niceLength; short[] prev = this.prev; int scan = this.strstart; int match; int best_end = this.strstart + matchLen; int best_len = Math.Max(matchLen, MIN_MATCH - 1); int limit = Math.Max(strstart - MAX_DIST, 0); int strend = strstart + MAX_MATCH - 1; byte scan_end1 = window[best_end - 1]; byte scan_end = window[best_end]; // Do not waste too much time if we already have a good match: if (best_len >= this.goodLength) { chainLength >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (niceLength > lookahead) { niceLength = lookahead; } #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD)) { throw new InvalidOperationException("need lookahead"); } #endif do { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) ) { throw new InvalidOperationException("no future"); } #endif if (window[curMatch + best_len] != scan_end || window[curMatch + best_len - 1] != scan_end1 || window[curMatch] != window[scan] || window[curMatch + 1] != window[scan + 1]) { continue; } match = curMatch + 2; scan += 2; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart + 258. */ while ( window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && (scan < strend)) { // Do nothing } if (scan > best_end) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (ins_h == 0) ) Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart)); #endif matchStart = curMatch; best_end = scan; best_len = scan - strstart; if (best_len >= niceLength) { break; } scan_end1 = window[best_end - 1]; scan_end = window[best_end]; } scan = strstart; } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0); matchLen = Math.Min(best_len, lookahead); return matchLen >= MIN_MATCH; } bool DeflateStored(bool flush, bool finish) { if (!flush && (lookahead == 0)) { return false; } strstart += lookahead; lookahead = 0; int storedLength = strstart - blockStart; if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full (blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window flush) { bool lastBlock = finish; if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) { storedLength = DeflaterConstants.MAX_BLOCK_SIZE; lastBlock = false; } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]"); } #endif huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock); blockStart += storedLength; return !lastBlock; } return true; } bool DeflateFast(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { // We are flushing everything huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int hashHead; if (lookahead >= MIN_MATCH && (hashHead = InsertString()) != 0 && strategy != DeflateStrategy.HuffmanOnly && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart + i] != window[matchStart + i]) { throw new SharpZipBaseException("Match failure"); } } } #endif bool full = huffman.TallyDist(strstart - matchStart, matchLen); lookahead -= matchLen; if (matchLen <= max_lazy && lookahead >= MIN_MATCH) { while (--matchLen > 0) { ++strstart; InsertString(); } ++strstart; } else { strstart += matchLen; if (lookahead >= MIN_MATCH - 1) { UpdateHash(); } } matchLen = MIN_MATCH - 1; if (!full) { continue; } } else { // No match found huffman.TallyLit(window[strstart] & 0xff); ++strstart; --lookahead; } if (huffman.IsFull()) { bool lastBlock = finish && (lookahead == 0); huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock); blockStart = strstart; return !lastBlock; } } return true; } bool DeflateSlow(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } prevAvailable = false; // We are flushing everything #if DebugDeflation if (DeflaterConstants.DEBUGGING && !flush) { throw new SharpZipBaseException("Not flushing, but no lookahead"); } #endif huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int prevMatch = matchStart; int prevLen = matchLen; if (lookahead >= MIN_MATCH) { int hashHead = InsertString(); if (strategy != DeflateStrategy.HuffmanOnly && hashHead != 0 && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen // Discard match if too small and too far away if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) { matchLen = MIN_MATCH - 1; } } } // previous match was better if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen) ) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart-1+i] != window[prevMatch + i]) throw new SharpZipBaseException(); } } #endif huffman.TallyDist(strstart - 1 - prevMatch, prevLen); prevLen -= 2; do { strstart++; lookahead--; if (lookahead >= MIN_MATCH) { InsertString(); } } while (--prevLen > 0); strstart ++; lookahead--; prevAvailable = false; matchLen = MIN_MATCH - 1; } else { if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } prevAvailable = true; strstart++; lookahead--; } if (huffman.IsFull()) { int len = strstart - blockStart; if (prevAvailable) { len--; } bool lastBlock = (finish && (lookahead == 0) && !prevAvailable); huffman.FlushBlock(window, blockStart, len, lastBlock); blockStart += len; return !lastBlock; } } return true; } #region Instance Fields // Hash index of string to be inserted int ins_h; /// <summary> /// Hashtable, hashing three characters to an index for window, so /// that window[index]..window[index+2] have this hash code. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] head; /// <summary> /// <code>prev[index &amp; WMASK]</code> points to the previous index that has the /// same hash code as the string starting at index. This way /// entries with the same hash code are in a linked list. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] prev; int matchStart; // Length of best match int matchLen; // Set if previous match exists bool prevAvailable; int blockStart; /// <summary> /// Points to the current character in the window. /// </summary> int strstart; /// <summary> /// lookahead is the number of characters starting at strstart in /// window that are valid. /// So window[strstart] until window[strstart+lookahead-1] are valid /// characters. /// </summary> int lookahead; /// <summary> /// This array contains the part of the uncompressed stream that /// is of relevance. The current character is indexed by strstart. /// </summary> byte[] window; DeflateStrategy strategy; int max_chain, max_lazy, niceLength, goodLength; /// <summary> /// The current compression function. /// </summary> int compressionFunction; /// <summary> /// The input data for compression. /// </summary> byte[] inputBuf; /// <summary> /// The total bytes of input read. /// </summary> int totalIn; /// <summary> /// The offset into inputBuf, where input data starts. /// </summary> int inputOff; /// <summary> /// The end offset of the input data. /// </summary> int inputEnd; DeflaterPending pending; DeflaterHuffman huffman; /// <summary> /// The adler checksum /// </summary> Adler32 adler; #endregion } }
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 RestfullService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F10_City (editable child object).<br/> /// This is a generated base class of <see cref="F10_City"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="F11_CityRoadObjects"/> of type <see cref="F11_CityRoadColl"/> (1:M relation to <see cref="F12_CityRoad"/>)<br/> /// This class is an item of <see cref="F09_CityColl"/> collection. /// </remarks> [Serializable] public partial class F10_City : BusinessBase<F10_City> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Region_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_ID"/> property. /// </summary> public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID"); /// <summary> /// Gets the Cities ID. /// </summary> /// <value>The Cities ID.</value> public int City_ID { get { return GetProperty(City_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="City_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name"); /// <summary> /// Gets or sets the Cities Name. /// </summary> /// <value>The Cities Name.</value> public string City_Name { get { return GetProperty(City_NameProperty); } set { SetProperty(City_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F11_City_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<F11_City_Child> F11_City_SingleObjectProperty = RegisterProperty<F11_City_Child>(p => p.F11_City_SingleObject, "F11 City Single Object", RelationshipTypes.Child); /// <summary> /// Gets the F11 City Single Object ("parent load" child property). /// </summary> /// <value>The F11 City Single Object.</value> public F11_City_Child F11_City_SingleObject { get { return GetProperty(F11_City_SingleObjectProperty); } private set { LoadProperty(F11_City_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F11_City_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<F11_City_ReChild> F11_City_ASingleObjectProperty = RegisterProperty<F11_City_ReChild>(p => p.F11_City_ASingleObject, "F11 City ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the F11 City ASingle Object ("parent load" child property). /// </summary> /// <value>The F11 City ASingle Object.</value> public F11_City_ReChild F11_City_ASingleObject { get { return GetProperty(F11_City_ASingleObjectProperty); } private set { LoadProperty(F11_City_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F11_CityRoadObjects"/> property. /// </summary> public static readonly PropertyInfo<F11_CityRoadColl> F11_CityRoadObjectsProperty = RegisterProperty<F11_CityRoadColl>(p => p.F11_CityRoadObjects, "F11 CityRoad Objects", RelationshipTypes.Child); /// <summary> /// Gets the F11 City Road Objects ("parent load" child property). /// </summary> /// <value>The F11 City Road Objects.</value> public F11_CityRoadColl F11_CityRoadObjects { get { return GetProperty(F11_CityRoadObjectsProperty); } private set { LoadProperty(F11_CityRoadObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F10_City"/> object. /// </summary> /// <returns>A reference to the created <see cref="F10_City"/> object.</returns> internal static F10_City NewF10_City() { return DataPortal.CreateChild<F10_City>(); } /// <summary> /// Factory method. Loads a <see cref="F10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F10_City"/> object.</returns> internal static F10_City GetF10_City(SafeDataReader dr) { F10_City obj = new F10_City(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(F11_CityRoadObjectsProperty, F11_CityRoadColl.NewF11_CityRoadColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F10_City"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F10_City() { // 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="F10_City"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(F11_City_SingleObjectProperty, DataPortal.CreateChild<F11_City_Child>()); LoadProperty(F11_City_ASingleObjectProperty, DataPortal.CreateChild<F11_City_ReChild>()); LoadProperty(F11_CityRoadObjectsProperty, DataPortal.CreateChild<F11_CityRoadColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_IDProperty, dr.GetInt32("City_ID")); LoadProperty(City_NameProperty, dr.GetString("City_Name")); // parent properties parent_Region_ID = dr.GetInt32("Parent_Region_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="F11_City_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F11_City_Child child) { LoadProperty(F11_City_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="F11_City_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F11_City_ReChild child) { LoadProperty(F11_City_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="F10_City"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F08_Region parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IF10_CityDal>(); using (BypassPropertyChecks) { int city_ID = -1; dal.Insert( parent.Region_ID, out city_ID, City_Name ); LoadProperty(City_IDProperty, city_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="F10_City"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IF10_CityDal>(); using (BypassPropertyChecks) { dal.Update( City_ID, City_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="F10_City"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IF10_CityDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(City_IDProperty)); } 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 } }
using BotBits.Shop; // ReSharper disable MemberHidesStaticFromOuterClass namespace BotBits { public static class Foreground { public enum Id : ushort { } public const Id Empty = 0; public static class Gravity { public const Id Left = (Id)1, Up = (Id)2, Right = (Id)3, Dot = (Id)4, InvisibleLeft = (Id)411, InvisibleUp = (Id)412, InvisibleRight = (Id)413, InvisibleDot = (Id)414, SlowDot = (Id)459, InvisibleSlowDot = (Id)460; } public static class Key { public const Id Red = (Id)6, Green = (Id)7, Blue = (Id)8, Cyan = (Id)408, Magenta = (Id)409, Yellow = (Id)410; } public static class Basic { public const Id Gray = (Id)9, Blue = (Id)10, Purple = (Id)11, Red = (Id)12, Orange = (Id)1018, Yellow = (Id)13, Green = (Id)14, Cyan = (Id)15, Black = (Id)182, White = (Id)1088; } public static class Brick { public const Id Gray = (Id)1022, Orange = (Id)16, Blue = (Id)1023, Teal = (Id)17, Purple = (Id)18, Green = (Id)19, Red = (Id)20, Tan = (Id)21, Black = (Id)1024, White = (Id)1090; } public static class Generic { public const Id StripedYellow = (Id)22, Yellow = (Id)1057, Face = (Id)32, Black = (Id)33, StripedBlack = (Id)1058; } public static class Door { public const Id Red = (Id)23, Green = (Id)24, Blue = (Id)25, Cyan = (Id)1005, Magenta = (Id)1006, Yellow = (Id)1007; } public static class Gate { public const Id Red = (Id)26, Green = (Id)27, Blue = (Id)28, Cyan = (Id)1008, Magenta = (Id)1009, Yellow = (Id)1010; } public static class Gold { [Pack("-", GoldMembershipItem = true)] public const Id Door = (Id)200, Gate = (Id)201, Basic = (Id)1065, Brick = (Id)1066, Panel = (Id)1067, Ornate = (Id)1068, OneWay = (Id)1069; } public static class Team { [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Effect = (Id)423; [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Door = (Id)1027; [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Gate = (Id)1028; } public static class Death { [Pack("brickdeathdoor", ForegroundType = ForegroundType.Goal)] public const Id Door = (Id)1011; [Pack("brickdeathdoor", ForegroundType = ForegroundType.Goal)] public const Id Gate = (Id)1012; } public static class Metal { public const Id White = (Id)29, Red = (Id)30, Yellow = (Id)31; } public static class Grass { public const Id Left = (Id)34, Middle = (Id)35, Right = (Id)36; } public static class Beta { [Pack("pro")] public const Id Pink = (Id)37, Green = (Id)38, Cyan = (Id)1019, Blue = (Id)39, Red = (Id)40, Orange = (Id)1020, Yellow = (Id)41, Gray = (Id)42, Black = (Id)1021, White = (Id)1089; } public static class Factory { public const Id TanCross = (Id)45, Planks = (Id)46, Sandpaper = (Id)47, BrownCross = (Id)48, Fishscales = (Id)49; } public static class Secret { public const Id Unpassable = (Id)50, InvisibleUnpassable = (Id)136, Passable = (Id)243, Black = (Id)44; } public static class Glass { public const Id Red = (Id)51, Pink = (Id)52, Indigo = (Id)53, Blue = (Id)54, Cyan = (Id)55, Green = (Id)56, Yellow = (Id)57, Orange = (Id)58; } public static class Summer2011 { [Pack("bricksummer2012")] public const Id Sand = (Id)59, Sunshade = (Id)228, RightCornerSand = (Id)229, LeftCornerSand = (Id)230, Rock = (Id)231; } public static class Candy { [Pack("brickcandy")] public const Id Pink = (Id)60, OneWayPink = (Id)61, OneWayRed = (Id)62, OneWayCyan = (Id)63, OneWayGreen = (Id)64, CandyCane = (Id)65, CandyCorn = (Id)66, Chocolate = (Id)67, ToppingSmall = (Id)227, ToppingBig = (Id)431, PuddingRed = (Id)432, PuddingGreen = (Id)433, PuddingPurple = (Id)434; } public static class Halloween2011 { [Pack("brickhw2011")] public const Id Blood = (Id)68, FullBrick = (Id)69, Tombstone = (Id)224, LeftCornerWeb = (Id)225, RightCornerWeb = (Id)226; } public static class Mineral { [Pack("brickminiral")] public const Id Red = (Id)70, Pink = (Id)71, Blue = (Id)72, Cyan = (Id)73, Green = (Id)74, Yellow = (Id)75, Orange = (Id)76; } public static class Music { [Pack("bricknode", ForegroundType = ForegroundType.Note)] public const Id Piano = (Id)77; [Pack("brickdrums", ForegroundType = ForegroundType.Note)] public const Id Drum = (Id)83; } public static class Christmas2011 { [Pack("brickxmas2011")] public const Id YellowBox = (Id)78, WhiteBox = (Id)79, RedBox = (Id)80, BlueBox = (Id)81, GreenBox = (Id)82, SphereBlue = (Id)218, SphereGreen = (Id)219, SphereRed = (Id)220, Wreath = (Id)221, Star = (Id)222; } public static class SciFi { [Pack("brickscifi")] public const Id Red = (Id)84, Blue = (Id)85, Gray = (Id)86, White = (Id)87, Brown = (Id)88, OneWayRed = (Id)89, OneWayBlue = (Id)90, OneWayGreen = (Id)91, OneWayYellow = (Id)1051; [Pack("brickscifi", ForegroundType = ForegroundType.Morphable)] public const Id BlueSlope = (Id)375, BlueStraight = (Id)376, GreenSlope = (Id)379, GreenStraight = (Id)380, YellowSlope = (Id)377, YellowStraight = (Id)378, RedSlope = (Id)438, RedStraight = (Id)439; } public static class Prison { [Pack("brickprison")] public const Id Wall = (Id)92, Bars = (Id)261; } public static class Pirate { [Pack("brickpirate")] public const Id Planks = (Id)93, Chest = (Id)94, Canoncover = (Id)271, Skull = (Id)272, Canon = (Id)435, Window = (Id)436, OneWay = (Id)154; } public static class Stone { [Pack("brickstone")] public const Id Gray = (Id)95, Teal = (Id)1044, Brown = (Id)1045, Blue = (Id)1046; } public static class Dojo { [Pack("brickninja")] public const Id White = (Id)96, Gray = (Id)97, BrightWindow = (Id)278, DarkWindow = (Id)281, LadderShape = (Id)282, AntennaShape = (Id)283, YinYang = (Id)284; [Pack("brickninja", ForegroundType = ForegroundType.Morphable)] public const Id LeftRooftop = (Id)276, RightRooftop = (Id)277, LeftDarkRooftop = (Id)279, RightDarkRooftop = (Id)280; } public static class Ladder { [Pack("brickmedieval")] public const Id Chain = (Id)118; [Pack("brickninja")] public const Id Wood = (Id)120; public const Id VineVertical = (Id)98, VineHorizontal = (Id)99; [Pack("brickcowboy")] public const Id Rope = (Id)424; } public static class Coin { public const Id Gold = (Id)100, Blue = (Id)101; [Pack("-", ForegroundType = ForegroundType.Goal)] public const Id GoldDoor = (Id)43, GoldGate = (Id)165; [Pack("-", ForegroundType = ForegroundType.Goal)] public const Id BlueDoor = (Id)213, BlueGate = (Id)214; } public static class Switch { [Pack("brickswitchpurple", ForegroundType = ForegroundType.Goal)] public const Id Purple = (Id)113, PurpleDoor = (Id)184, PurpleGate = (Id)185; [Pack("brickswitchorange", ForegroundType = ForegroundType.Goal)] public const Id Orange = (Id)467, OrangeDoor = (Id)1079, OrangeGate = (Id)1080; } public static class Boost { [Pack("brickboost")] public const Id Left = (Id)114, Right = (Id)115, Up = (Id)116, Down = (Id)117; } public static class Water { public const Id Waves = (Id)300; } public static class Tool { public const Id Crown = (Id)5, Spawnpoint = (Id)255; public const Id Trophy = (Id)121; public const Id Checkpoint = (Id)360; public const Id Resetpoint = (Id)466; } public static class WildWest { [Pack("brickcowboy")] public const Id BrownLit = (Id)122, RedLit = (Id)123, BlueLit = (Id)124, BrownDark = (Id)125, RedDark = (Id)126, BlueDark = (Id)127, PoleLit = (Id)285, PoleDark = (Id)286, DoorBrownLeft = (Id)287, DoorBrownRight = (Id)288, DoorRedLeft = (Id)289, DoorRedRight = (Id)290, DoorBlueLeft = (Id)291, DoorBlueRight = (Id)292, Window = (Id)293, TableBrownLit = (Id)294, TableBrownDark = (Id)295, TableRedLit = (Id)296, TableRedDark = (Id)297, TableBlueLit = (Id)298, TableBlueDark = (Id)299; } public static class Plastic { [Pack("brickplastic")] public const Id LightGreen = (Id)128, Red = (Id)129, Yellow = (Id)130, Cyan = (Id)131, Blue = (Id)132, Pink = (Id)133, Green = (Id)134, Orange = (Id)135; } public static class Sand { [Pack("bricksand")] public const Id White = (Id)137, Gray = (Id)138, Yellow = (Id)139, Orange = (Id)140, Tan = (Id)141, Brown = (Id)142, DuneWhite = (Id)301, DuneGray = (Id)302, DuneYellow = (Id)303, DuneOrange = (Id)304, DuneTan = (Id)305, DuneBrown = (Id)306; } public static class Cloud { public const Id White = (Id)143, Bottom = (Id)311, Top = (Id)312, Right = (Id)313, Left = (Id)314, BottomLeftCorner = (Id)315, BottomRightCorner = (Id)316, TopRightCorner = (Id)317, TopLeftCorner = (Id)318; } public static class Industrial { [Pack("brickindustrial")] public const Id Iron = (Id)144, Wires = (Id)145, OneWay = (Id)146, CrossSupport = (Id)147, Elevator = (Id)148, Support = (Id)149, LeftConveyor = (Id)150, SupportedMiddleConveyor = (Id)151, MiddleConveyor = (Id)152, RightConveyor = (Id)153, SignFire = (Id)319, SignSkull = (Id)320, SignLightning = (Id)321, SignCross = (Id)322, HorizontalLine = (Id)323, VerticalLine = (Id)324; } public static class Timed { [Pack("bricktimeddoor")] public const Id Door = (Id)156; [Pack("bricktimeddoor")] public const Id Gate = (Id)157; } public static class Medieval { [Pack("brickmedieval")] public const Id CastleOneWay = (Id)158, CastleWall = (Id)159, CastleWindow = (Id)160, Anvil = (Id)162, Barrel = (Id)163, CastleSupport = (Id)325, Tombstone = (Id)326, Shield = (Id)330, ClosedDoor = (Id)437; [Pack("brickmedieval", ForegroundType = ForegroundType.Morphable)] public const Id Timber = (Id)440, Axe = (Id)275, Sword = (Id)329, Circle = (Id)273, CoatOfArms = (Id)328, Banner = (Id)327; } public static class Pipe { public const Id Left = (Id)166, Horizontal = (Id)167, Right = (Id)168, Up = (Id)169, Vertical = (Id)170, Down = (Id)171; } public static class OuterSpace { public const Id White = (Id)172, Blue = (Id)173, Green = (Id)174, Red = (Id)175, Dust = (Id)176, SilverTexture = (Id)1029, GreenSign = (Id)332, RedLight = (Id)333, BlueLight = (Id)334, Computer = (Id)335, BigStar = (Id)428, MediumStar = (Id)429, LittleStar = (Id)430, Stone = (Id)331; } public static class Desert { // TODO find better names for Patterns public const Id Pattern1 = (Id)177, Pattern2 = (Id)178, Pattern3 = (Id)179, Pattern4 = (Id)180, Pattern5 = (Id)181, Rock = (Id)336, Cactus = (Id)425, Shrub = (Id)426, Tree = (Id)427; } public static class Checker { public const Id Gray = (Id)186, DarkBlue = (Id)187, Purple = (Id)188, Red = (Id)189, Yellow = (Id)190, Green = (Id)191, LightBlue = (Id)192, Orange = (Id)1025, Black = (Id)1026, White = (Id)1091; } public static class Jungle { public const Id Tiki = (Id)193, OneWay = (Id)194, Gray = (Id)195, Red = (Id)196, Blue = (Id)197, Yellow = (Id)198, Vase = (Id)199, Undergrowth = (Id)357, Log = (Id)358, Idol = (Id)359; } public static class Lava { [Pack("bricklava")] public const Id Yellow = (Id)202, Orange = (Id)203, Red = (Id)204, Waves = (Id)415; } public static class Marble { [Pack("bricksparta")] public const Id Gray = (Id)208, Green = (Id)209, Red = (Id)210, OneWay = (Id)211, PillarTop = (Id)382, PillarMiddle = (Id)383, PillarBottom = (Id)384; } public static class Farm { [Pack("brickfarm")] public const Id Hay = (Id)212, Crop = (Id)386, Plants = (Id)387, FenceLeftEnded = (Id)388, FenceRightEnded = (Id)389; } public static class Autumn2014 { [Pack("brickautumn2014")] public const Id RightCornerLeaves = (Id)390, LeftCornerLeaves = (Id)391, LeftGrass = (Id)392, MiddleGrass = (Id)393, RightGrass = (Id)394, Acorn = (Id)395, Pumpkin = (Id)396; } public static class Christmas2014 { [Pack("brickchristmas2014")] public const Id Ice = (Id)215, OneWay = (Id)216, LeftSnow = (Id)398, MiddleSnow = (Id)399, RightSnow = (Id)400, CandyCane = (Id)401, Wreath = (Id)402, Stocking = (Id)403, Bow = (Id)404; } public static class Zombie { [Pack("brickeffectzombie", ForegroundType = ForegroundType.ToggleGoal)] public const Id Effect = (Id)422; [Pack("brickzombiedoor")] public const Id Door = (Id)207; [Pack("brickzombiedoor")] public const Id Gate = (Id)206; } public static class Hologram { [Pack("brickhologram")] public const Id Block = (Id)397; } public static class Prize { [Pack("brickhwtrophy")] public const Id HalloweenTrophy = (Id)223; [Pack("brickspringtrophybronze")] public const Id BronzeSpringTrophy = (Id)478; [Pack("brickspringtrophysilver")] public const Id SilverSpringTrophy = (Id)479; [Pack("brickspringtrophygold")] public const Id GoldSpringTrophy = (Id)480; } public static class Spring2011 { [Pack("brickspring2011")] public const Id LeftGrass = (Id)233, MiddleGrass = (Id)234, RightGrass = (Id)235, LeftBush = (Id)236, MiddleBush = (Id)237, RightBush = (Id)238, Flower = (Id)239, Shrub = (Id)240; } public static class Diamond { [Pack("brickdiamond")] public const Id Block = (Id)241; } public static class Portal { [Pack("brickportal", ForegroundType = ForegroundType.Portal)] public const Id Normal = (Id)242; [Pack("brickinvisibleportal", ForegroundType = ForegroundType.Portal)] public const Id Invisible = (Id)381; [Pack("brickworldportal", ForegroundType = ForegroundType.WorldPortal)] public const Id World = (Id)374; } public static class NewYear2010 { [Pack("mixednewyear2010")] public const Id Purple = (Id)244, Yellow = (Id)245, Blue = (Id)246, Red = (Id)247, Green = (Id)248; } public static class Christmas2010 { [Pack("brickchristmas2010")] public const Id RightCornerSnow = (Id)249, LeftCornerSnow = (Id)250, Tree = (Id)251, DecoratedTree = (Id)252, SnowyFence = (Id)253, Fence = (Id)254; } public static class Easter2012 { [Pack("brickeaster2012")] public const Id BlueEgg = (Id)256, PinkEgg = (Id)257, YellowEgg = (Id)258, RedEgg = (Id)259, GreenEgg = (Id)260; } public static class Window { public const Id Clear = (Id)262, Green = (Id)263, Teal = (Id)264, Blue = (Id)265, Purple = (Id)266, Pink = (Id)267, Red = (Id)268, Orange = (Id)269, Yellow = (Id)270; } public static class Summer2012 { [Pack("bricksummer2012")] public const Id Ball = (Id)307, Bucket = (Id)308, Grubber = (Id)309, Cocktail = (Id)310; } public static class Cake { [Pack("brickcake")] public const Id Block = (Id)337; } public static class Monster { [Pack("brickmonster", ForegroundType = ForegroundType.Morphable)] public const Id BigTooth = (Id)338, SmallTooth = (Id)339, TripleTooth = (Id)340; [Pack("brickmonster")] public const Id PurpleEye = (Id)274, OrangeEye = (Id)341, BlueEye = (Id)342; } public static class Fog { [Pack("brickfog")] public const Id Full = (Id)343, Bottom = (Id)344, Top = (Id)345, Right = (Id)346, Left = (Id)347, BottomLeftCorner = (Id)348, BottomRightCorner = (Id)349, TopRightCorner = (Id)350, TopLeftCorner = (Id)351; } public static class Halloween2012 { [Pack("brickhw2012")] public const Id TeslaCap = (Id)352, TeslaCoil = (Id)353, WiresVertical = (Id)354, WiresHorizontal = (Id)355, Electricity = (Id)356; } public static class Hazard { [Pack("brickspike", ForegroundType = ForegroundType.Morphable)] public const Id Spike = (Id)361; [Pack("brickfire")] public const Id Fire = (Id)368; } public static class Swamp { [Pack("brickswamp")] public const Id MudBubbles = (Id)370, Grass = (Id)371, Log = (Id)372, Radioactive = (Id)373; } public static class Christmas2012 { [Pack("brickxmas2012")] public const Id BlueVertical = (Id)362, BlueHorizontal = (Id)363, BlueCross = (Id)364, RedVertical = (Id)365, RedHorizontal = (Id)366, RedCross = (Id)367; } public static class Sign { [Pack("bricksign", ForegroundType = ForegroundType.Sign)] public const Id Block = (Id)385; } public static class Admin { [Pack("-", AdminOnly = true, ForegroundType = ForegroundType.Label)] public const Id Text = (Id)1000; } public static class OneWay { [Pack("brickoneway", ForegroundType = ForegroundType.Morphable)] public const Id Cyan = (Id)1001, Orange = (Id)1002, Yellow = (Id)1003, Pink = (Id)1004, Gray = (Id)1052, Blue = (Id)1053, Red = (Id)1054, Green = (Id)1055, Black = (Id)1056, White = (Id)1092; } public static class Valentines2015 { [Pack("brickvalentines2015")] public const Id RedHeart = (Id)405, PurpleHeart = (Id)406, PinkHeart = (Id)407; } public static class Magic { [Pack("brickmagic")] public const Id Green = (Id)1013; [Pack("brickmagic2")] public const Id Purple = (Id)1014; [Pack("brickmagic3")] public const Id Orange = (Id)1015; [Pack("brickmagic4")] public const Id Blue = (Id)1016; [Pack("brickmagic5")] public const Id Red = (Id)1017; } public static class Effect { [Pack("brickeffectjump", ForegroundType = ForegroundType.Toggle)] public const Id Jump = (Id)417; [Pack("brickeffectfly", ForegroundType = ForegroundType.Toggle)] public const Id Fly = (Id)418; [Pack("brickeffectspeed", ForegroundType = ForegroundType.Toggle)] public const Id Speed = (Id)419; [Pack("brickeffectprotection", ForegroundType = ForegroundType.Toggle)] public const Id Protection = (Id)420; [Pack("brickeffectcurse", ForegroundType = ForegroundType.ToggleGoal)] public const Id Curse = (Id)421; [Pack("brickeffectlowgravity", ForegroundType = ForegroundType.Toggle)] public const Id LowGravity = (Id)453; [Pack("brickeffectmultijump", ForegroundType = ForegroundType.Morphable)] public const Id MultiJump = (Id)461; } public static class Liquid { [Pack("brickswamp")] public const Id Swamp = (Id)369; public const Id Water = (Id)119; [Pack("bricklava")] public const Id Lava = (Id)416; } public static class Summer2015 { [Pack("bricksummer2015")] public const Id Lifesaver = (Id)441, Anchor = (Id)442, RopeLeftEnded = (Id)443, RopeRightEnded = (Id)444, PalmTree = (Id)445; } public static class Environment { public const Id Tree = (Id)1030, Grass = (Id)1031, Bamboo = (Id)1032, Rock = (Id)1033, Lava = (Id)1034; } public static class Domestic { [Pack("brickdomestic")] public const Id Tile = (Id)1035, Wood = (Id)1036, CarpetRed = (Id)1037, CarpetBlue = (Id)1038, CarpetGreen = (Id)1039, WoodenPanel = (Id)1040, Lamp = (Id)446; [Pack("brickdomestic", ForegroundType = ForegroundType.Morphable)] public const Id BeigeHalfBlock = (Id)1041, WoodHalfBlock = (Id)1042, WhiteHalfBlock = (Id)1043, LightBulb = (Id)447, Pipe = (Id)448, Painting = (Id)449, Vase = (Id)450, Television = (Id)451, Window = (Id)452; } public static class Halloween2015 { [Pack("brickhalloween2015")] public const Id MossyBrick = (Id)1047, Siding = (Id)1048, Rooftop = (Id)1049, OneWay = (Id)1050, DeadShrub = (Id)454, IronFence = (Id)455; [Pack("brickhalloween2015", ForegroundType = ForegroundType.Morphable)] public const Id Window = (Id)456, WoodHalfBlock = (Id)457, Lantern = (Id)458; } public static class Ice { [Pack("brickice2")] public const Id Block = (Id)1064; } public static class Arctic { public const Id Ice = (Id)1059, Snow = (Id)1060, SnowyLeft = (Id)1061, SnowyMiddle = (Id)1062, SnowyRight = (Id)1063; } public static class NewYear2015 { [Pack("bricknewyear2015")] public const Id WineGlass = (Id)462, Bottle = (Id)463; [Pack("bricknewyear2015", ForegroundType = ForegroundType.Morphable)] public const Id Balloon = (Id)464, Streamer = (Id)465; } public static class Fairytale { [Pack("brickfairytale")] public const Id Pebbles = (Id)1070, Tree = (Id)1071, Moss = (Id)1072, Cloud = (Id)1073, MushroomBlock = (Id)1074, Vine = (Id)468, Mushroom = (Id)469, WaterDrop = (Id)470; [Pack("brickfairytale", ForegroundType = ForegroundType.Morphable)] public const Id OneWayOrange = (Id)1075, OneWayGreen = (Id)1076, OneWayBlue = (Id)1077, OneWayPink = (Id)1078, Flowers = (Id)471; } public static class Spring2016 { [Pack("brickspring2016")] public const Id Dirt = (Id)1081, Hedge = (Id)1082, LeftSlope = (Id)473, RightSlope = (Id)474; [Pack("brickspring2016", ForegroundType = ForegroundType.Morphable)] public const Id Daisy = (Id)475, Tulip = (Id)476, Daffodil = (Id)477; } public static class Summer2016 { [Pack("bricksummer2016")] public const Id Beige = (Id)1083, Purple = (Id)1084, Yellow = (Id)1085, Teal = (Id)1086, OneWay = (Id)1087; [Pack("bricksummer2016", ForegroundType = ForegroundType.Morphable)] public const Id Flags = (Id)481, Awning = (Id)482, IceCream = (Id)483; } public static class SummerTrophy { [Pack("bricksummertrophybronze")] public const Id Bronze = (Id)484; [Pack("bricksummertrophysilver")] public const Id Silver = (Id)485; [Pack("bricksummertrophygold")] public const Id Gold = (Id)486; } public static class Restaurant { [Pack("brickrestaurant")] public const Id Hamburger = (Id)487, Hotdog = (Id)488, Sandwich = (Id)489, Soda = (Id)490, Fries = (Id)491; [Pack("brickrestaurant", ForegroundType = ForegroundType.Morphable)] public const Id Glass = (Id)492, Plate = (Id)493, Bowl = (Id)494; } public static class Mine { public const Id Rocks = (Id)1093, Stalagmite = (Id)495, Stalagtite = (Id)496, Torch = (Id)498; [Pack("brickmine", ForegroundType = ForegroundType.Morphable)] public const Id Crystal = (Id)497; } public static class Halloween2016 { [Pack("brickhalloween2016")] public const Id Grass = (Id)1501; [Pack("brickhalloween2016", ForegroundType = ForegroundType.Morphable)] public const Id Branch = (Id)499, Pumpkin = (Id)1500, Eyes = (Id)1502; } public static class Construction { public const Id Plywood = (Id)1096, Gravel = (Id)1097, Cement = (Id)1098, BeamHorizontal = (Id)1099, BeamVertical = (Id)1100, Sawhorse = (Id)1503, Cone = (Id)1504, Sign = (Id)1505; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { /// <summary> /// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it /// easier to split the class into abstract and implementation classes if desired.) /// </summary> internal sealed partial class X509Pal : IX509Pal { public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { unsafe { ushort keyUsagesAsShort = (ushort)keyUsages; CRYPT_BIT_BLOB blob = new CRYPT_BIT_BLOB() { cbData = 2, pbData = (byte*)&keyUsagesAsShort, cUnusedBits = 0, }; return Interop.crypt32.EncodeObject(CryptDecodeObjectStructType.X509_KEY_USAGE, &blob); } } public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { unsafe { uint keyUsagesAsUint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_KEY_USAGE, delegate (void* pvDecoded) { CRYPT_BIT_BLOB* pBlob = (CRYPT_BIT_BLOB*)pvDecoded; keyUsagesAsUint = 0; if (pBlob->pbData != null) { keyUsagesAsUint = *(uint*)(pBlob->pbData); } } ); keyUsages = (X509KeyUsageFlags)keyUsagesAsUint; } } public byte[] EncodeX509BasicConstraints2Extension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { unsafe { CERT_BASIC_CONSTRAINTS2_INFO constraintsInfo = new CERT_BASIC_CONSTRAINTS2_INFO() { fCA = certificateAuthority ? 1 : 0, fPathLenConstraint = hasPathLengthConstraint ? 1 : 0, dwPathLenConstraint = pathLengthConstraint, }; return Interop.crypt32.EncodeObject(Oids.BasicConstraints2, &constraintsInfo); } } public void DecodeX509BasicConstraintsExtension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS_INFO* pBasicConstraints = (CERT_BASIC_CONSTRAINTS_INFO*)pvDecoded; localCertificateAuthority = (pBasicConstraints->SubjectType.pbData[0] & CERT_BASIC_CONSTRAINTS_INFO.CERT_CA_SUBJECT_FLAG) != 0; localHasPathLengthConstraint = pBasicConstraints->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public void DecodeX509BasicConstraints2Extension(byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { unsafe { bool localCertificateAuthority = false; bool localHasPathLengthConstraint = false; int localPathLengthConstraint = 0; encoded.DecodeObject( CryptDecodeObjectStructType.X509_BASIC_CONSTRAINTS2, delegate (void* pvDecoded) { CERT_BASIC_CONSTRAINTS2_INFO* pBasicConstraints2 = (CERT_BASIC_CONSTRAINTS2_INFO*)pvDecoded; localCertificateAuthority = pBasicConstraints2->fCA != 0; localHasPathLengthConstraint = pBasicConstraints2->fPathLenConstraint != 0; localPathLengthConstraint = pBasicConstraints2->dwPathLenConstraint; } ); certificateAuthority = localCertificateAuthority; hasPathLengthConstraint = localHasPathLengthConstraint; pathLengthConstraint = localPathLengthConstraint; } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { int numUsages; using (SafeHandle usagesSafeHandle = usages.ToLpstrArray(out numUsages)) { unsafe { CERT_ENHKEY_USAGE enhKeyUsage = new CERT_ENHKEY_USAGE() { cUsageIdentifier = numUsages, rgpszUsageIdentifier = (IntPtr*)(usagesSafeHandle.DangerousGetHandle()), }; return Interop.crypt32.EncodeObject(Oids.EnhancedKeyUsage, &enhKeyUsage); } } } public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection localUsages = new OidCollection(); unsafe { encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, delegate (void* pvDecoded) { CERT_ENHKEY_USAGE* pEnhKeyUsage = (CERT_ENHKEY_USAGE*)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; String oidValue = Marshal.PtrToStringAnsi(oidValuePointer); Oid oid = new Oid(oidValue); localUsages.Add(oid); } } ); } usages = localUsages; return; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { unsafe { fixed (byte* pSubkectKeyIdentifier = subjectKeyIdentifier) { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(subjectKeyIdentifier.Length, pSubkectKeyIdentifier); return Interop.crypt32.EncodeObject(Oids.SubjectKeyIdentifier, &blob); } } } public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { unsafe { byte[] localSubjectKeyIdentifier = null; encoded.DecodeObject( Oids.SubjectKeyIdentifier, delegate (void* pvDecoded) { CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded; localSubjectKeyIdentifier = pBlob->ToByteArray(); } ); subjectKeyIdentifier = localSubjectKeyIdentifier; } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { unsafe { fixed (byte* pszOidValue = key.Oid.ValueAsAscii()) { byte[] encodedParameters = key.EncodedParameters.RawData; fixed (byte* pEncodedParameters = encodedParameters) { byte[] encodedKeyValue = key.EncodedKeyValue.RawData; fixed (byte* pEncodedKeyValue = encodedKeyValue) { CERT_PUBLIC_KEY_INFO publicKeyInfo = new CERT_PUBLIC_KEY_INFO() { Algorithm = new CRYPT_ALGORITHM_IDENTIFIER() { pszObjId = new IntPtr(pszOidValue), Parameters = new CRYPTOAPI_BLOB(encodedParameters.Length, pEncodedParameters), }, PublicKey = new CRYPT_BIT_BLOB() { cbData = encodedKeyValue.Length, pbData = pEncodedKeyValue, cUnusedBits = 0, }, }; int cb = 20; byte[] buffer = new byte[cb]; if (!Interop.crypt32.CryptHashPublicKeyInfo(IntPtr.Zero, AlgId.CALG_SHA1, 0, CertEncodingType.All, ref publicKeyInfo, buffer, ref cb)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (cb < buffer.Length) { byte[] newBuffer = new byte[cb]; Array.Copy(buffer, newBuffer, cb); buffer = newBuffer; } return buffer; } } } } } } }
// 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.Threading.Tasks; using System.IO; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Http.Headers; using System.Diagnostics.Contracts; using System.Text; namespace System.Net.Http { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Represents a multipart/* content. Even if a collection of HttpContent is stored, " + "suffix Collection is not appropriate.")] public class MultipartContent : HttpContent, IEnumerable<HttpContent> { #region Fields private const string crlf = "\r\n"; private List<HttpContent> _nestedContent; private string _boundary; // Temp context for serialization. private int _nextContentIndex; private Stream _outputStream; private TaskCompletionSource<Object> _tcs; #endregion Fields #region Construction public MultipartContent() : this("mixed", GetDefaultBoundary()) { } public MultipartContent(string subtype) : this(subtype, GetDefaultBoundary()) { } public MultipartContent(string subtype, string boundary) { if (string.IsNullOrWhiteSpace(subtype)) { throw new ArgumentException(SR.net_http_argument_empty_string, "subtype"); } Contract.EndContractBlock(); ValidateBoundary(boundary); _boundary = boundary; string quotedBoundary = boundary; if (!quotedBoundary.StartsWith("\"", StringComparison.Ordinal)) { quotedBoundary = "\"" + quotedBoundary + "\""; } MediaTypeHeaderValue contentType = new MediaTypeHeaderValue("multipart/" + subtype); contentType.Parameters.Add(new NameValueHeaderValue("boundary", quotedBoundary)); Headers.ContentType = contentType; _nestedContent = new List<HttpContent>(); } private static void ValidateBoundary(string boundary) { // NameValueHeaderValue is too restrictive for boundary. // Instead validate it ourselves and then quote it. if (string.IsNullOrWhiteSpace(boundary)) { throw new ArgumentException(SR.net_http_argument_empty_string, "boundary"); } // RFC 2046 Section 5.1.1 // boundary := 0*69<bchars> bcharsnospace // bchars := bcharsnospace / " " // bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" if (boundary.Length > 70) { throw new ArgumentOutOfRangeException("boundary", boundary, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70)); } // Cannot end with space. if (boundary.EndsWith(" ", StringComparison.Ordinal)) { throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), "boundary"); } Contract.EndContractBlock(); string allowedMarks = @"'()+_,-./:=? "; foreach (char ch in boundary) { if (('0' <= ch && ch <= '9') || // Digit. ('a' <= ch && ch <= 'z') || // alpha. ('A' <= ch && ch <= 'Z') || // ALPHA. (allowedMarks.IndexOf(ch) >= 0)) // Marks. { // Valid. } else { throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), "boundary"); } } } private static string GetDefaultBoundary() { return Guid.NewGuid().ToString(); } public virtual void Add(HttpContent content) { if (content == null) { throw new ArgumentNullException("content"); } Contract.EndContractBlock(); _nestedContent.Add(content); } #endregion Construction #region Dispose protected override void Dispose(bool disposing) { if (disposing) { foreach (HttpContent content in _nestedContent) { content.Dispose(); } _nestedContent.Clear(); } base.Dispose(disposing); } #endregion Dispose #region IEnumerable<HttpContent> Members public IEnumerator<HttpContent> GetEnumerator() { return _nestedContent.GetEnumerator(); } #endregion #region IEnumerable Members Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return _nestedContent.GetEnumerator(); } #endregion #region Serialization // for-each content // write "--" + boundary // for-each content header // write header: header-value // write content.CopyTo[Async] // write "--" + boundary + "--" // Can't be canceled directly by the user. If the overall request is canceled // then the stream will be closed an an exception thrown. protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Debug.Assert(stream != null); Debug.Assert(_outputStream == null, "Opperation already in progress"); Debug.Assert(_tcs == null, "Opperation already in progress"); Debug.Assert(_nextContentIndex == 0, "Opperation already in progress"); // Keep a local copy in case the operation completes and cleans up synchronously. TaskCompletionSource<Object> localTcs = new TaskCompletionSource<Object>(); _tcs = localTcs; _outputStream = stream; _nextContentIndex = 0; // Start Boundary, chain everything else. EncodeStringToStreamAsync(_outputStream, "--" + _boundary + crlf) .ContinueWithStandard(WriteNextContentHeadersAsync); return localTcs.Task; } private void WriteNextContentHeadersAsync(Task task) { if (task.IsFaulted) { HandleAsyncException("WriteNextContentHeadersAsync", task.Exception.GetBaseException()); return; } try { // Base case, no more content, finish. if (_nextContentIndex >= _nestedContent.Count) { WriteTerminatingBoundaryAsync(); return; } string internalBoundary = crlf + "--" + _boundary + crlf; StringBuilder output = new StringBuilder(); if (_nextContentIndex == 0) { // First time, don't write dividing boundary. } else { output.Append(internalBoundary); } HttpContent content = _nestedContent[_nextContentIndex]; // Headers foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { output.Append(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf); } output.Append(crlf); // Extra CRLF to end headers (even if there are no headers). EncodeStringToStreamAsync(_outputStream, output.ToString()) .ContinueWithStandard(WriteNextContentAsync); } catch (Exception ex) { HandleAsyncException("WriteNextContentHeadersAsync", ex); } } private void WriteNextContentAsync(Task task) { if (task.IsFaulted) { HandleAsyncException("WriteNextContentAsync", task.Exception.GetBaseException()); return; } try { HttpContent content = _nestedContent[_nextContentIndex]; _nextContentIndex++; // Next call will operate on the next content object. content.CopyToAsync(_outputStream) .ContinueWithStandard(WriteNextContentHeadersAsync); } catch (Exception ex) { HandleAsyncException("WriteNextContentAsync", ex); } } // Final step, write the footer boundary. private void WriteTerminatingBoundaryAsync() { try { EncodeStringToStreamAsync(_outputStream, crlf + "--" + _boundary + "--" + crlf) .ContinueWithStandard(task => { if (task.IsFaulted) { HandleAsyncException("WriteTerminatingBoundaryAsync", task.Exception.GetBaseException()); return; } TaskCompletionSource<object> lastTcs = CleanupAsync(); lastTcs.TrySetResult(null); // This was the final opperation. }); } catch (Exception ex) { HandleAsyncException("WriteTerminatingBoundaryAsync", ex); } } private static Task EncodeStringToStreamAsync(Stream stream, string input) { byte[] buffer = HttpRuleParser.DefaultHttpEncoding.GetBytes(input); return stream.WriteAsync(buffer, 0, buffer.Length); } private TaskCompletionSource<object> CleanupAsync() { Contract.Requires(_tcs != null, "Operation already cleaned up"); TaskCompletionSource<object> toReturn = _tcs; _outputStream = null; _nextContentIndex = 0; _tcs = null; return toReturn; } private void HandleAsyncException(string method, Exception ex) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, method, ex); TaskCompletionSource<object> lastTcs = CleanupAsync(); lastTcs.TrySetException(ex); } protected internal override bool TryComputeLength(out long length) { long currentLength = 0; long internalBoundaryLength = GetEncodedLength(crlf + "--" + _boundary + crlf); // Start Boundary. currentLength += GetEncodedLength("--" + _boundary + crlf); bool first = true; foreach (HttpContent content in _nestedContent) { if (first) { first = false; // First boundary already written. } else { // Internal Boundary. currentLength += internalBoundaryLength; } // Headers. foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { currentLength += GetEncodedLength(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf); } currentLength += crlf.Length; // Content. long tempContentLength = 0; if (!content.TryComputeLength(out tempContentLength)) { length = 0; return false; } currentLength += tempContentLength; } // Terminating boundary. currentLength += GetEncodedLength(crlf + "--" + _boundary + "--" + crlf); length = currentLength; return true; } private static int GetEncodedLength(string input) { return HttpRuleParser.DefaultHttpEncoding.GetByteCount(input); } #endregion Serialization } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Lime.Protocol.Listeners; using Lime.Protocol.Network; using Lime.Protocol.Security; namespace Lime.Protocol.Server { /// <summary> /// Simple generic server for receiving connections and processing envelopes. /// </summary> public class Server : IServer { private readonly ITransportListener _transportListener; private readonly Func<ITransport, IServerChannel> _serverChannelFactory; private readonly SessionCompression[] _enabledCompressionOptions; private readonly SessionEncryption[] _enabledEncryptionOptions; private readonly AuthenticationScheme[] _schemeOptions; private readonly Func<Identity, Authentication, CancellationToken, Task<AuthenticationResult>> _authenticator; private readonly Func<IChannelInformation, IChannelListener> _channelListenerFactory; private readonly INodeRegistry _nodeRegistry; private readonly Func<Exception, Task<bool>> _exceptionHandler; private readonly int _maxActiveChannels; private readonly SemaphoreSlim _semaphore; private CancellationTokenSource _listenerCts; private Task _listenerTask; private ITargetBlock<IServerChannel> _consumerBlock; public Server( ITransportListener transportListener, Func<ITransport, IServerChannel> serverChannelFactory, SessionCompression[] enabledCompressionOptions, SessionEncryption[] enabledEncryptionOptions, AuthenticationScheme[] schemeOptions, Func<Identity, Authentication, CancellationToken, Task<AuthenticationResult>> authenticator, Func<IChannelInformation, IChannelListener> channelListenerFactory, INodeRegistry nodeRegistry = null, Func<Exception, Task<bool>> exceptionHandler = null, int maxActiveChannels = -1) { _transportListener = transportListener ?? throw new ArgumentNullException(nameof(transportListener)); _serverChannelFactory = serverChannelFactory ?? throw new ArgumentNullException(nameof(serverChannelFactory)); _enabledCompressionOptions = enabledCompressionOptions ?? throw new ArgumentNullException(nameof(enabledCompressionOptions)); _enabledEncryptionOptions = enabledEncryptionOptions ?? throw new ArgumentNullException(nameof(enabledEncryptionOptions)); _schemeOptions = schemeOptions ?? throw new ArgumentNullException(nameof(schemeOptions)); _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); _channelListenerFactory = channelListenerFactory ?? throw new ArgumentNullException(nameof(channelListenerFactory)); _nodeRegistry = nodeRegistry ?? new NodeRegistry(); _exceptionHandler = exceptionHandler; _maxActiveChannels = maxActiveChannels; _semaphore = new SemaphoreSlim(1, 1); } public async Task StartAsync(CancellationToken cancellationToken) { await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_listenerTask != null) throw new InvalidOperationException("The server is already started"); // Initialize a block for holding the channel consumer tasks. _consumerBlock = new ActionBlock<IServerChannel>( ConsumeAsync, new ExecutionDataflowBlockOptions { BoundedCapacity = _maxActiveChannels, MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, EnsureOrdered = false }); await _transportListener.StartAsync(cancellationToken).ConfigureAwait(false); // Initialize a background task for listening for new transport connections _listenerCts = new CancellationTokenSource(); _listenerTask = Task.Run(() => AcceptTransportsAsync(_listenerCts.Token)); } finally { _semaphore.Release(); } } public async Task StopAsync(CancellationToken cancellationToken) { await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_listenerTask == null) throw new InvalidOperationException("The server is not started"); await _transportListener.StopAsync(cancellationToken); _listenerCts.Cancel(); _consumerBlock.Complete(); await Task.WhenAll(_listenerTask, _consumerBlock.Completion).ConfigureAwait(false); _listenerCts.Dispose(); _listenerCts = null; _listenerTask = null; _consumerBlock = null; } finally { _semaphore.Release(); } } private async Task AcceptTransportsAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { try { var transport = await _transportListener.AcceptTransportAsync(cancellationToken) .ConfigureAwait(false); await transport.OpenAsync(null, cancellationToken).ConfigureAwait(false); var channel = _serverChannelFactory(transport); if (!await _consumerBlock.SendAsync(channel, cancellationToken)) { // The server pipeline is complete break; } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { break; } catch (Exception ex) { if (_exceptionHandler == null || !await _exceptionHandler(ex).ConfigureAwait(false)) { throw; } } } } private async Task ConsumeAsync(IServerChannel serverChannel) { try { // Establishes the session await serverChannel.EstablishSessionAsync( serverChannel.Transport.GetSupportedCompression().Intersect(_enabledCompressionOptions) .ToArray(), serverChannel.Transport.GetSupportedEncryption().Intersect(_enabledEncryptionOptions).ToArray(), _schemeOptions, _authenticator, _nodeRegistry.TryRegisterAsync, _listenerCts.Token) .ConfigureAwait(false); if (serverChannel.State == SessionState.Established) { await ListenAsync(serverChannel); } // If something bizarre occurs if (serverChannel.IsActive()) { await serverChannel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_ERROR, Description = "The session was terminated by the server" }, _listenerCts.Token); } } catch (OperationCanceledException) when (_listenerCts.IsCancellationRequested) { if (serverChannel.IsActive()) { await serverChannel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_ERROR, Description = "The server is being shut down" }, CancellationToken.None); } } catch (Exception ex) { if (_exceptionHandler != null) { await _exceptionHandler(ex).ConfigureAwait(false); } if (serverChannel.IsActive()) { await serverChannel.SendFailedSessionAsync( new Reason() { Code = ReasonCodes.SESSION_ERROR, Description = "An unexpected server error occurred" }, CancellationToken.None); } } finally { serverChannel.DisposeIfDisposable(); } } private async Task ListenAsync(IServerChannel serverChannel) { // Initializes a new consumer var channelListener = _channelListenerFactory(serverChannel); try { // Consume the channel envelopes channelListener.Start(serverChannel); // Awaits for the finishing envelope var finishingSessionTask = serverChannel.ReceiveFinishingSessionAsync(_listenerCts.Token); // Stops the consumer when any of the tasks finishes await Task.WhenAny( finishingSessionTask, channelListener.MessageListenerTask, channelListener.CommandListenerTask, channelListener.NotificationListenerTask); if (finishingSessionTask.IsCompleted) { await serverChannel.SendFinishedSessionAsync(_listenerCts.Token); } } finally { channelListener.Stop(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await _nodeRegistry.UnregisterAsync(serverChannel.RemoteNode, cts.Token); } } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiTextListCtrl : GuiArrayCtrl { public GuiTextListCtrl() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiTextListCtrlCreateInstance()); } public GuiTextListCtrl(uint pId) : base(pId) { } public GuiTextListCtrl(string pName) : base(pName) { } public GuiTextListCtrl(IntPtr pObjPtr) : base(pObjPtr) { } public GuiTextListCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiTextListCtrl(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _GuiTextListCtrlGetEnumerate(IntPtr ctrl); private static _GuiTextListCtrlGetEnumerate _GuiTextListCtrlGetEnumerateFunc; internal static bool GuiTextListCtrlGetEnumerate(IntPtr ctrl) { if (_GuiTextListCtrlGetEnumerateFunc == null) { _GuiTextListCtrlGetEnumerateFunc = (_GuiTextListCtrlGetEnumerate)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetEnumerate"), typeof(_GuiTextListCtrlGetEnumerate)); } return _GuiTextListCtrlGetEnumerateFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetEnumerate(IntPtr ctrl, bool enumerate); private static _GuiTextListCtrlSetEnumerate _GuiTextListCtrlSetEnumerateFunc; internal static void GuiTextListCtrlSetEnumerate(IntPtr ctrl, bool enumerate) { if (_GuiTextListCtrlSetEnumerateFunc == null) { _GuiTextListCtrlSetEnumerateFunc = (_GuiTextListCtrlSetEnumerate)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetEnumerate"), typeof(_GuiTextListCtrlSetEnumerate)); } _GuiTextListCtrlSetEnumerateFunc(ctrl, enumerate); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _GuiTextListCtrlGetResizeCell(IntPtr ctrl); private static _GuiTextListCtrlGetResizeCell _GuiTextListCtrlGetResizeCellFunc; internal static bool GuiTextListCtrlGetResizeCell(IntPtr ctrl) { if (_GuiTextListCtrlGetResizeCellFunc == null) { _GuiTextListCtrlGetResizeCellFunc = (_GuiTextListCtrlGetResizeCell)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetResizeCell"), typeof(_GuiTextListCtrlGetResizeCell)); } return _GuiTextListCtrlGetResizeCellFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetResizeCell(IntPtr ctrl, bool resize); private static _GuiTextListCtrlSetResizeCell _GuiTextListCtrlSetResizeCellFunc; internal static void GuiTextListCtrlSetResizeCell(IntPtr ctrl, bool resize) { if (_GuiTextListCtrlSetResizeCellFunc == null) { _GuiTextListCtrlSetResizeCellFunc = (_GuiTextListCtrlSetResizeCell)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetResizeCell"), typeof(_GuiTextListCtrlSetResizeCell)); } _GuiTextListCtrlSetResizeCellFunc(ctrl, resize); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _GuiTextListCtrlGetFitParentWidth(IntPtr ctrl); private static _GuiTextListCtrlGetFitParentWidth _GuiTextListCtrlGetFitParentWidthFunc; internal static bool GuiTextListCtrlGetFitParentWidth(IntPtr ctrl) { if (_GuiTextListCtrlGetFitParentWidthFunc == null) { _GuiTextListCtrlGetFitParentWidthFunc = (_GuiTextListCtrlGetFitParentWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetFitParentWidth"), typeof(_GuiTextListCtrlGetFitParentWidth)); } return _GuiTextListCtrlGetFitParentWidthFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetFitParentWidth(IntPtr ctrl, bool fitParentWidth); private static _GuiTextListCtrlSetFitParentWidth _GuiTextListCtrlSetFitParentWidthFunc; internal static void GuiTextListCtrlSetFitParentWidth(IntPtr ctrl, bool fitParentWidth) { if (_GuiTextListCtrlSetFitParentWidthFunc == null) { _GuiTextListCtrlSetFitParentWidthFunc = (_GuiTextListCtrlSetFitParentWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetFitParentWidth"), typeof(_GuiTextListCtrlSetFitParentWidth)); } _GuiTextListCtrlSetFitParentWidthFunc(ctrl, fitParentWidth); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _GuiTextListCtrlGetClipColumnText(IntPtr ctrl); private static _GuiTextListCtrlGetClipColumnText _GuiTextListCtrlGetClipColumnTextFunc; internal static bool GuiTextListCtrlGetClipColumnText(IntPtr ctrl) { if (_GuiTextListCtrlGetClipColumnTextFunc == null) { _GuiTextListCtrlGetClipColumnTextFunc = (_GuiTextListCtrlGetClipColumnText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetClipColumnText"), typeof(_GuiTextListCtrlGetClipColumnText)); } return _GuiTextListCtrlGetClipColumnTextFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetClipColumnText(IntPtr ctrl, bool clip); private static _GuiTextListCtrlSetClipColumnText _GuiTextListCtrlSetClipColumnTextFunc; internal static void GuiTextListCtrlSetClipColumnText(IntPtr ctrl, bool clip) { if (_GuiTextListCtrlSetClipColumnTextFunc == null) { _GuiTextListCtrlSetClipColumnTextFunc = (_GuiTextListCtrlSetClipColumnText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetClipColumnText"), typeof(_GuiTextListCtrlSetClipColumnText)); } _GuiTextListCtrlSetClipColumnTextFunc(ctrl, clip); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiTextListCtrlCreateInstance(); private static _GuiTextListCtrlCreateInstance _GuiTextListCtrlCreateInstanceFunc; internal static IntPtr GuiTextListCtrlCreateInstance() { if (_GuiTextListCtrlCreateInstanceFunc == null) { _GuiTextListCtrlCreateInstanceFunc = (_GuiTextListCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlCreateInstance"), typeof(_GuiTextListCtrlCreateInstance)); } return _GuiTextListCtrlCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate uint _GuiTextListCtrlGetSelectedId(IntPtr ctrl); private static _GuiTextListCtrlGetSelectedId _GuiTextListCtrlGetSelectedIdFunc; internal static uint GuiTextListCtrlGetSelectedId(IntPtr ctrl) { if (_GuiTextListCtrlGetSelectedIdFunc == null) { _GuiTextListCtrlGetSelectedIdFunc = (_GuiTextListCtrlGetSelectedId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetSelectedId"), typeof(_GuiTextListCtrlGetSelectedId)); } return _GuiTextListCtrlGetSelectedIdFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetSelectedById(IntPtr ctrl, uint ID); private static _GuiTextListCtrlSetSelectedById _GuiTextListCtrlSetSelectedByIdFunc; internal static void GuiTextListCtrlSetSelectedById(IntPtr ctrl, uint ID) { if (_GuiTextListCtrlSetSelectedByIdFunc == null) { _GuiTextListCtrlSetSelectedByIdFunc = (_GuiTextListCtrlSetSelectedById)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetSelectedById"), typeof(_GuiTextListCtrlSetSelectedById)); } _GuiTextListCtrlSetSelectedByIdFunc(ctrl, ID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetSelectedRow(IntPtr ctrl, uint rowNum); private static _GuiTextListCtrlSetSelectedRow _GuiTextListCtrlSetSelectedRowFunc; internal static void GuiTextListCtrlSetSelectedRow(IntPtr ctrl, uint rowNum) { if (_GuiTextListCtrlSetSelectedRowFunc == null) { _GuiTextListCtrlSetSelectedRowFunc = (_GuiTextListCtrlSetSelectedRow)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetSelectedRow"), typeof(_GuiTextListCtrlSetSelectedRow)); } _GuiTextListCtrlSetSelectedRowFunc(ctrl, rowNum); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate uint _GuiTextListCtrlGetSelectedRow(IntPtr ctrl); private static _GuiTextListCtrlGetSelectedRow _GuiTextListCtrlGetSelectedRowFunc; internal static uint GuiTextListCtrlGetSelectedRow(IntPtr ctrl) { if (_GuiTextListCtrlGetSelectedRowFunc == null) { _GuiTextListCtrlGetSelectedRowFunc = (_GuiTextListCtrlGetSelectedRow)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetSelectedRow"), typeof(_GuiTextListCtrlGetSelectedRow)); } return _GuiTextListCtrlGetSelectedRowFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlClearSelection(IntPtr ctrl); private static _GuiTextListCtrlClearSelection _GuiTextListCtrlClearSelectionFunc; internal static void GuiTextListCtrlClearSelection(IntPtr ctrl) { if (_GuiTextListCtrlClearSelectionFunc == null) { _GuiTextListCtrlClearSelectionFunc = (_GuiTextListCtrlClearSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlClearSelection"), typeof(_GuiTextListCtrlClearSelection)); } _GuiTextListCtrlClearSelectionFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiTextListCtrlAddRow(IntPtr ctrl, uint ID, string text, int row); private static _GuiTextListCtrlAddRow _GuiTextListCtrlAddRowFunc; internal static int GuiTextListCtrlAddRow(IntPtr ctrl, uint ID, string text, int row) { if (_GuiTextListCtrlAddRowFunc == null) { _GuiTextListCtrlAddRowFunc = (_GuiTextListCtrlAddRow)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlAddRow"), typeof(_GuiTextListCtrlAddRow)); } return _GuiTextListCtrlAddRowFunc(ctrl, ID, text, row); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetRowById(IntPtr ctrl, uint ID, string text); private static _GuiTextListCtrlSetRowById _GuiTextListCtrlSetRowByIdFunc; internal static void GuiTextListCtrlSetRowById(IntPtr ctrl, uint ID, string text) { if (_GuiTextListCtrlSetRowByIdFunc == null) { _GuiTextListCtrlSetRowByIdFunc = (_GuiTextListCtrlSetRowById)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetRowById"), typeof(_GuiTextListCtrlSetRowById)); } _GuiTextListCtrlSetRowByIdFunc(ctrl, ID, text); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSort(IntPtr ctrl, uint columnID, bool ascending); private static _GuiTextListCtrlSort _GuiTextListCtrlSortFunc; internal static void GuiTextListCtrlSort(IntPtr ctrl, uint columnID, bool ascending) { if (_GuiTextListCtrlSortFunc == null) { _GuiTextListCtrlSortFunc = (_GuiTextListCtrlSort)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSort"), typeof(_GuiTextListCtrlSort)); } _GuiTextListCtrlSortFunc(ctrl, columnID, ascending); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSortNumerical(IntPtr ctrl, uint columnID, bool ascending); private static _GuiTextListCtrlSortNumerical _GuiTextListCtrlSortNumericalFunc; internal static void GuiTextListCtrlSortNumerical(IntPtr ctrl, uint columnID, bool ascending) { if (_GuiTextListCtrlSortNumericalFunc == null) { _GuiTextListCtrlSortNumericalFunc = (_GuiTextListCtrlSortNumerical)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSortNumerical"), typeof(_GuiTextListCtrlSortNumerical)); } _GuiTextListCtrlSortNumericalFunc(ctrl, columnID, ascending); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlClear(IntPtr ctrl); private static _GuiTextListCtrlClear _GuiTextListCtrlClearFunc; internal static void GuiTextListCtrlClear(IntPtr ctrl) { if (_GuiTextListCtrlClearFunc == null) { _GuiTextListCtrlClearFunc = (_GuiTextListCtrlClear)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlClear"), typeof(_GuiTextListCtrlClear)); } _GuiTextListCtrlClearFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate uint _GuiTextListCtrlRowCount(IntPtr ctrl); private static _GuiTextListCtrlRowCount _GuiTextListCtrlRowCountFunc; internal static uint GuiTextListCtrlRowCount(IntPtr ctrl) { if (_GuiTextListCtrlRowCountFunc == null) { _GuiTextListCtrlRowCountFunc = (_GuiTextListCtrlRowCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlRowCount"), typeof(_GuiTextListCtrlRowCount)); } return _GuiTextListCtrlRowCountFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate uint _GuiTextListCtrlGetRowId(IntPtr ctrl, uint row); private static _GuiTextListCtrlGetRowId _GuiTextListCtrlGetRowIdFunc; internal static uint GuiTextListCtrlGetRowId(IntPtr ctrl, uint row) { if (_GuiTextListCtrlGetRowIdFunc == null) { _GuiTextListCtrlGetRowIdFunc = (_GuiTextListCtrlGetRowId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetRowId"), typeof(_GuiTextListCtrlGetRowId)); } return _GuiTextListCtrlGetRowIdFunc(ctrl, row); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiTextListCtrlGetRowTextById(IntPtr ctrl, uint ID); private static _GuiTextListCtrlGetRowTextById _GuiTextListCtrlGetRowTextByIdFunc; internal static IntPtr GuiTextListCtrlGetRowTextById(IntPtr ctrl, uint ID) { if (_GuiTextListCtrlGetRowTextByIdFunc == null) { _GuiTextListCtrlGetRowTextByIdFunc = (_GuiTextListCtrlGetRowTextById)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetRowTextById"), typeof(_GuiTextListCtrlGetRowTextById)); } return _GuiTextListCtrlGetRowTextByIdFunc(ctrl, ID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiTextListCtrlGetRowNumById(IntPtr ctrl, uint ID); private static _GuiTextListCtrlGetRowNumById _GuiTextListCtrlGetRowNumByIdFunc; internal static int GuiTextListCtrlGetRowNumById(IntPtr ctrl, uint ID) { if (_GuiTextListCtrlGetRowNumByIdFunc == null) { _GuiTextListCtrlGetRowNumByIdFunc = (_GuiTextListCtrlGetRowNumById)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetRowNumById"), typeof(_GuiTextListCtrlGetRowNumById)); } return _GuiTextListCtrlGetRowNumByIdFunc(ctrl, ID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiTextListCtrlGetRowText(IntPtr ctrl, uint row); private static _GuiTextListCtrlGetRowText _GuiTextListCtrlGetRowTextFunc; internal static IntPtr GuiTextListCtrlGetRowText(IntPtr ctrl, uint row) { if (_GuiTextListCtrlGetRowTextFunc == null) { _GuiTextListCtrlGetRowTextFunc = (_GuiTextListCtrlGetRowText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlGetRowText"), typeof(_GuiTextListCtrlGetRowText)); } return _GuiTextListCtrlGetRowTextFunc(ctrl, row); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlRemoveRowById(IntPtr ctrl, uint ID); private static _GuiTextListCtrlRemoveRowById _GuiTextListCtrlRemoveRowByIdFunc; internal static void GuiTextListCtrlRemoveRowById(IntPtr ctrl, uint ID) { if (_GuiTextListCtrlRemoveRowByIdFunc == null) { _GuiTextListCtrlRemoveRowByIdFunc = (_GuiTextListCtrlRemoveRowById)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlRemoveRowById"), typeof(_GuiTextListCtrlRemoveRowById)); } _GuiTextListCtrlRemoveRowByIdFunc(ctrl, ID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlRemoveRow(IntPtr ctrl, int row); private static _GuiTextListCtrlRemoveRow _GuiTextListCtrlRemoveRowFunc; internal static void GuiTextListCtrlRemoveRow(IntPtr ctrl, int row) { if (_GuiTextListCtrlRemoveRowFunc == null) { _GuiTextListCtrlRemoveRowFunc = (_GuiTextListCtrlRemoveRow)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlRemoveRow"), typeof(_GuiTextListCtrlRemoveRow)); } _GuiTextListCtrlRemoveRowFunc(ctrl, row); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlScrollVisible(IntPtr ctrl, uint row); private static _GuiTextListCtrlScrollVisible _GuiTextListCtrlScrollVisibleFunc; internal static void GuiTextListCtrlScrollVisible(IntPtr ctrl, uint row) { if (_GuiTextListCtrlScrollVisibleFunc == null) { _GuiTextListCtrlScrollVisibleFunc = (_GuiTextListCtrlScrollVisible)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlScrollVisible"), typeof(_GuiTextListCtrlScrollVisible)); } _GuiTextListCtrlScrollVisibleFunc(ctrl, row); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _GuiTextListCtrlFindTextIndex(IntPtr ctrl, string text); private static _GuiTextListCtrlFindTextIndex _GuiTextListCtrlFindTextIndexFunc; internal static int GuiTextListCtrlFindTextIndex(IntPtr ctrl, string text) { if (_GuiTextListCtrlFindTextIndexFunc == null) { _GuiTextListCtrlFindTextIndexFunc = (_GuiTextListCtrlFindTextIndex)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlFindTextIndex"), typeof(_GuiTextListCtrlFindTextIndex)); } return _GuiTextListCtrlFindTextIndexFunc(ctrl, text); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiTextListCtrlSetRowActive(IntPtr ctrl, uint row, bool active); private static _GuiTextListCtrlSetRowActive _GuiTextListCtrlSetRowActiveFunc; internal static void GuiTextListCtrlSetRowActive(IntPtr ctrl, uint row, bool active) { if (_GuiTextListCtrlSetRowActiveFunc == null) { _GuiTextListCtrlSetRowActiveFunc = (_GuiTextListCtrlSetRowActive)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlSetRowActive"), typeof(_GuiTextListCtrlSetRowActive)); } _GuiTextListCtrlSetRowActiveFunc(ctrl, row, active); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _GuiTextListCtrlIsRowActive(IntPtr ctrl, uint row); private static _GuiTextListCtrlIsRowActive _GuiTextListCtrlIsRowActiveFunc; internal static bool GuiTextListCtrlIsRowActive(IntPtr ctrl, uint row) { if (_GuiTextListCtrlIsRowActiveFunc == null) { _GuiTextListCtrlIsRowActiveFunc = (_GuiTextListCtrlIsRowActive)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiTextListCtrlIsRowActive"), typeof(_GuiTextListCtrlIsRowActive)); } return _GuiTextListCtrlIsRowActiveFunc(ctrl, row); } } #endregion #region Properties public bool Enumerate { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetEnumerate(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetEnumerate(ObjectPtr->ObjPtr, value); } } public bool ResizeCell { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetResizeCell(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetResizeCell(ObjectPtr->ObjPtr, value); } } public bool FitParentWidth { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetFitParentWidth(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetFitParentWidth(ObjectPtr->ObjPtr, value); } } public bool ClipColumnText { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetClipColumnText(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetClipColumnText(ObjectPtr->ObjPtr, value); } } #endregion #region Methods public uint GetSelectedId() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetSelectedId(ObjectPtr->ObjPtr); } public void SetSelectedById(uint ID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetSelectedById(ObjectPtr->ObjPtr, ID); } public void SetSelectedRow(uint rowNum) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetSelectedRow(ObjectPtr->ObjPtr, rowNum); } public uint GetSelectedRow() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetSelectedRow(ObjectPtr->ObjPtr); } public void ClearSelection() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlClearSelection(ObjectPtr->ObjPtr); } public int AddRow(uint ID, string text, int row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlAddRow(ObjectPtr->ObjPtr, ID, text, row); } public void SetRowById(uint ID, string text) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetRowById(ObjectPtr->ObjPtr, ID, text); } public void Sort(uint columnID, bool ascending) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSort(ObjectPtr->ObjPtr, columnID, ascending); } public void SortNumerical(uint columnID, bool ascending) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSortNumerical(ObjectPtr->ObjPtr, columnID, ascending); } public void Clear() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlClear(ObjectPtr->ObjPtr); } public uint RowCount() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlRowCount(ObjectPtr->ObjPtr); } public uint GetRowId(uint row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetRowId(ObjectPtr->ObjPtr, row); } public string GetRowTextById(uint ID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.GuiTextListCtrlGetRowTextById(ObjectPtr->ObjPtr, ID)); } public int GetRowNumById(uint ID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlGetRowNumById(ObjectPtr->ObjPtr, ID); } public string GetRowText(uint row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.GuiTextListCtrlGetRowText(ObjectPtr->ObjPtr, row)); } public void RemoveRowById(uint ID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlRemoveRowById(ObjectPtr->ObjPtr, ID); } public void RemoveRow(int row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlRemoveRow(ObjectPtr->ObjPtr, row); } public void ScrollVisible(uint row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlScrollVisible(ObjectPtr->ObjPtr, row); } public int FindTextIndex(string text) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlFindTextIndex(ObjectPtr->ObjPtr, text); } public void SetRowActive(uint row, bool active) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiTextListCtrlSetRowActive(ObjectPtr->ObjPtr, row, active); } public bool IsRowActive(uint row) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiTextListCtrlIsRowActive(ObjectPtr->ObjPtr, row); } #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. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class represents the software preferences of a particular // culture or community. It includes information such as the // language, writing system, and a calendar used by the culture // as well as methods for common operations such as printing // dates and sorting strings. // // // // !!!! NOTE WHEN CHANGING THIS CLASS !!!! // // If adding or removing members to this class, please update CultureInfoBaseObject // in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be // different than the order in which members are declared. For instance, all // reference types will come first in the class before value types (like ints, bools, etc) // regardless of the order in which they are declared. The best way to see the // actual order of the class is to do a !dumpobj on an instance of the managed // object inside of the debugger. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; #if ENABLE_WINRT using Internal.Runtime.Augments; #endif namespace System.Globalization { [Serializable] public partial class CultureInfo : IFormatProvider, ICloneable { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// //--------------------------------------------------------------------// // Data members to be serialized: //--------------------------------------------------------------------// // We use an RFC4646 type string to construct CultureInfo. // This string is stored in m_name and is authoritative. // We use the _cultureData to get the data for our object private bool _isReadOnly; private CompareInfo _compareInfo; private TextInfo _textInfo; internal NumberFormatInfo numInfo; internal DateTimeFormatInfo dateTimeInfo; private Calendar _calendar; // // The CultureData instance that we are going to read data from. // For supported culture, this will be the CultureData instance that read data from mscorlib assembly. // For customized culture, this will be the CultureData instance that read data from user customized culture binary file. // internal CultureData _cultureData; internal bool _isInherited; private CultureInfo m_consoleFallbackCulture; // Names are confusing. Here are 3 names we have: // // new CultureInfo() m_name _nonSortName _sortName // en-US en-US en-US en-US // de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb // fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US) // en en // // Note that in Silverlight we ask the OS for the text and sort behavior, so the // textinfo and compareinfo names are the same as the name // Note that the name used to be serialized for Everett; it is now serialized // because alernate sorts can have alternate names. // This has a de-DE, de-DE_phoneb or fj-FJ style name internal string m_name; // This will hold the non sorting name to be returned from CultureInfo.Name property. // This has a de-DE style name even for de-DE_phoneb type cultures private string _nonSortName; // This will hold the sorting name to be returned from CultureInfo.SortName property. // This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ. // Otherwise its the sort name, ie: de-DE or de-DE_phoneb private string _sortName; //--------------------------------------------------------------------// // // Static data members // //--------------------------------------------------------------------// //Get the current user default culture. This one is almost always used, so we create it by default. private static volatile CultureInfo s_userDefaultCulture; // // All of the following will be created on demand. // // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. //The Invariant culture; private static volatile CultureInfo s_InvariantCultureInfo; //These are defaults that we use if a thread has not opted into having an explicit culture private static volatile CultureInfo s_DefaultThreadCurrentUICulture; private static volatile CultureInfo s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo s_currentThreadCulture; [ThreadStatic] private static CultureInfo s_currentThreadUICulture; private static readonly Lock s_lock = new Lock(); private static volatile LowLevelDictionary<string, CultureInfo> s_NameCachedCultures; private static volatile LowLevelDictionary<int, CultureInfo> s_LcidCachedCultures; //The parent culture. private CultureInfo _parent; // LOCALE constants of interest to us internally and privately for LCID functions // (ie: avoid using these and use names if possible) internal const int LOCALE_NEUTRAL = 0x0000; private const int LOCALE_USER_DEFAULT = 0x0400; private const int LOCALE_SYSTEM_DEFAULT = 0x0800; internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000; internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00; internal const int LOCALE_INVARIANT = 0x007F; // // The CultureData instance that reads the data provided by our CultureData class. // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. private static readonly bool s_init = Init(); private static bool Init() { if (s_InvariantCultureInfo == null) { CultureInfo temp = new CultureInfo("", false); temp._isReadOnly = true; s_InvariantCultureInfo = temp; } s_userDefaultCulture = GetUserDefaultCulture(); return true; } //////////////////////////////////////////////////////////////////////// // // CultureInfo Constructors // //////////////////////////////////////////////////////////////////////// public CultureInfo(String name) : this(name, true) { } public CultureInfo(String name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException(nameof(name), SR.ArgumentNull_String); } // Get our data providing record this._cultureData = CultureData.GetCultureData(name, useUserOverride); if (this._cultureData == null) throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); this.m_name = this._cultureData.CultureName; this._isInherited = !this.EETypePtr.FastEquals(EETypePtr.EETypePtrOf<CultureInfo>()); } public CultureInfo(int culture) : this(culture, true) { } public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); InitializeFromCultureId(culture, useUserOverride); } private void InitializeFromCultureId(int culture, bool useUserOverride) { switch (culture) { case LOCALE_CUSTOM_DEFAULT: case LOCALE_SYSTEM_DEFAULT: case LOCALE_NEUTRAL: case LOCALE_USER_DEFAULT: case LOCALE_CUSTOM_UNSPECIFIED: // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); default: // Now see if this LCID is supported in the system default CultureData table. _cultureData = CultureData.GetCultureData(culture, useUserOverride); break; } _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo)); m_name = _cultureData.CultureName; } // Constructor called by SQL Server's special munged culture - creates a culture with // a TextInfo and CompareInfo that come from a supplied alternate source. This object // is ALWAYS read-only. // Note that we really cannot use an LCID version of this override as the cached // name we create for it has to include both names, and the logic for this is in // the GetCultureInfo override *only*. internal CultureInfo(String cultureName, String textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); } Contract.EndContractBlock(); _cultureData = CultureData.GetCultureData(cultureName, false); if (_cultureData == null) throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported); m_name = _cultureData.CultureName; CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName); _compareInfo = altCulture.CompareInfo; _textInfo = altCulture.TextInfo; } // We do this to try to return the system UI language and the default user languages // This method will fallback if this fails (like Invariant) // // TODO: It would appear that this is only ever called with userOveride = true // and this method only has one caller. Can we fold it into the caller? private static CultureInfo GetCultureByName(String name, bool userOverride) { CultureInfo ci = null; // Try to get our culture try { ci = userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name); } catch (ArgumentException) { } if (ci == null) { ci = InvariantCulture; } return ci; } // // Return a specific culture. A tad irrelevent now since we always return valid data // for neutral locales. // // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647, // if we can't find a bigger name. That doesn't help with things like "zh" though, so // the approach is of questionable value // public static CultureInfo CreateSpecificCulture(String name) { Contract.Ensures(Contract.Result<CultureInfo>() != null); CultureInfo culture; try { culture = new CultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. int idx; culture = null; for (idx = 0; idx < name.Length; idx++) { if ('-' == name[idx]) { try { culture = new CultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!(culture.IsNeutralCulture)) { return culture; } return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE)); } // // // // Return a specific culture. A tad irrelevent now since we always return valid data // // for neutral locales. // // // // Note that there's interesting behavior that tries to find a smaller name, ala RFC4647, // // if we can't find a bigger name. That doesn't help with things like "zh" though, so // // the approach is of questionable value // // internal static bool VerifyCultureName(String cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, // so we should check against CultureInfo.Name. for (int i = 0; i < cultureName.Length; i++) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { //If we have an instance of one of our CultureInfos, the user can't have changed the //name and we know that all names are valid in files. if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } //////////////////////////////////////////////////////////////////////// // // CurrentCulture // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// // // We use the following order to return CurrentCulture and CurrentUICulture // o Use WinRT to return the current user profile language // o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture // o use thread culture if the user already set one using DefaultThreadCurrentCulture // or DefaultThreadCurrentUICulture // o Use NLS default user culture // o Use NLS default system culture // o Use Invariant culture // public static CultureInfo CurrentCulture { get { CultureInfo ci = GetUserDefaultCultureCacheOverride(); if (ci != null) { return ci; } if (s_currentThreadCulture != null) { return s_currentThreadCulture; } ci = s_DefaultThreadCurrentCulture; if (ci != null) { return ci; } // if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize if (s_userDefaultCulture == null) { Init(); } Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif s_currentThreadCulture = value; } } public static CultureInfo CurrentUICulture { get { CultureInfo ci = GetUserDefaultCultureCacheOverride(); if (ci != null) { return ci; } if (s_currentThreadUICulture != null) { return s_currentThreadUICulture; } ci = s_DefaultThreadCurrentUICulture; if (ci != null) { return ci; } // if s_userDefaultCulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn't get chance to initialize if (s_userDefaultCulture == null) { Init(); } Debug.Assert(s_userDefaultCulture != null); return s_userDefaultCulture; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } CultureInfo.VerifyCultureName(value, true); #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; if (callbacks != null && callbacks.IsAppxModel()) { callbacks.SetGlobalDefaultCulture(value); return; } #endif s_currentThreadUICulture = value; } } public static CultureInfo InstalledUICulture { get { Contract.Ensures(Contract.Result<CultureInfo>() != null); if (s_userDefaultCulture == null) { Init(); } Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null"); return s_userDefaultCulture; } } public static CultureInfo DefaultThreadCurrentCulture { get { return s_DefaultThreadCurrentCulture; } set { // If you add pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentCulture.set. s_DefaultThreadCurrentCulture = value; } } public static CultureInfo DefaultThreadCurrentUICulture { get { return s_DefaultThreadCurrentUICulture; } set { //If they're trying to use a Culture with a name that we can't use in resource lookup, //don't even let them set it on the thread. // If you add more pre-conditions to this method, check to see if you also need to // add them to Thread.CurrentUICulture.set. if (value != null) { CultureInfo.VerifyCultureName(value, true); } s_DefaultThreadCurrentUICulture = value; } } //////////////////////////////////////////////////////////////////////// // // InvariantCulture // // This instance provides methods, for example for casing and sorting, // that are independent of the system and current user settings. It // should be used only by processes such as some system services that // require such invariant results (eg. file systems). In general, // the results are not linguistically correct and do not match any // culture info. // //////////////////////////////////////////////////////////////////////// public static CultureInfo InvariantCulture { get { return (s_InvariantCultureInfo); } } //////////////////////////////////////////////////////////////////////// // // Parent // // Return the parent CultureInfo for the current instance. // //////////////////////////////////////////////////////////////////////// public virtual CultureInfo Parent { get { if (null == _parent) { CultureInfo culture = null; try { string parentName = this._cultureData.SPARENT; if (String.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } else { culture = new CultureInfo(parentName, this._cultureData.UseUserOverride); } } catch (ArgumentException) { // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. culture = InvariantCulture; } Interlocked.CompareExchange<CultureInfo>(ref _parent, culture, null); } return _parent; } } public virtual int LCID { get { return (this._cultureData.ILANGUAGE); } } public virtual int KeyboardLayoutId { get { return _cultureData.IINPUTLANGUAGEHANDLE; } } public static CultureInfo[] GetCultures(CultureTypes types) { Contract.Ensures(Contract.Result<CultureInfo[]>() != null); // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return (CultureData.GetCultures(types)); } //////////////////////////////////////////////////////////////////////// // // Name // // Returns the full name of the CultureInfo. The name is in format like // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { // We return non sorting name here. if (_nonSortName == null) { _nonSortName = this._cultureData.SNAME; if (_nonSortName == null) { _nonSortName = String.Empty; } } return _nonSortName; } } // This one has the sort information (ie: de-DE_phoneb) internal String SortName { get { if (_sortName == null) { _sortName = this._cultureData.SCOMPAREINFO; } return _sortName; } } public string IetfLanguageTag { get { Contract.Ensures(Contract.Result<string>() != null); // special case the compatibility cultures switch (this.Name) { case "zh-CHT": return "zh-Hant"; case "zh-CHS": return "zh-Hans"; default: return this.Name; } } } //////////////////////////////////////////////////////////////////////// // // DisplayName // // Returns the full name of the CultureInfo in the localized language. // For example, if the localized language of the runtime is Spanish and the CultureInfo is // US English, "Ingles (Estados Unidos)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { Contract.Ensures(Contract.Result<String>() != null); Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set"); return _cultureData.SLOCALIZEDDISPLAYNAME; } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the full name of the CultureInfo in the native language. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SNATIVEDISPLAYNAME); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the full name of the CultureInfo in English. // For example, if the CultureInfo is US English, "English // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SENGDISPLAYNAME); } } // ie: en public virtual String TwoLetterISOLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return (this._cultureData.SISO639LANGNAME); } } // ie: eng public virtual String ThreeLetterISOLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return _cultureData.SISO639LANGNAME2; } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsLanguageName // // Returns the 3 letter windows language name for the current instance. eg: "ENU" // The ISO names are much preferred // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsLanguageName { get { Contract.Ensures(Contract.Result<String>() != null); return _cultureData.SABBREVLANGNAME; } } //////////////////////////////////////////////////////////////////////// // // CompareInfo Read-Only Property // // Gets the CompareInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual CompareInfo CompareInfo { get { if (_compareInfo == null) { // Since CompareInfo's don't have any overrideable properties, get the CompareInfo from // the Non-Overridden CultureInfo so that we only create one CompareInfo per culture CompareInfo temp = UseUserOverride ? GetCultureInfo(this.m_name).CompareInfo : new CompareInfo(this); if (OkayToCacheClassWithCompatibilityBehavior) { _compareInfo = temp; } else { return temp; } } return (_compareInfo); } } private static bool OkayToCacheClassWithCompatibilityBehavior { get { return true; } } //////////////////////////////////////////////////////////////////////// // // TextInfo // // Gets the TextInfo for this culture. // //////////////////////////////////////////////////////////////////////// public virtual TextInfo TextInfo { get { if (_textInfo == null) { // Make a new textInfo TextInfo tempTextInfo = new TextInfo(this._cultureData); tempTextInfo.SetReadOnlyState(_isReadOnly); if (OkayToCacheClassWithCompatibilityBehavior) { _textInfo = tempTextInfo; } else { return tempTextInfo; } } return (_textInfo); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { if (Object.ReferenceEquals(this, value)) return true; CultureInfo that = value as CultureInfo; if (that != null) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo)); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the CultureInfo, // eg. "de-DE_phoneb", "en-US", or "fj-FJ". // //////////////////////////////////////////////////////////////////////// public override String ToString() { return m_name; } public virtual Object GetFormat(Type formatType) { if (formatType == typeof(NumberFormatInfo)) return (NumberFormat); if (formatType == typeof(DateTimeFormatInfo)) return (DateTimeFormat); return (null); } public virtual bool IsNeutralCulture { get { return this._cultureData.IsNeutralCulture; } } public CultureTypes CultureTypes { get { CultureTypes types = 0; if (_cultureData.IsNeutralCulture) types |= CultureTypes.NeutralCultures; else types |= CultureTypes.SpecificCultures; types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0; // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete #pragma warning disable 618 types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0; #pragma warning restore 618 types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0; types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0; return types; } } public virtual NumberFormatInfo NumberFormat { get { if (numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(this._cultureData); temp.isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref numInfo, temp, null); } return (numInfo); } set { if (value == null) { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj); } VerifyWritable(); numInfo = value; } } //////////////////////////////////////////////////////////////////////// // // GetDateTimeFormatInfo // // Create a DateTimeFormatInfo, and fill in the properties according to // the CultureID. // //////////////////////////////////////////////////////////////////////// public virtual DateTimeFormatInfo DateTimeFormat { get { if (dateTimeInfo == null) { // Change the calendar of DTFI to the specified calendar of this CultureInfo. DateTimeFormatInfo temp = new DateTimeFormatInfo(this._cultureData, this.Calendar); temp._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref dateTimeInfo, temp, null); } return (dateTimeInfo); } set { if (value == null) { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj); } VerifyWritable(); dateTimeInfo = value; } } public void ClearCachedData() { s_userDefaultCulture = null; RegionInfo.s_currentRegionInfo = null; #pragma warning disable 0618 // disable the obsolete warning TimeZone.ResetTimeZone(); #pragma warning restore 0618 TimeZoneInfo.ClearCachedData(); s_LcidCachedCultures = null; s_NameCachedCultures = null; CultureData.ClearCachedData(); } /*=================================GetCalendarInstance========================== **Action: Map a Win32 CALID to an instance of supported calendar. **Returns: An instance of calendar. **Arguments: calType The Win32 CALID **Exceptions: ** Shouldn't throw exception since the calType value is from our data table or from Win32 registry. ** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar. ============================================================================*/ internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return (new GregorianCalendar()); } return GetCalendarInstanceRare(calType); } //This function exists as a shortcut to prevent us from loading all of the non-gregorian //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(CalendarId calType) { Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN"); switch (calType) { case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar return (new GregorianCalendar((GregorianCalendarTypes)calType)); case CalendarId.TAIWAN: // Taiwan Era calendar return (new TaiwanCalendar()); case CalendarId.JAPAN: // Japanese Emperor Era calendar return (new JapaneseCalendar()); case CalendarId.KOREA: // Korean Tangun Era calendar return (new KoreanCalendar()); case CalendarId.THAI: // Thai calendar return (new ThaiBuddhistCalendar()); case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar return (new HijriCalendar()); case CalendarId.HEBREW: // Hebrew (Lunar) calendar return (new HebrewCalendar()); case CalendarId.UMALQURA: return (new UmAlQuraCalendar()); case CalendarId.PERSIAN: return (new PersianCalendar()); } return (new GregorianCalendar()); } /*=================================Calendar========================== **Action: Return/set the default calendar used by this culture. ** This value can be overridden by regional option if this is a current culture. **Returns: **Arguments: **Exceptions: ** ArgumentNull_Obj if the set value is null. ============================================================================*/ public virtual Calendar Calendar { get { if (_calendar == null) { Debug.Assert(this._cultureData.CalendarIds.Length > 0, "this._cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = this._cultureData.DefaultCalendar; System.Threading.Interlocked.MemoryBarrier(); newObj.SetReadOnlyState(_isReadOnly); _calendar = newObj; } return (_calendar); } } /*=================================OptionCalendars========================== **Action: Return an array of the optional calendar for this culture. **Returns: an array of Calendar. **Arguments: **Exceptions: ============================================================================*/ public virtual Calendar[] OptionalCalendars { get { Contract.Ensures(Contract.Result<Calendar[]>() != null); // // This property always returns a new copy of the calendar array. // CalendarId[] calID = this._cultureData.CalendarIds; Calendar[] cals = new Calendar[calID.Length]; for (int i = 0; i < cals.Length; i++) { cals[i] = GetCalendarInstance(calID[i]); } return (cals); } } public bool UseUserOverride { get { return _cultureData.UseUserOverride; } } public CultureInfo GetConsoleFallbackUICulture() { Contract.Ensures(Contract.Result<CultureInfo>() != null); CultureInfo temp = m_consoleFallbackCulture; if (temp == null) { temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); temp._isReadOnly = true; m_consoleFallbackCulture = temp; } return (temp); } public virtual Object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!_isInherited) { if (this.dateTimeInfo != null) { ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone(); } if (this.numInfo != null) { ci.numInfo = (NumberFormatInfo)this.numInfo.Clone(); } } else { ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone(); ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone(); } if (_textInfo != null) { ci._textInfo = (TextInfo)_textInfo.Clone(); } if (_calendar != null) { ci._calendar = (Calendar)_calendar.Clone(); } return (ci); } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException(nameof(ci)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); if (ci.IsReadOnly) { return (ci); } CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone()); if (!ci.IsNeutralCulture) { //If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless //they've already been allocated. If this is a derived type, we'll take a more generic codepath. if (!ci._isInherited) { if (ci.dateTimeInfo != null) { newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo); } if (ci.numInfo != null) { newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo); } } else { newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { newInfo._calendar = Calendar.ReadOnly(ci._calendar); } // Don't set the read-only flag too early. // We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set. newInfo._isReadOnly = true; return (newInfo); } public bool IsReadOnly { get { return (_isReadOnly); } } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } // For resource lookup, we consider a culture the invariant culture by name equality. // We perform this check frequently during resource lookup, so adding a property for // improved readability. internal bool HasInvariantCultureName { get { return Name == CultureInfo.InvariantCulture.Name; } } // Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name. // If lcid is -1, use the altName and create one of those special SQL cultures. internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName) { // retval is our return value. CultureInfo retval; // Temporary hashtable for the names. LowLevelDictionary<string, CultureInfo> tempNameHT = s_NameCachedCultures; if (name != null) { name = CultureData.AnsiToLower(name); } if (altName != null) { altName = CultureData.AnsiToLower(altName); } // We expect the same result for both hashtables, but will test individually for added safety. if (tempNameHT == null) { tempNameHT = new LowLevelDictionary<string, CultureInfo>(); } else { // If we are called by name, check if the object exists in the hashtable. If so, return it. if (lcid == -1 || lcid == 0) { bool ret; using (LockHolder.Hold(s_lock)) { ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval); } if (ret && retval != null) { return retval; } } } // Next, the Lcid table. LowLevelDictionary<int, CultureInfo> tempLcidHT = s_LcidCachedCultures; if (tempLcidHT == null) { // Case insensitive is not an issue here, save the constructor call. tempLcidHT = new LowLevelDictionary<int, CultureInfo>(); } else { // If we were called by Lcid, check if the object exists in the table. If so, return it. if (lcid > 0) { bool ret; using (LockHolder.Hold(s_lock)) { ret = tempLcidHT.TryGetValue(lcid, out retval); } if (ret && retval != null) { return retval; } } } // We now have two temporary hashtables and the desired object was not found. // We'll construct it. We catch any exceptions from the constructor call and return null. try { switch (lcid) { case -1: // call the private constructor retval = new CultureInfo(name, altName); break; case 0: retval = new CultureInfo(name, false); break; default: retval = new CultureInfo(lcid, false); break; } } catch (ArgumentException) { return null; } // Set it to read-only retval._isReadOnly = true; if (lcid == -1) { using (LockHolder.Hold(s_lock)) { // This new culture will be added only to the name hash table. tempNameHT[name + '\xfffd' + altName] = retval; } // when lcid == -1 then TextInfo object is already get created and we need to set it as read only. retval.TextInfo.SetReadOnlyState(true); } else if (lcid == 0) { // Remember our name (as constructed). Do NOT use alternate sort name versions because // we have internal state representing the sort. (So someone would get the wrong cached version) string newName = CultureData.AnsiToLower(retval.m_name); // We add this new culture info object to both tables. using (LockHolder.Hold(s_lock)) { tempNameHT[newName] = retval; } } else { using (LockHolder.Hold(s_lock)) { tempLcidHT[lcid] = retval; } } // Copy the two hashtables to the corresponding member variables. This will potentially overwrite // new tables simultaneously created by a new thread, but maximizes thread safety. if (-1 != lcid) { // Only when we modify the lcid hash table, is there a need to overwrite. s_LcidCachedCultures = tempLcidHT; } s_NameCachedCultures = tempNameHT; // Finally, return our new CultureInfo object. return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (LCID version)... use named version public static CultureInfo GetCultureInfo(int culture) { // Must check for -1 now since the helper function uses the value to signal // the altCulture code path for SQL Server. // Also check for zero as this would fail trying to add as a key to the hash. if (culture <= 0) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(culture, null, null); if (null == retval) { throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). (Named version) public static CultureInfo GetCultureInfo(string name) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } CultureInfo retval = GetCultureInfoHelper(0, name, null); if (retval == null) { throw new CultureNotFoundException( nameof(name), name, SR.Argument_CultureNotSupported); } return retval; } // Gets a cached copy of the specified culture from an internal hashtable (or creates it // if not found). public static CultureInfo GetCultureInfo(string name, string altName) { // Make sure we have a valid, non-zero length string as name if (name == null) { throw new ArgumentNullException(nameof(name)); } if (altName == null) { throw new ArgumentNullException(nameof(altName)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) { throw new CultureNotFoundException("name or altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } return retval; } // This function is deprecated, we don't like it public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { Contract.Ensures(Contract.Result<CultureInfo>() != null); // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo ci = GetCultureInfo(name); // Disallow alt sorts and es-es_TS if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return ci; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography { internal static partial class CngPkcs8 { // Windows 7, 8, and 8.1 don't support PBES2 export, so use // the 3DES-192 scheme from PKCS12-PBE whenever deferring to the system. // // Since we're going to immediately re-encrypt the value when using this, // and still have the password in memory while it's running, // just use one iteration in the KDF and cut down on the CPU time involved. private static readonly PbeParameters s_platformParameters = new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 1); internal static bool IsPlatformScheme(PbeParameters pbeParameters) { Debug.Assert(pbeParameters != null); return pbeParameters.EncryptionAlgorithm == s_platformParameters.EncryptionAlgorithm && pbeParameters.HashAlgorithm == s_platformParameters.HashAlgorithm; } internal static byte[] ExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException(nameof(pbeParameters)); } PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); if (passwordBytes.Length == 0) { // Switch to character-based, since that's the native input format. return key.ExportEncryptedPkcs8PrivateKey(ReadOnlySpan<char>.Empty, pbeParameters); } using (AsnWriter writer = RewriteEncryptedPkcs8PrivateKey(key, passwordBytes, pbeParameters)) { return writer.Encode(); } } internal static bool TryExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (passwordBytes.Length == 0) { // Switch to character-based, since that's the native input format. return key.TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char>.Empty, pbeParameters, destination, out bytesWritten); } using (AsnWriter writer = RewriteEncryptedPkcs8PrivateKey(key, passwordBytes, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } internal static byte[] ExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<char> password, PbeParameters pbeParameters) { using (AsnWriter writer = RewriteEncryptedPkcs8PrivateKey(key, password, pbeParameters)) { return writer.Encode(); } } internal static bool TryExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { using (AsnWriter writer = RewriteEncryptedPkcs8PrivateKey(key, password, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } internal static unsafe Pkcs8Response ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { int len; fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); len = reader.ReadEncodedValue().Length; } } bytesRead = len; return ImportPkcs8(source.Slice(0, len)); } internal static unsafe Pkcs8Response ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { // Since there's no bytes-based-password PKCS8 import in CNG, just do the decryption // here and call the unencrypted PKCS8 import. ArraySegment<byte> decrypted = KeyFormatHelper.DecryptPkcs8( passwordBytes, manager.Memory, out bytesRead); Span<byte> decryptedSpan = decrypted; try { return ImportPkcs8(decryptedSpan); } catch (CryptographicException e) { throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e); } finally { CryptographicOperations.ZeroMemory(decryptedSpan); CryptoPool.Return(decrypted.Array); } } } } internal static unsafe Pkcs8Response ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); int len = reader.ReadEncodedValue().Length; source = source.Slice(0, len); try { bytesRead = len; return ImportPkcs8(source, password); } catch (CryptographicException) { } ArraySegment<byte> decrypted = KeyFormatHelper.DecryptPkcs8( password, manager.Memory.Slice(0, len), out int innerRead); Span<byte> decryptedSpan = decrypted; try { if (innerRead != len) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } bytesRead = len; return ImportPkcs8(decryptedSpan); } catch (CryptographicException e) { throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e); } finally { CryptographicOperations.ZeroMemory(decryptedSpan); CryptoPool.Return(decrypted.Array, clearSize: 0); } } } } private static AsnWriter RewriteEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { Debug.Assert(pbeParameters != null); // For RSA: // * 512-bit key needs ~400 bytes // * 16384-bit key needs ~10k bytes. // * KeySize (bits) should avoid re-rent. // // For DSA: // * 512-bit key needs ~300 bytes. // * 1024-bit key needs ~400 bytes. // * 2048-bit key needs ~700 bytes. // * KeySize (bits) should avoid re-rent. // // For ECC: // * secp256r1 needs ~200 bytes (named) or ~450 (explicit) // * secp384r1 needs ~250 bytes (named) or ~600 (explicit) // * secp521r1 needs ~300 bytes (named) or ~730 (explicit) // * KeySize (bits) should avoid re-rent for named, and probably // gets one re-rent for explicit. byte[] rented = CryptoPool.Rent(key.KeySize); int rentWritten = 0; // If we use 6 bits from each byte, that's 22 * 6 = 132 Span<char> randomString = stackalloc char[22]; try { FillRandomAsciiString(randomString); while (!key.TryExportEncryptedPkcs8PrivateKey( randomString, s_platformParameters, rented, out rentWritten)) { int size = rented.Length; byte[] current = rented; rented = CryptoPool.Rent(checked(size * 2)); CryptoPool.Return(current, rentWritten); } return KeyFormatHelper.ReencryptPkcs8( randomString, rented.AsMemory(0, rentWritten), passwordBytes, pbeParameters); } finally { randomString.Clear(); CryptoPool.Return(rented, rentWritten); } } private static AsnWriter RewriteEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan<char> password, PbeParameters pbeParameters) { Debug.Assert(pbeParameters != null); byte[] rented = CryptoPool.Rent(key.KeySize); int rentWritten = 0; try { while (!key.TryExportEncryptedPkcs8PrivateKey( password, s_platformParameters, rented, out rentWritten)) { int size = rented.Length; byte[] current = rented; rented = CryptoPool.Rent(checked(size * 2)); CryptoPool.Return(current, rentWritten); } return KeyFormatHelper.ReencryptPkcs8( password, rented.AsMemory(0, rentWritten), password, pbeParameters); } finally { CryptoPool.Return(rented, rentWritten); } } private static void FillRandomAsciiString(Span<char> destination) { Debug.Assert(destination.Length < 128); Span<byte> randomKey = stackalloc byte[destination.Length]; RandomNumberGenerator.Fill(randomKey); for (int i = 0; i < randomKey.Length; i++) { // 33 (!) up to 33 + 63 = 96 (`) destination[i] = (char)(33 + (randomKey[i] & 0b0011_1111)); } } } }
using Microsoft.Extensions.Logging; using System; namespace Orleans.Runtime { /// <summary> /// Extension methods which preserves legacy orleans log methods style /// </summary> public static class OrleansLoggerExtension { /// <summary> /// Writes a log entry at the Debug severity level. /// </summary> /// <param name="logger">The logger</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Debug(this ILogger logger, string format, params object[] args) { logger.LogDebug(format, args); } /// <summary> /// Writes a log entry at the Verbose severity level. /// Verbose is suitable for debugging information that should usually not be logged in production. /// Verbose is lower than Info. /// </summary> /// <param name="logger">The logger</param> /// <param name="message">The log message.</param> public static void Debug(this ILogger logger, string message) { logger.LogDebug(message); } /// <summary> /// Writes a log entry at the Trace logLevel. /// </summary> /// <param name="logger">The logger</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Trace(this ILogger logger, string format, params object[] args) { logger.LogTrace(format, args); } /// <summary> /// Writes a log entry at the Verbose2 severity level. /// Verbose2 is lower than Verbose. /// </summary> /// <param name="logger">The logger</param> /// <param name="message">The log message.</param> public static void Trace(this ILogger logger, string message) { logger.LogTrace(message); } /// <summary> /// Writes a log entry at the Information Level /// </summary> /// <param name="logger">Target logger.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Info(this ILogger logger, string format, params object[] args) { logger.LogInformation(format, args); } /// <summary> /// Writes a log entry at the Info logLevel /// </summary> /// <param name="logger">Target logger.</param> /// <param name="message">The log message.</param> public static void Info(this ILogger logger, string message) { logger.LogInformation(message); } /// <summary> /// Writes a log entry at the Debug logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Debug(this ILogger logger, int logCode, string format, params object[] args) { logger.LogDebug(logCode, format, args); } public static void Debug(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogDebug(new EventId((int)logCode), format, args); } /// <summary> /// Writes a log entry at the Debug logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Debug(this ILogger logger, int logCode, string message) { logger.LogDebug(logCode, message); } public static void Debug(this ILogger logger, ErrorCode logCode, string message) { logger.LogDebug(new EventId((int)logCode), message); } /// <summary> /// Writes a log entry at the Trace logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Trace(this ILogger logger, int logCode, string format, params object[] args) { logger.LogTrace(logCode, format, args); } public static void Trace(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogTrace(new EventId((int)logCode), format, args); } /// <summary> /// Writes a log entry at the Trace logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Trace(this ILogger logger, int logCode, string message) { logger.LogTrace(logCode, message); } public static void Trace(this ILogger logger, ErrorCode logCode, string message) { logger.LogTrace(new EventId((int)logCode), message); } /// <summary> /// Writes a log entry at the Information logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Info(this ILogger logger, int logCode, string format, params object[] args) { logger.LogInformation(logCode, format, args); } public static void Info(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogInformation(new EventId((int)logCode), format, args); } /// <summary> /// Writes a log entry at the Information logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Info(this ILogger logger, int logCode, string message) { logger.LogInformation(logCode, message); } public static void Info(this ILogger logger, ErrorCode logCode, string message) { logger.LogInformation(new EventId((int)logCode), message); } /// <summary> /// Writes a log entry at the Warning level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Warn(this ILogger logger, int logCode, string format, params object[] args) { logger.LogWarning(logCode, format, args); } public static void Warn(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogWarning(new EventId((int)logCode), format, args); } /// <summary> /// Writes a log entry at the Warning level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The warning message to log.</param> /// <param name="exception">An exception related to the warning, if any.</param> public static void Warn(this ILogger logger, int logCode, string message, Exception exception = null) { logger.LogWarning(logCode, exception, message); } public static void Warn(this ILogger logger, ErrorCode logCode, string message, Exception exception = null) { logger.LogWarning(new EventId((int)logCode), exception, message); } /// <summary> /// Writes a log entry at the Error level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The error message to log.</param> /// <param name="exception">An exception related to the error, if any.</param> public static void Error(this ILogger logger, int logCode, string message, Exception exception = null) { logger.LogError(logCode, exception, message); } public static void Error(this ILogger logger, ErrorCode logCode, string message, Exception exception = null) { logger.LogError(new EventId((int)logCode), exception, message); } } }
namespace AutoMapper { using System; using System.ComponentModel; using System.Linq.Expressions; /// <summary> /// Mapping configuration options for non-generic maps /// </summary> public interface IMappingExpression { /// <summary> /// Preserve object identity. Useful for circular references. /// </summary> /// <returns></returns> IMappingExpression PreserveReferences(); /// <summary> /// Customize configuration for individual constructor parameter /// </summary> /// <param name="ctorParamName">Constructor parameter name</param> /// <param name="paramOptions">Options</param> /// <returns>Itself</returns> IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions); /// <summary> /// Create a type mapping from the destination to the source type, using the destination members as validation. /// </summary> /// <returns>Itself</returns> IMappingExpression ReverseMap(); /// <summary> /// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types. /// The returned source object will be mapped instead of what was supplied in the original source object. /// </summary> /// <param name="substituteFunc">Substitution function</param> /// <returns>New source object to map.</returns> IMappingExpression Substitute(Func<object, object> substituteFunc); /// <summary> /// Construct the destination object using the service locator /// </summary> /// <returns>Itself</returns> IMappingExpression ConstructUsingServiceLocator(); /// <summary> /// For self-referential types, limit recurse depth. /// Enables PreserveReferences. /// </summary> /// <param name="depth">Number of levels to limit to</param> /// <returns>Itself</returns> IMappingExpression MaxDepth(int depth); /// <summary> /// Supply a custom instantiation expression for the destination type for LINQ projection /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression ConstructProjectionUsing(LambdaExpression ctor); /// <summary> /// Supply a custom instantiation function for the destination type, based on the entire resolution context /// </summary> /// <param name="ctor">Callback to create the destination type given the source object and current resolution context</param> /// <returns>Itself</returns> IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor); /// <summary> /// Supply a custom instantiation function for the destination type /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression ConstructUsing(Func<object, object> ctor); /// <summary> /// Skip member mapping and use a custom expression during LINQ projection /// </summary> /// <param name="projectionExpression">Projection expression</param> void ProjectUsing(Expression<Func<object, object>> projectionExpression); /// <summary> /// Customize configuration for all members /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions); /// <summary> /// Customize configuration for members not previously configured /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions); /// <summary> /// Customize configuration for an individual source member /// </summary> /// <param name="sourceMemberName">Source member name</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping /// </summary> /// <typeparam name="TTypeConverter">Type converter type</typeparam> void ConvertUsing<TTypeConverter>(); /// <summary> /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping /// Use this method if you need to specify the converter type at runtime /// </summary> /// <param name="typeConverterType">Type converter type</param> void ConvertUsing(Type typeConverterType); /// <summary> /// Override the destination type mapping for looking up configuration and instantiation /// </summary> /// <param name="typeOverride"></param> void As(Type typeOverride); /// <summary> /// Customize individual members /// </summary> /// <param name="name">Name of the member</param> /// <param name="memberOptions">Callback for configuring member</param> /// <returns>Itself</returns> IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <param name="derivedSourceType">Derived source type</param> /// <param name="derivedDestinationType">Derived destination type</param> /// <returns>Itself</returns> IMappingExpression Include(Type derivedSourceType, Type derivedDestinationType); /// <summary> /// Ignores all destination properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter) /// </summary> /// <returns>Itself</returns> IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter(); /// <summary> /// When using ReverseMap, ignores all source properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: destination properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used) /// </summary> /// <returns>Itself</returns> IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); /// <summary> /// Include the base type map's configuration in this map /// </summary> /// <param name="sourceBase">Base source type</param> /// <param name="destinationBase">Base destination type</param> /// <returns></returns> IMappingExpression IncludeBase(Type sourceBase, Type destinationBase); /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression BeforeMap(Action<object, object> beforeFunction); /// <summary> /// Execute a custom mapping action before member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>; /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression AfterMap(Action<object, object> afterFunction); /// <summary> /// Execute a custom mapping action after member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>; } /// <summary> /// Mapping configuration options /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> public interface IMappingExpression<TSource, TDestination> { /// <summary> /// Preserve object identity. Useful for circular references. /// </summary> /// <returns></returns> IMappingExpression<TSource, TDestination> PreserveReferences(); /// <summary> /// Customize configuration for members not previously configured /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions); /// <summary> /// Customize configuration for individual member /// </summary> /// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type /// <param name="memberOptions">Callback for member options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember, Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions); /// <summary> /// Customize configuration for individual member. Used when the name isn't known at compile-time /// </summary> /// <param name="name">Destination member name</param> /// <param name="memberOptions">Callback for member options</param> /// <returns></returns> IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions); /// <summary> /// Customize configuration for all members /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions); /// <summary> /// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter) /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter(); /// <summary> /// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used) /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <typeparam name="TOtherSource">Derived source type</typeparam> /// <typeparam name="TOtherDestination">Derived destination type</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination; /// <summary> /// Include the base type map's configuration in this map /// </summary> /// <typeparam name="TSourceBase">Base source type</typeparam> /// <typeparam name="TDestinationBase">Base destination type</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>(); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <param name="derivedSourceType">Derived source type</param> /// <param name="derivedDestinationType">Derived destination type</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType); /// <summary> /// Skip member mapping and use a custom expression during LINQ projection /// </summary> /// <param name="projectionExpression">Projection expression</param> void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <param name="mappingFunction">Callback to convert from source type to destination type</param> void ConvertUsing(Func<TSource, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <param name="mappingFunction">Callback to convert from source type to destination type</param> void ConvertUsing(Func<TSource, ResolutionContext, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <param name="converter">Type converter instance</param> void ConvertUsing(ITypeConverter<TSource, TDestination> converter); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <typeparam name="TTypeConverter">Type converter type</typeparam> void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>; /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction); /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction); /// <summary> /// Execute a custom mapping action before member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction); /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction); /// <summary> /// Execute a custom mapping action after member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Supply a custom instantiation function for the destination type /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor); /// <summary> /// Supply a custom instantiation expression for the destination type for LINQ projection /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor); /// <summary> /// Supply a custom instantiation function for the destination type, based on the entire resolution context /// </summary> /// <param name="ctor">Callback to create the destination type given the current resolution context</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor); /// <summary> /// Override the destination type mapping for looking up configuration and instantiation /// </summary> /// <typeparam name="T">Destination type to use</typeparam> void As<T>(); /// <summary> /// For self-referential types, limit recurse depth. /// Enables PreserveReferences. /// </summary> /// <param name="depth">Number of levels to limit to</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> MaxDepth(int depth); /// <summary> /// Construct the destination object using the service locator /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator(); /// <summary> /// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation /// </summary> /// <returns>Itself</returns> IMappingExpression<TDestination, TSource> ReverseMap(); /// <summary> /// Customize configuration for an individual source member /// </summary> /// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Customize configuration for an individual source member. Member name not known until runtime /// </summary> /// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types. /// The returned source object will be mapped instead of what was supplied in the original source object. /// </summary> /// <param name="substituteFunc">Substitution function</param> /// <returns>New source object to map.</returns> IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc); /// <summary> /// Customize configuration for individual constructor parameter /// </summary> /// <param name="ctorParamName">Constructor parameter name</param> /// <param name="paramOptions">Options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Game.Replays; using osu.Game.Rulesets.Replays; namespace osu.Game.Tests.NonVisual { [TestFixture] public class FramedReplayInputHandlerTest { private Replay replay; private TestInputHandler handler; [SetUp] public void SetUp() { handler = new TestInputHandler(replay = new Replay { Frames = new List<ReplayFrame> { new TestReplayFrame(0), new TestReplayFrame(1000), new TestReplayFrame(2000), new TestReplayFrame(3000, true), new TestReplayFrame(4000, true), new TestReplayFrame(5000, true), new TestReplayFrame(7000, true), new TestReplayFrame(8000), } }); } [Test] public void TestNormalPlayback() { Assert.IsNull(handler.CurrentFrame); confirmCurrentFrame(null); confirmNextFrame(0); setTime(0, 0); confirmCurrentFrame(0); confirmNextFrame(1); //if we hit the first frame perfectly, time should progress to it. setTime(1000, 1000); confirmCurrentFrame(1); confirmNextFrame(2); //in between non-important frames should progress based on input. setTime(1200, 1200); confirmCurrentFrame(1); setTime(1400, 1400); confirmCurrentFrame(1); // progressing beyond the next frame should force time to that frame once. setTime(2200, 2000); confirmCurrentFrame(2); // second attempt should progress to input time setTime(2200, 2200); confirmCurrentFrame(2); // entering important section setTime(3000, 3000); confirmCurrentFrame(3); // cannot progress within setTime(3500, null); confirmCurrentFrame(3); setTime(4000, 4000); confirmCurrentFrame(4); // still cannot progress setTime(4500, null); confirmCurrentFrame(4); setTime(5200, 5000); confirmCurrentFrame(5); // important section AllowedImportantTimeSpan allowance setTime(5200, 5200); confirmCurrentFrame(5); setTime(7200, 7000); confirmCurrentFrame(6); setTime(7200, null); confirmCurrentFrame(6); // exited important section setTime(8200, 8000); confirmCurrentFrame(7); confirmNextFrame(null); setTime(8200, 8200); confirmCurrentFrame(7); confirmNextFrame(null); } [Test] public void TestIntroTime() { setTime(-1000, -1000); confirmCurrentFrame(null); confirmNextFrame(0); setTime(-500, -500); confirmCurrentFrame(null); confirmNextFrame(0); setTime(0, 0); confirmCurrentFrame(0); confirmNextFrame(1); } [Test] public void TestBasicRewind() { setTime(2800, 0); setTime(2800, 1000); setTime(2800, 2000); setTime(2800, 2800); confirmCurrentFrame(2); confirmNextFrame(3); // pivot without crossing a frame boundary setTime(2700, 2700); confirmCurrentFrame(2); confirmNextFrame(1); // cross current frame boundary; should not yet update frame setTime(1980, 1980); confirmCurrentFrame(2); confirmNextFrame(1); setTime(1200, 1200); confirmCurrentFrame(2); confirmNextFrame(1); //ensure each frame plays out until start setTime(-500, 1000); confirmCurrentFrame(1); confirmNextFrame(0); setTime(-500, 0); confirmCurrentFrame(0); confirmNextFrame(null); setTime(-500, -500); confirmCurrentFrame(0); confirmNextFrame(null); } [Test] public void TestRewindInsideImportantSection() { fastForwardToPoint(3000); setTime(4000, 4000); confirmCurrentFrame(4); confirmNextFrame(5); setTime(3500, null); confirmCurrentFrame(4); confirmNextFrame(3); setTime(3000, 3000); confirmCurrentFrame(3); confirmNextFrame(2); setTime(3500, null); confirmCurrentFrame(3); confirmNextFrame(4); setTime(4000, 4000); confirmCurrentFrame(4); confirmNextFrame(5); setTime(4500, null); confirmCurrentFrame(4); confirmNextFrame(5); setTime(4000, null); confirmCurrentFrame(4); confirmNextFrame(5); setTime(3500, null); confirmCurrentFrame(4); confirmNextFrame(3); setTime(3000, 3000); confirmCurrentFrame(3); confirmNextFrame(2); } [Test] public void TestRewindOutOfImportantSection() { fastForwardToPoint(3500); confirmCurrentFrame(3); confirmNextFrame(4); setTime(3200, null); // next frame doesn't change even though direction reversed, because of important section. confirmCurrentFrame(3); confirmNextFrame(4); setTime(3000, null); confirmCurrentFrame(3); confirmNextFrame(4); setTime(2800, 2800); confirmCurrentFrame(3); confirmNextFrame(2); } private void fastForwardToPoint(double destination) { for (int i = 0; i < 1000; i++) { if (handler.SetFrameFromTime(destination) == null) return; } throw new TimeoutException("Seek was never fulfilled"); } private void setTime(double set, double? expect) { Assert.AreEqual(expect, handler.SetFrameFromTime(set)); } private void confirmCurrentFrame(int? frame) { if (frame.HasValue) { Assert.IsNotNull(handler.CurrentFrame); Assert.AreEqual(replay.Frames[frame.Value].Time, handler.CurrentFrame.Time); } else { Assert.IsNull(handler.CurrentFrame); } } private void confirmNextFrame(int? frame) { if (frame.HasValue) { Assert.IsNotNull(handler.NextFrame); Assert.AreEqual(replay.Frames[frame.Value].Time, handler.NextFrame.Time); } else { Assert.IsNull(handler.NextFrame); } } private class TestReplayFrame : ReplayFrame { public readonly bool IsImportant; public TestReplayFrame(double time, bool isImportant = false) : base(time) { IsImportant = isImportant; } } private class TestInputHandler : FramedReplayInputHandler<TestReplayFrame> { public TestInputHandler(Replay replay) : base(replay) { FrameAccuratePlayback = true; } protected override double AllowedImportantTimeSpan => 1000; protected override bool IsImportant(TestReplayFrame frame) => frame.IsImportant; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ForumSystem.Services.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (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.Linq; using EnvDTE; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeClassTests : AbstractFileCodeElementTests { public FileCodeClassTests() : base(@"using System; public abstract class Foo : IDisposable, ICloneable { } [Serializable] public class Bar { int a; public int A { get { return a; } } }") { } private CodeClass GetCodeClass(params object[] path) { return (CodeClass)GetCodeElement(path); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void IsAbstract() { CodeClass cc = GetCodeClass("Foo"); Assert.True(cc.IsAbstract); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Bases() { CodeClass cc = GetCodeClass("Foo"); var bases = cc.Bases; Assert.Equal(bases.Count, 1); Assert.Equal(bases.Cast<CodeElement>().Count(), 1); Assert.NotNull(bases.Parent); var parentClass = bases.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal(parentClass.FullName, "Foo"); Assert.True(bases.Item("object") is CodeClass); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void ImplementedInterfaces() { CodeClass cc = GetCodeClass("Foo"); var interfaces = cc.ImplementedInterfaces; Assert.Equal(interfaces.Count, 2); Assert.Equal(interfaces.Cast<CodeElement>().Count(), 2); Assert.NotNull(interfaces.Parent); var parentClass = interfaces.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal(parentClass.FullName, "Foo"); Assert.True(interfaces.Item("System.IDisposable") is CodeInterface); Assert.True(interfaces.Item("ICloneable") is CodeInterface); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void KindTest() { CodeClass cc = GetCodeClass("Foo"); Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody); Assert.Equal(10, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader); Assert.Equal(8, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, startPoint.Line); Assert.Equal(14, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { CodeClass testObject = GetCodeClass("Bar"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, endPoint.Line); Assert.Equal(15, endPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { CodeClass testObject = GetCodeClass("Bar"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody); Assert.Equal(19, endPoint.Line); Assert.Equal(1, endPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { CodeClass testObject = GetCodeClass("Bar"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, endPoint.Line); Assert.Equal(17, endPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { CodeClass testObject = GetCodeClass("Bar"); AssertEx.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole)); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { CodeClass testObject = GetCodeClass("Bar"); TextPoint endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(19, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { CodeClass testObject = GetCodeClass("Bar"); TextPoint startPoint = testObject.StartPoint; Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [ConditionalFact(typeof(x86))] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { CodeClass testObject = GetCodeClass("Bar"); TextPoint endPoint = testObject.EndPoint; Assert.Equal(19, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } } }
//----------------------------------------------------------------------- // <copyright file="DynamicApis.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, mail@rsuter.com</author> //----------------------------------------------------------------------- using Namotion.Reflection; using System; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace NJsonSchema.Infrastructure { /// <summary>Provides dynamic access to framework APIs.</summary> public static class DynamicApis { private static readonly Type XPathExtensionsType; private static readonly Type FileType; private static readonly Type DirectoryType; private static readonly Type PathType; private static readonly Type HttpClientHandlerType; private static readonly Type HttpClientType; static DynamicApis() { XPathExtensionsType = TryLoadType( "System.Xml.XPath.Extensions, System.Xml.XPath.XDocument", "System.Xml.XPath.Extensions, System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); HttpClientHandlerType = TryLoadType( "System.Net.Http.HttpClientHandler, System.Net.Http", "System.Net.Http.HttpClientHandler, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); HttpClientType = TryLoadType( "System.Net.Http.HttpClient, System.Net.Http", "System.Net.Http.HttpClient, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); FileType = TryLoadType("System.IO.File, System.IO.FileSystem", "System.IO.File"); DirectoryType = TryLoadType("System.IO.Directory, System.IO.FileSystem", "System.IO.Directory"); PathType = TryLoadType("System.IO.Path, System.IO.FileSystem", "System.IO.Path"); } /// <summary>Gets a value indicating whether file APIs are available.</summary> public static bool SupportsFileApis => FileType != null; /// <summary>Gets a value indicating whether path APIs are available.</summary> public static bool SupportsPathApis => PathType != null; /// <summary>Gets a value indicating whether path APIs are available.</summary> public static bool SupportsDirectoryApis => DirectoryType != null; /// <summary>Gets a value indicating whether XPath APIs are available.</summary> public static bool SupportsXPathApis => XPathExtensionsType != null; /// <summary>Gets a value indicating whether WebClient APIs are available.</summary> public static bool SupportsHttpClientApis => HttpClientType != null; /// <summary>Request the given URL via HTTP.</summary> /// <param name="url">The URL.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The content.</returns> /// <exception cref="NotSupportedException">The HttpClient.GetAsync API is not available on this platform.</exception> public static async Task<string> HttpGetAsync(string url, CancellationToken cancellationToken) { if (!SupportsHttpClientApis) { throw new NotSupportedException("The System.Net.Http.HttpClient API is not available on this platform."); } using (dynamic handler = (IDisposable)Activator.CreateInstance(HttpClientHandlerType)) using (dynamic client = (IDisposable)Activator.CreateInstance(HttpClientType, new[] { handler })) { handler.UseDefaultCredentials = true; var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync().ConfigureAwait(false); } } /// <summary>Gets the current working directory.</summary> /// <returns>The directory path.</returns> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static string DirectoryGetCurrentDirectory() { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } return (string)DirectoryType.GetRuntimeMethod("GetCurrentDirectory", new Type[] { }).Invoke(null, new object[] { }); } /// <summary>Gets the current working directory.</summary> /// <returns>The directory path.</returns> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static string[] DirectoryGetDirectories(string directory) { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } return (string[])DirectoryType.GetRuntimeMethod("GetDirectories", new[] { typeof(string) }).Invoke(null, new object[] { directory }); } /// <summary>Gets the files of the given directory.</summary> /// <param name="directory">The directory.</param> /// <param name="filter">The filter.</param> /// <returns>The file paths.</returns> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static string[] DirectoryGetFiles(string directory, string filter) { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } return (string[])DirectoryType.GetRuntimeMethod("GetFiles", new[] { typeof(string), typeof(string) }).Invoke(null, new object[] { directory, filter }); } /// <summary>Retrieves the parent directory of the specified path, including both absolute and relative paths..</summary> /// <returns>The directory path.</returns> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static string DirectoryGetParent(string path) { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } return DirectoryType.GetRuntimeMethod("GetParent", new[] { typeof(string) }).Invoke(null, new object[] { path }).TryGetPropertyValue<string>("FullName"); } /// <summary>Creates a directory.</summary> /// <param name="directory">The directory.</param> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static void DirectoryCreateDirectory(string directory) { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } DirectoryType.GetRuntimeMethod("CreateDirectory", new[] { typeof(string) }).Invoke(null, new object[] { directory }); } /// <summary>Checks whether a directory exists.</summary> /// <param name="filePath">The file path.</param> /// <returns>true or false</returns> /// <exception cref="NotSupportedException">The System.IO.Directory API is not available on this platform.</exception> public static bool DirectoryExists(string filePath) { if (!SupportsDirectoryApis) { throw new NotSupportedException("The System.IO.Directory API is not available on this platform."); } if (string.IsNullOrEmpty(filePath)) { return false; } return (bool)DirectoryType.GetRuntimeMethod("Exists", new[] { typeof(string) }).Invoke(null, new object[] { filePath }); } /// <summary>Checks whether a file exists.</summary> /// <param name="filePath">The file path.</param> /// <returns>true or false</returns> /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception> public static bool FileExists(string filePath) { if (!SupportsFileApis) { throw new NotSupportedException("The System.IO.File API is not available on this platform."); } if (string.IsNullOrEmpty(filePath)) { return false; } return (bool)FileType.GetRuntimeMethod("Exists", new[] { typeof(string) }).Invoke(null, new object[] { filePath }); } /// <summary>Reads all content of a file (UTF8 with or without BOM).</summary> /// <param name="filePath">The file path.</param> /// <returns>The file content.</returns> /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception> public static string FileReadAllText(string filePath) { if (!SupportsFileApis) { throw new NotSupportedException("The System.IO.File API is not available on this platform."); } return (string)FileType.GetRuntimeMethod("ReadAllText", new[] { typeof(string), typeof(Encoding) }).Invoke(null, new object[] { filePath, Encoding.UTF8 }); } /// <summary>Writes text to a file (UTF8 without BOM).</summary> /// <param name="filePath">The file path.</param> /// <param name="text">The text.</param> /// <returns></returns> /// <exception cref="NotSupportedException">The System.IO.File API is not available on this platform.</exception> public static void FileWriteAllText(string filePath, string text) { if (!SupportsFileApis) { throw new NotSupportedException("The System.IO.File API is not available on this platform."); } // Default of encoding is StreamWriter.UTF8NoBOM FileType.GetRuntimeMethod("WriteAllText", new[] { typeof(string), typeof(string) }).Invoke(null, new object[] { filePath, text }); } /// <summary>Combines two paths.</summary> /// <param name="path1">The path1.</param> /// <param name="path2">The path2.</param> /// <returns>The combined path.</returns> /// <exception cref="NotSupportedException">The System.IO.Path API is not available on this platform.</exception> public static string PathCombine(string path1, string path2) { if (!SupportsPathApis) { throw new NotSupportedException("The System.IO.Path API is not available on this platform."); } return (string)PathType.GetRuntimeMethod("Combine", new[] { typeof(string), typeof(string) }).Invoke(null, new object[] { path1, path2 }); } /// <summary>Gets the file name from a given path.</summary> /// <param name="filePath">The file path.</param> /// <returns>The directory name.</returns> /// <exception cref="NotSupportedException">The System.IO.Path API is not available on this platform.</exception> public static string PathGetFileName(string filePath) { if (!SupportsPathApis) { throw new NotSupportedException("The System.IO.Path API is not available on this platform."); } return (string)PathType.GetRuntimeMethod("GetFileName", new[] { typeof(string) }).Invoke(null, new object[] { filePath }); } /// <summary>Gets the full path from a given path</summary> /// <param name="path">The path</param> /// <returns>The full path</returns> /// <exception cref="NotSupportedException">The System.IO.Path API is not available on this platform.</exception> public static string GetFullPath(string path) { if (!SupportsPathApis) { throw new NotSupportedException("The System.IO.Path API is not available on this platform."); } return (string)PathType.GetRuntimeMethod("GetFullPath", new[] { typeof(string) }).Invoke(null, new object[] { path }); } /// <summary>Gets the directory path of a file path.</summary> /// <param name="filePath">The file path.</param> /// <returns>The directory name.</returns> /// <exception cref="NotSupportedException">The System.IO.Path API is not available on this platform.</exception> public static string PathGetDirectoryName(string filePath) { if (!SupportsPathApis) { throw new NotSupportedException("The System.IO.Path API is not available on this platform."); } return (string)PathType.GetRuntimeMethod("GetDirectoryName", new[] { typeof(string) }).Invoke(null, new object[] { filePath }); } /// <summary>Evaluates the XPath for a given XML document.</summary> /// <param name="document">The document.</param> /// <param name="path">The path.</param> /// <returns>The value.</returns> /// <exception cref="NotSupportedException">The System.Xml.XPath.Extensions API is not available on this platform.</exception> public static object XPathEvaluate(XDocument document, string path) { if (!SupportsXPathApis) { throw new NotSupportedException("The System.Xml.XPath.Extensions API is not available on this platform."); } return XPathExtensionsType.GetRuntimeMethod("XPathEvaluate", new[] { typeof(XDocument), typeof(string) }).Invoke(null, new object[] { document, path }); } /// <summary> /// Handle cases of specs in subdirectories having external references to specs also in subdirectories /// </summary> /// <param name="fullPath"></param> /// <param name="jsonPath"></param> /// <returns></returns> public static string HandleSubdirectoryRelativeReferences(string fullPath, string jsonPath) { try { if (!DynamicApis.DirectoryExists(DynamicApis.PathGetDirectoryName(fullPath))) { string fileName = DynamicApis.PathGetFileName(fullPath); string directoryName = DynamicApis.PathGetDirectoryName(fullPath); string folderName = directoryName.Replace("\\", "/").Split('/').Last(); if (!string.IsNullOrWhiteSpace(DynamicApis.DirectoryGetParent(directoryName))) { foreach (string subDir in DynamicApis.DirectoryGetDirectories(DynamicApis.DirectoryGetParent(directoryName))) { string expectedDir = DynamicApis.PathCombine(subDir, folderName); string expectedFile = DynamicApis.PathCombine(expectedDir, fileName); if (DynamicApis.DirectoryExists(expectedDir)) { fullPath = DynamicApis.PathCombine(expectedDir, fileName); break; } } } } if (!DynamicApis.FileExists(fullPath)) { string fileDir = DynamicApis.PathGetDirectoryName(fullPath); if (DynamicApis.DirectoryExists(fileDir)) { string fileName = DynamicApis.PathGetFileName(fullPath); string[] pathPieces = fullPath.Replace("\\", "/").Split('/'); string subDirPiece = pathPieces[pathPieces.Length - 2]; foreach (string subDir in DynamicApis.DirectoryGetDirectories(fileDir)) { string expectedFile = DynamicApis.PathCombine(subDir, fileName); if (DynamicApis.FileExists(expectedFile) && DynamicApis.FileReadAllText(expectedFile).Contains(jsonPath.Split('/').Last())) { fullPath = DynamicApis.PathCombine(subDir, fileName); break; } } } } return fullPath; } catch { return fullPath; } } #if LEGACY #pragma warning disable CS1998 internal static async Task<T> FromResult<T>(T result) { return result; } #pragma warning restore CS1998 #else [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Task<T> FromResult<T>(T result) { return Task.FromResult(result); } #endif private static Type TryLoadType(params string[] typeNames) { foreach (var typeName in typeNames) { try { var type = Type.GetType(typeName, false); if (type != null) { return type; } } catch { } } return null; } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: api@oanda.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.IO; using System.Web; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; using RestSharp; namespace Oanda.RestV20.Client { /// <summary> /// API client is mainly responsible for making the HTTP call to the API backend. /// </summary> public partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration and base path (https://localhost/v3). /// </summary> public ApiClient() { Configuration = Configuration.Default; RestClient = new RestClient("https://localhost/v3"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default base path (https://localhost/v3). /// </summary> /// <param name="config">An instance of Configuration.</param> public ApiClient(Configuration config = null) { if (config == null) Configuration = Configuration.Default; else Configuration = config; RestClient = new RestClient("https://localhost/v3"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> /// <param name="basePath">The base path.</param> public ApiClient(String basePath = "https://localhost/v3") { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); Configuration = Configuration.Default; } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The default API client.</value> [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")] public static ApiClient Default; /// <summary> /// Gets or sets the Configuration. /// </summary> /// <value>An instance of the Configuration.</value> public Configuration Configuration { get; set; } /// <summary> /// Gets or sets the RestClient. /// </summary> /// <value>An instance of the RestClient</value> public RestClient RestClient { get; set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = new RestRequest(path, method); // add path parameter, if any foreach(var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach(var param in headerParams) request.AddHeader(param.Key, param.Value); // add query parameter, if any foreach(var param in queryParams) request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach(var param in formParams) request.AddParameter(param.Key, param.Value); // add file parameter, if any foreach(var param in fileParams) { request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); } if (postBody != null) // http body (model or byte[]) parameter { if (postBody.GetType() == typeof(String)) { request.AddParameter("application/json", postBody, ParameterType.RequestBody); } else if (postBody.GetType() == typeof(byte[])) { request.AddParameter(contentType, postBody, ParameterType.RequestBody); } } return request; } /// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content Type of the request</param> /// <returns>Object</returns> public Object CallApi( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); // set timeout RestClient.Timeout = Configuration.Timeout; // set user agent RestClient.UserAgent = Configuration.UserAgent; InterceptRequest(request); var response = RestClient.Execute(request); InterceptResponse(request, response); return (Object) response; } /// <summary> /// Makes the asynchronous HTTP request. /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <param name="contentType">Content type.</param> /// <returns>The Task instance.</returns> public async System.Threading.Tasks.Task<Object> CallApiAsync( String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams, String contentType) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); InterceptRequest(request); var response = await RestClient.ExecuteTaskAsync(request); InterceptResponse(request, response); return (Object)response; } /// <summary> /// Escape string (url-encoded). /// </summary> /// <param name="str">String to be escaped.</param> /// <returns>Escaped string.</returns> public string EscapeString(string str) { return UrlEncode(str); } /// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// <summary> /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// </summary> /// <param name="obj">The parameter (header, path, query, form).</param> /// <returns>Formatted string.</returns> public string ParameterToString(object obj) { if (obj is DateTime) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is DateTimeOffset) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); foreach (var param in (IList)obj) { if (flattenedString.Length > 0) flattenedString.Append(","); flattenedString.Append(param); } return flattenedString.ToString(); } else return Convert.ToString (obj); } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> public object Deserialize(IRestResponse response, Type type) { IList<Parameter> headers = response.Headers; if (type == typeof(byte[])) // return byte array { return response.RawBytes; } if (type == typeof(Stream)) { if (headers != null) { var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, response.RawBytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(response.RawBytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return ConvertType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Serialize an input (model) into JSON string /// </summary> /// <param name="obj">Object.</param> /// <returns>JSON string.</returns> public String Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Select the Content-Type header's value from the given content-type array: /// if JSON exists in the given array, use it; /// otherwise use the first one defined in 'consumes' /// </summary> /// <param name="contentTypes">The Content-Type array to select from.</param> /// <returns>The Content-Type header to use.</returns> public String SelectHeaderContentType(String[] contentTypes) { if (contentTypes.Length == 0) return null; if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return contentTypes[0]; // use the first content type specified in 'consumes' } /// <summary> /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; /// otherwise use all of them (joining into a string) /// </summary> /// <param name="accepts">The accepts array to select from.</param> /// <returns>The Accept header to use.</returns> public String SelectHeaderAccept(String[] accepts) { if (accepts.Length == 0) return null; if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return String.Join(",", accepts); } /// <summary> /// Encode string in base64 format. /// </summary> /// <param name="text">String to be encoded.</param> /// <returns>Encoded string.</returns> public static string Base64Encode(string text) { return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// <summary> /// Dynamically cast the object into target type. /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast /// </summary> /// <param name="source">Object to be casted</param> /// <param name="dest">Target type</param> /// <returns>Casted object</returns> public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } /// <summary> /// Convert stream to byte array /// Credit/Ref: http://stackoverflow.com/a/221941/677735 /// </summary> /// <param name="input">Input stream to be converted</param> /// <returns>Byte array</returns> public static byte[] ReadAsBytes(Stream input) { byte[] buffer = new byte[16*1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } /// <summary> /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// </summary> /// <param name="input">String to be URL encoded</param> /// <returns>Byte array</returns> public static string UrlEncode(string input) { const int maxLength = 32766; if (input == null) { throw new ArgumentNullException("input"); } if (input.Length <= maxLength) { return Uri.EscapeDataString(input); } StringBuilder sb = new StringBuilder(input.Length * 2); int index = 0; while (index < input.Length) { int length = Math.Min(input.Length - index, maxLength); string subString = input.Substring(index, length); sb.Append(Uri.EscapeDataString(subString)); index += subString.Length; } return sb.ToString(); } /// <summary> /// Sanitize filename by removing the path /// </summary> /// <param name="filename">Filename</param> /// <returns>Filename</returns> public static string SanitizeFilename(string filename) { Match match = Regex.Match(filename, @".*[/\\](.*)$"); if (match.Success) { return match.Groups[1].Value; } else { return filename; } } } }
using OpenKh.Kh2; using OpenKh.Tools.BarEditor.Interfaces; using OpenKh.Tools.BarEditor.Models; using OpenKh.Tools.BarEditor.Services; using OpenKh.Tools.Common; using OpenKh.Tools.Common.Wpf; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using Xe.Tools.Models; using Xe.Tools.Wpf.Commands; using Xe.Tools.Wpf.Dialogs; using Xe.Tools.Wpf.Models; namespace OpenKh.Tools.BarEditor.ViewModels { public class BarViewModel : GenericListModel<BarEntryModel>, IViewSettings { private static string ApplicationName = Utilities.GetApplicationName(); private string _fileName; private static readonly List<FileDialogFilter> Filters = FileDialogFilterComposer.Compose().AddAllFiles(); private readonly ToolInvokeDesc _toolInvokeDesc; private Bar.MotionsetType _motionsetType; private bool _showSlotNumber; private bool _showMovesetName; public static EnumModel<Bar.MotionsetType> MotionsetTypes { get; } = new EnumModel<Bar.MotionsetType>(); public string Title => $"{FileName ?? "untitled"} | {ApplicationName}"; public BarViewModel(ToolInvokeDesc desc) : this() { _toolInvokeDesc = desc; OpenStream(desc.SelectedEntry.Stream); NewCommand = new RelayCommand(x => { }, x => false); OpenCommand = new RelayCommand(x => { }, x => false); SaveCommand = new RelayCommand(x => { var memoryStream = new MemoryStream(); Bar.Write(memoryStream, Items.Select(item => item.Entry), MotionsetType); var stream = _toolInvokeDesc.SelectedEntry.Stream; stream.Position = 0; stream.SetLength(0); memoryStream.Position = 0; memoryStream.CopyTo(stream); }); SaveAsCommand = new RelayCommand(x => { }, x => false); } public BarViewModel() : base(new BarEntryModel[0]) { Types = new EnumModel<Bar.EntryType>(); NewCommand = new RelayCommand(x => { FileName = "untitled.bar"; Items.Clear(); MotionsetType = 0; }, x => true); OpenCommand = new RelayCommand(x => { FileDialog.OnOpen(fileName => { OpenFileName(fileName); FileName = fileName; }, Filters); }, x => true); SaveCommand = new RelayCommand(x => { if (!string.IsNullOrEmpty(FileName)) { SaveToFile(FileName); } else { SaveAsCommand.Execute(x); } }, x => true); SaveAsCommand = new RelayCommand(x => { FileDialog.OnSave(fileName => { SaveToFile(fileName); }, Filters, Path.GetFileName(FileName)); }, x => true); ExitCommand = new RelayCommand(x => { Window.Close(); }, x => true); AboutCommand = new RelayCommand(x => { new AboutDialog(Assembly.GetExecutingAssembly()).ShowDialog(); }, x => true); OpenItemCommand = new RelayCommand(x => { try { var tempFileName = SaveToTempraryFile(); switch (ToolsLoaderService.OpenTool(FileName, tempFileName, SelectedItem.Entry)) { case Common.ToolInvokeDesc.ContentChangeInfo.File: ReloadFromTemporaryFile(tempFileName); break; } } catch (Exception e) { MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } OnPropertyChanged(nameof(SelectedItem)); }, x => true); ExportCommand = new RelayCommand(x => { var defaultFileName = GetSuggestedFileName(SelectedItem.Entry); FileDialog.OnSave(fileName => { using var fStream = File.OpenWrite(fileName); SelectedItem.Entry.Stream.Position = 0; SelectedItem.Entry.Stream.CopyTo(fStream); }, Filters, defaultFileName); }, x => IsItemSelected); ExportAllCommand = new RelayCommand(x => { FileDialog.OnFolder(folder => { foreach (var item in Items.Select(item => item.Entry)) { var fileName = GetSuggestedFileName(item); using var fStream = File.OpenWrite(Path.Combine(folder, fileName)); item.Stream.Position = 0; item.Stream.CopyTo(fStream); } }); }, x => true); ImportCommand = new RelayCommand(x => { FileDialog.OnOpen(fileName => { var fStream = File.OpenRead(fileName); var memStream = new MemoryStream((int)fStream.Length); fStream.CopyTo(memStream); SelectedItem.Entry.Stream = memStream; OnPropertyChanged(nameof(SelectedItem)); }, Filters); }, x => IsItemSelected); } public void OpenFileName(string fileName) { using var stream = File.Open(fileName, FileMode.Open); OpenStream(stream); } private void OpenStream(Stream stream) { Items.Clear(); var binarc = Bar.Read(stream); ShowMovesetName = AutodetectMsetFile(binarc); ShowSlotNumber = ShowMovesetName; MotionsetType = binarc.Motionset; foreach (var item in binarc) { Items.Add(new BarEntryModel(item, this)); } } private void SaveToFile(string fileName) { var memoryStream = new MemoryStream(); Bar.Write(memoryStream, Items.Select(item => item.Entry), MotionsetType); using var stream = File.Open(fileName, FileMode.Create); memoryStream.Position = 0; memoryStream.CopyTo(stream); } private string GetTemporaryFileName(string actualFileName) { return Path.GetTempFileName(); } private string SaveToTempraryFile() { var tempFileName = GetTemporaryFileName(FileName); SaveToFile(tempFileName); return tempFileName; } private void ReloadFromTemporaryFile(string tempFileName) { OpenFileName(tempFileName); } private static string GetSuggestedFileName(Bar.Entry item) => $"{item.Name}_{item.Index}.{Helpers.GetSuggestedExtension(item.Type)}"; private Window Window => Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive); public string FileName { get => _fileName; set { _fileName = value; OnPropertyChanged(nameof(Title)); } } public Bar.MotionsetType MotionsetType { get => _motionsetType; set { _motionsetType = value; InvalidateBarEntryTags(); OnPropertyChanged(nameof(MotionsetType)); OnPropertyChanged(nameof(IsMsetInfoVisible)); } } public Visibility IsMsetInfoVisible => MotionsetType == Bar.MotionsetType.Player && ShowMovesetName == true ? Visibility.Visible : Visibility.Collapsed; public RelayCommand NewCommand { get; set; } public RelayCommand OpenCommand { get; set; } public RelayCommand SaveCommand { get; set; } public RelayCommand SaveAsCommand { get; set; } public RelayCommand ExitCommand { get; set; } public RelayCommand AboutCommand { get; set; } public RelayCommand ExportCommand { get; set; } public RelayCommand ExportAllCommand { get; set; } public RelayCommand ImportCommand { get; set; } public RelayCommand OpenItemCommand { get; set; } public EnumModel<Bar.EntryType> Types { get; set; } public string ExportFileName => IsItemSelected ? GetSuggestedFileName(SelectedItem.Entry) : string.Empty; public bool IsPlayer => MotionsetType != Bar.MotionsetType.Default; public bool ShowSlotNumber { get => _showSlotNumber; set { _showSlotNumber = value; InvalidateBarEntryTags(); OnPropertyChanged(); } } public bool ShowMovesetName { get => _showMovesetName; set { _showMovesetName = value; InvalidateBarEntryTags(); OnPropertyChanged(); OnPropertyChanged(nameof(IsMsetInfoVisible)); } } public int GetSlotIndex(BarEntryModel item) => Items.IndexOf(item); private void InvalidateBarEntryTags() { foreach (var item in Items) item.InvalidateTag(); } protected override BarEntryModel OnNewItem() { return new BarEntryModel(new Bar.Entry() { Stream = new MemoryStream() }, this); } protected override void OnSelectedItem(BarEntryModel item) { base.OnSelectedItem(item); ExportCommand.CanExecute(SelectedItem); ImportCommand.CanExecute(SelectedItem); OpenItemCommand.CanExecute(SelectedItem); OnPropertyChanged(nameof(ExportFileName)); } private static bool AutodetectMsetFile(Bar binarc) { // When the motionset type is not default, it's easy to assume it's a MSET. if (binarc.Motionset != Bar.MotionsetType.Default) return true; // When not, we need to make an assumption. For example a MSET usually // contains a bunch of ANB. We can say that if we find mroe tha N ANB // entries then it's a MSET. const int AnbCountAssumption = 4; return binarc.Count(x => x.Type == Bar.EntryType.Anb) >= AnbCountAssumption; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; using Cassandra.Requests; using Cassandra.Serialization; namespace Cassandra { /// <summary> /// Base class for statements that contains the options. /// </summary> public abstract class Statement : IStatement { protected const string ProxyExecuteKey = "ProxyExecute"; private ConsistencyLevel _serialConsistency = QueryProtocolOptions.Default.SerialConsistency; private object[] _values; private bool _autoPage = true; private volatile int _isIdempotent = int.MinValue; private volatile Host _host; private string _authorizationId; private IDictionary<string, byte[]> _outgoingPayload; public virtual object[] QueryValues { get { return _values; } } /// <inheritdoc /> public bool SkipMetadata { get; private set; } /// <inheritdoc /> public ConsistencyLevel? ConsistencyLevel { get; private set; } /// <summary> /// Gets the serial consistency level for this query. /// </summary> public ConsistencyLevel SerialConsistencyLevel { get { return _serialConsistency; } } /// <inheritdoc /> public int PageSize { get; private set; } /// <inheritdoc /> public bool IsTracing { get; private set; } /// <inheritdoc /> public int ReadTimeoutMillis { get; private set; } /// <inheritdoc /> public IRetryPolicy RetryPolicy { get; private set; } /// <inheritdoc /> public byte[] PagingState { get; private set; } /// <inheritdoc /> public DateTimeOffset? Timestamp { get; private set; } /// <inheritdoc /> public bool AutoPage { get { return _autoPage; } } /// <inheritdoc /> public IDictionary<string, byte[]> OutgoingPayload { get { return _outgoingPayload; } private set { RebuildOutgoingPayload(value); } } /// <inheritdoc /> public abstract RoutingKey RoutingKey { get; } /// <inheritdoc /> public bool? IsIdempotent { get { var idempotence = _isIdempotent; if (idempotence == int.MinValue) { return null; } return idempotence == 1; } } /// <inheritdoc /> public virtual string Keyspace { get { return null; } } /// <summary> /// Gets the host configured on this <see cref="Statement"/>, or <c>null</c> if none is configured. /// <para> /// In the general case, the host used to execute this <see cref="Statement"/> will depend on the configured /// <see cref="ILoadBalancingPolicy"/> and this property will return <c>null</c>. /// </para> /// <seealso cref="SetHost"/> /// </summary> public Host Host => _host; protected Statement() { } // ReSharper disable once UnusedParameter.Local protected Statement(QueryProtocolOptions queryProtocolOptions) { //the unused parameter is maintained for backward compatibility } /// <inheritdoc /> public IStatement ExecutingAs(string userOrRole) { _authorizationId = userOrRole; RebuildOutgoingPayload(_outgoingPayload); return this; } private void RebuildOutgoingPayload(IDictionary<string, byte[]> payload) { if (_authorizationId == null) { _outgoingPayload = payload; return; } IDictionary<string, byte[]> builder; if (payload != null) { builder = new Dictionary<string, byte[]>(payload); } else { builder = new Dictionary<string, byte[]>(1); } builder[ProxyExecuteKey] = Encoding.UTF8.GetBytes(_authorizationId); _outgoingPayload = builder; } /// <inheritdoc /> internal Statement SetSkipMetadata(bool val) { SkipMetadata = val; return this; } /// <summary> /// Bound values to the variables of this statement. This method provides a /// convenience to bound all the variables of the <c>BoundStatement</c> in /// one call. /// </summary> /// <param name="values"> the values to bind to the variables of the newly /// created BoundStatement. The first element of <c>values</c> will /// be bound to the first bind variable, /// etc.. It is legal to provide less values than the statement has bound /// variables. In that case, the remaining variable need to be bound before /// execution. If more values than variables are provided however, an /// IllegalArgumentException will be raised. </param> /// <param name="serializer">Current serializer.</param> /// <returns>this bound statement. </returns> internal virtual void SetValues(object[] values, ISerializer serializer) { _values = values; } /// <inheritdoc /> public IStatement SetAutoPage(bool autoPage) { _autoPage = autoPage; return this; } /// <inheritdoc /> public IStatement SetPagingState(byte[] pagingState) { PagingState = pagingState; //Disable automatic paging only if paging state is set to something other then null if (pagingState != null && pagingState.Length > 0) { return SetAutoPage(false); } return this; } /// <inheritdoc /> public IStatement SetReadTimeoutMillis(int timeout) { ReadTimeoutMillis = timeout; return this; } /// <inheritdoc /> public IStatement SetConsistencyLevel(ConsistencyLevel? consistency) { ConsistencyLevel = consistency; return this; } /// <inheritdoc /> public IStatement SetSerialConsistencyLevel(ConsistencyLevel serialConsistency) { if (serialConsistency.IsSerialConsistencyLevel() == false) { throw new ArgumentException("The serial consistency can only be set to ConsistencyLevel.LocalSerial or ConsistencyLevel.Serial."); } _serialConsistency = serialConsistency; return this; } /// <inheritdoc /> public IStatement SetTimestamp(DateTimeOffset value) { Timestamp = value; return this; } /// <inheritdoc /> public IStatement EnableTracing(bool enable = true) { IsTracing = enable; return this; } /// <inheritdoc /> public IStatement DisableTracing() { IsTracing = false; return this; } /// <inheritdoc /> public IStatement SetRetryPolicy(IRetryPolicy policy) { RetryPolicy = policy; return this; } internal virtual IQueryRequest CreateBatchRequest(ISerializer serializer) { throw new InvalidOperationException("Cannot insert this query into the batch"); } /// <inheritdoc /> public IStatement SetIdempotence(bool value) { _isIdempotent = value ? 1 : 0; return this; } /// <inheritdoc /> public IStatement SetPageSize(int pageSize) { PageSize = pageSize; return this; } /// <inheritdoc /> public IStatement SetOutgoingPayload(IDictionary<string, byte[]> payload) { OutgoingPayload = payload; return this; } /// <summary> /// Sets the <see cref="Host"/> that should handle this query. /// <para> /// In the general case, use of this method is <em>heavily discouraged</em> and should only be /// used in the following cases: /// </para> /// <list type="bullet"> /// <item><description>Querying node-local tables, such as tables in the <c>system</c> and <c>system_views</c> /// keyspaces.</description></item> /// <item><description>Applying a series of schema changes, where it may be advantageous to execute schema /// changes in sequence on the same node.</description></item> /// </list> /// <para>Configuring a specific host causes the configured <see cref="ILoadBalancingPolicy"/> to be /// completely bypassed. However, if the load balancing policy dictates that the host is at /// distance <see cref="HostDistance.Ignored"/> or there is no active connectivity to the host, the /// request will fail with a <see cref="NoHostAvailableException"/>.</para> /// </summary> /// <param name="host">The host that should be used to handle executions of this statement or null to /// delegate to the configured load balancing policy.</param> /// <returns>this instance</returns> public IStatement SetHost(Host host) { _host = host; return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; using System.Runtime.Serialization; //For SR using System.Globalization; using System.Security; namespace System.Text { internal class Base64Encoding : Encoding { private static byte[] s_char2val = new byte[128] { /* 0-15 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 16-31 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 32-47 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 62, 0xFF, 0xFF, 0xFF, 63, /* 48-63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xFF, 0xFF, 0xFF, 64, 0xFF, 0xFF, /* 64-79 */ 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 80-95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* 96-111 */ 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 112-127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; private static string s_val2char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static byte[] s_val2byte = new byte[] { (byte)'A',(byte)'B',(byte)'C',(byte)'D',(byte)'E',(byte)'F',(byte)'G',(byte)'H',(byte)'I',(byte)'J',(byte)'K',(byte)'L',(byte)'M',(byte)'N',(byte)'O',(byte)'P', (byte)'Q',(byte)'R',(byte)'S',(byte)'T',(byte)'U',(byte)'V',(byte)'W',(byte)'X',(byte)'Y',(byte)'Z',(byte)'a',(byte)'b',(byte)'c',(byte)'d',(byte)'e',(byte)'f', (byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',(byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v', (byte)'w',(byte)'x',(byte)'y',(byte)'z',(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',(byte)'8',(byte)'9',(byte)'+',(byte)'/' }; public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", SR.Format(SR.ValueMustBeNonNegative))); if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); return charCount / 4 * 3; } private bool IsValidLeadBytes(int v1, int v2, int v3, int v4) { // First two chars of a four char base64 sequence can't be ==, and must be valid return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF); } private bool IsValidTailBytes(int v3, int v4) { // If the third char is = then the fourth char must be = return !(v3 == 64 && v4 != 64); } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetByteCount(char[] chars, int index, int count) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); if (index < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.Format(SR.ValueMustBeNonNegative))); if (index > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.ValueMustBeNonNegative))); if (count > chars.Length - index) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index))); if (count == 0) return 0; if ((count % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (char* _chars = &chars[index]) { int totalCount = 0; char* pch = _chars; char* pchMax = _chars + count; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); char pch0 = pch[0]; char pch1 = pch[1]; char pch2 = pch[2]; char pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); totalCount += byteCount; pch += 4; } return totalCount; } } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", SR.Format(SR.ValueMustBeNonNegative))); if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (charCount == 0) return 0; if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (char* _chars = &chars[charIndex]) { fixed (byte* _bytes = &bytes[byteIndex]) { char* pch = _chars; char* pchMax = _chars + charCount; byte* pb = _bytes; byte* pbMax = _bytes + bytes.Length - byteIndex; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); char pch0 = pch[0]; char pch1 = pch[1]; char pch2 = pch[2]; char pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); if (pb + byteCount > pbMax) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), "bytes")); pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03)); if (byteCount > 1) { pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F)); if (byteCount > 2) { pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F)); } } pb += byteCount; pch += 4; } return (int)(pb - _bytes); } } } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", SR.Format(SR.ValueMustBeNonNegative))); if (charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (charCount == 0) return 0; if ((charCount % 4) != 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); fixed (byte* _char2val = s_char2val) { fixed (byte* _chars = &chars[charIndex]) { fixed (byte* _bytes = &bytes[byteIndex]) { byte* pch = _chars; byte* pchMax = _chars + charCount; byte* pb = _bytes; byte* pbMax = _bytes + bytes.Length - byteIndex; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); byte pch0 = pch[0]; byte pch1 = pch[1]; byte pch2 = pch[2]; byte pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); if (pb + byteCount > pbMax) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), "bytes")); pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03)); if (byteCount > 1) { pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F)); if (byteCount > 2) { pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F)); } } pb += byteCount; pch += 4; } return (int)(pb - _bytes); } } } } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > int.MaxValue / 4 * 3 - 2) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 4 * 3 - 2))); return ((byteCount + 2) / 3) * 4; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (byteCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", SR.Format(SR.ValueMustBeNonNegative))); if (byteCount > bytes.Length - byteIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0 || charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), "chars")); // We've computed exactly how many chars there are and verified that // there's enough space in the char buffer, so we can proceed without // checking the charCount. if (byteCount > 0) { fixed (char* _val2char = s_val2char) { fixed (byte* _bytes = &bytes[byteIndex]) { fixed (char* _chars = &chars[charIndex]) { byte* pb = _bytes; byte* pbMax = pb + byteCount - 3; char* pch = _chars; // Convert chunks of 3 bytes to 4 chars while (pb <= pbMax) { // 76543210 76543210 76543210 // xx765432 xx107654 xx321076 xx543210 // Inspect the code carefully before you change this pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)]; pch[3] = _val2char[pb[2] & 0x3F]; pb += 3; pch += 4; } // Handle 1 or 2 trailing bytes if (pb - pbMax == 2) { // 1 trailing byte // 76543210 xxxxxxxx xxxxxxxx // xx765432 xx10xxxx xxxxxxxx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4)]; pch[2] = '='; pch[3] = '='; } else if (pb - pbMax == 1) { // 2 trailing bytes // 76543210 76543210 xxxxxxxx // xx765432 xx107654 xx3210xx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2)]; pch[3] = '='; } else { // 0 trailing bytes DiagnosticUtility.DebugAssert(pb - pbMax == 3, ""); } } } } } return charCount; } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe public int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex) { if (bytes == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); if (byteIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.ValueMustBeNonNegative))); if (byteIndex > bytes.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); if (byteCount < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", SR.Format(SR.ValueMustBeNonNegative))); if (byteCount > bytes.Length - byteIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); if (charIndex < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.ValueMustBeNonNegative))); if (charIndex > chars.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); if (charCount < 0 || charCount > chars.Length - charIndex) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), "chars")); // We've computed exactly how many chars there are and verified that // there's enough space in the char buffer, so we can proceed without // checking the charCount. if (byteCount > 0) { fixed (byte* _val2byte = s_val2byte) { fixed (byte* _bytes = &bytes[byteIndex]) { fixed (byte* _chars = &chars[charIndex]) { byte* pb = _bytes; byte* pbMax = pb + byteCount - 3; byte* pch = _chars; // Convert chunks of 3 bytes to 4 chars while (pb <= pbMax) { // 76543210 76543210 76543210 // xx765432 xx107654 xx321076 xx543210 // Inspect the code carefully before you change this pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2byte[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)]; pch[3] = _val2byte[pb[2] & 0x3F]; pb += 3; pch += 4; } // Handle 1 or 2 trailing bytes if (pb - pbMax == 2) { // 1 trailing byte // 76543210 xxxxxxxx xxxxxxxx // xx765432 xx10xxxx xxxxxxxx xxxxxxxx pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4)]; pch[2] = (byte)'='; pch[3] = (byte)'='; } else if (pb - pbMax == 1) { // 2 trailing bytes // 76543210 76543210 xxxxxxxx // xx765432 xx107654 xx3210xx xxxxxxxx pch[0] = _val2byte[(pb[0] >> 2)]; pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2byte[((pb[1] & 0x0F) << 2)]; pch[3] = (byte)'='; } else { // 0 trailing bytes DiagnosticUtility.DebugAssert(pb - pbMax == 3, ""); } } } } } return charCount; } } }
// Copyright (c) 2015 Alachisoft // // 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 System.Text; using Alachisoft.NCache.Serialization.Formatters; using Alachisoft.NCache.Serialization.Surrogates; using Alachisoft.NCache.Serialization; using Alachisoft.NCache.Runtime.Serialization.IO; using System.Reflection; namespace Alachisoft.NCache.IO { /// <summary> /// This class encapsulates a <see cref="BinaryReader"/> object. It also provides an extra /// Read method for <see cref="System.Object"/> types. /// </summary> public class CompactBinaryReader : CompactReader, IDisposable { private SerializationContext context; private BinaryReader reader; /// <summary> /// Constructs a compact reader over a <see cref="Stream"/> object. /// </summary> /// <param name="input"><see cref="Stream"/> object</param> public CompactBinaryReader(Stream input) : this(input, new UTF8Encoding(true)) { } /// <summary> /// Constructs a compact reader over a <see cref="Stream"/> object. /// </summary> /// <param name="input"><see cref="Stream"/> object</param> /// <param name="encoding"><see cref="System.Text.Encoding"/> object</param> public CompactBinaryReader(Stream input, Encoding encoding) { context = new SerializationContext(); reader = new BinaryReader(input, encoding); } /// <summary> Returns the underlying <see cref="BinaryReader"/> object. </summary> internal BinaryReader BaseReader { get { return reader; } } /// <summary> Returns the current <see cref="SerializationContext"/> object. </summary> internal SerializationContext Context { get { return context; } } #region Dispose /// <summary> /// Close the underlying <see cref="BinaryWriter"/>. /// </summary> public void Dispose() { if (reader != null) reader.Close(); } /// <summary> /// Close the underlying <see cref="BinaryWriter"/>. /// </summary> public void Dispose(bool closeStream) { if (closeStream) reader.Close(); reader = null; } #endregion /// <summary> /// Reads an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> /// <returns>object read from the stream</returns> public override object ReadObject() { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext); object obj = null; try { obj = surrogate.Read(this); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message, e); } return obj; } public override T ReadObjectAs<T>() { // Find an appropriate surrogate by type ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext); return (T)surrogate.Read(this); } /// <summary> /// Skips an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> public override void SkipObject() { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext); try { surrogate.Skip(this); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message); } } public override void SkipObjectAs<T>() { // Find an appropriate surrogate by type ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext); surrogate.Skip(this); } public object IfSkip(object readObjectValue, object defaultValue) { if (readObjectValue is SkipSerializationSurrogate) return defaultValue; else return readObjectValue; } public string CacheContext { get { return context.CacheContext; } } #region / CompactBinaryReader.ReadXXX / /// <summary> /// Reads an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override bool ReadBoolean() { return reader.ReadBoolean(); } /// <summary> /// Reads an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override byte ReadByte() { return reader.ReadByte(); } /// <summary> /// Reads an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> /// <returns>object read from the stream</returns> public override byte[] ReadBytes(int count) { return reader.ReadBytes(count); } /// <summary> /// Reads an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override char ReadChar() { return reader.ReadChar(); } /// <summary> /// Reads an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override char[] ReadChars(int count) { return reader.ReadChars(count); } /// <summary> /// Reads an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override decimal ReadDecimal() { return reader.ReadDecimal(); } /// <summary> /// Reads an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override float ReadSingle() { return reader.ReadSingle(); } /// <summary> /// Reads an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override double ReadDouble() { return reader.ReadDouble(); } /// <summary> /// Reads an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override short ReadInt16() { return reader.ReadInt16(); } /// <summary> /// Reads an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override int ReadInt32() { return reader.ReadInt32(); } /// <summary> /// Reads an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override long ReadInt64() { return reader.ReadInt64(); } /// <summary> /// Reads an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override string ReadString() { return reader.ReadString(); } /// <summary> /// Reads an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override DateTime ReadDateTime() { return new DateTime(reader.ReadInt64()); } /// <summary> /// Reads an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public override Guid ReadGuid() { return new Guid(reader.ReadBytes(16)); } /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of buffer read</returns> public override int Read(byte[] buffer, int index, int count) { return reader.Read(buffer, index, count); } /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of chars read</returns> public override int Read(char[] buffer, int index, int count) { return reader.Read(buffer, index, count); } /// <summary> /// Reads an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public override sbyte ReadSByte() { return reader.ReadSByte(); } /// <summary> /// Reads an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public override ushort ReadUInt16() { return reader.ReadUInt16(); } /// <summary> /// Reads an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public override uint ReadUInt32() { return reader.ReadUInt32(); } /// <summary> /// Reads an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public override ulong ReadUInt64() { return reader.ReadUInt64(); } #endregion #region / CompactBinaryReader.SkipXXX / /// <summary> /// Skips an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipBoolean() { reader.BaseStream.Position = reader.BaseStream.Position++; } /// <summary> /// Skips an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipByte() { reader.BaseStream.Position = reader.BaseStream.Position++; } /// <summary> /// Skips an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> public override void SkipBytes(int count) { reader.BaseStream.Position = reader.BaseStream.Position + count; } /// <summary> /// Skips an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipChar() { reader.BaseStream.Position = reader.BaseStream.Position++; } /// <summary> /// Skips an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipChars(int count) { reader.BaseStream.Position = reader.BaseStream.Position + count; } /// <summary> /// Skips an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipDecimal() { reader.BaseStream.Position = reader.BaseStream.Position + 16; } /// <summary> /// Skips an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipSingle() { reader.BaseStream.Position = reader.BaseStream.Position + 4; } /// <summary> /// Skips an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipDouble() { reader.BaseStream.Position = reader.BaseStream.Position + 8; } /// <summary> /// Skips an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipInt16() { reader.BaseStream.Position = reader.BaseStream.Position + 2; } /// <summary> /// Skips an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipInt32() { reader.BaseStream.Position = reader.BaseStream.Position + 4; } /// <summary> /// Skips an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipInt64() { reader.BaseStream.Position = reader.BaseStream.Position + 8; } /// <summary> /// Skips an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipString() { //Reads String but does not assign value in effect behaves as a string //Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time. reader.ReadString(); } /// <summary> /// Skips an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipDateTime() { this.SkipInt64(); } /// <summary> /// Skips an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipGuid() { reader.BaseStream.Position = reader.BaseStream.Position + 16; } /// <summary> /// Skips an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipSByte() { reader.BaseStream.Position++; } /// <summary> /// Skips an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipUInt16() { reader.BaseStream.Position = reader.BaseStream.Position + 2; } /// <summary> /// Skips an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipUInt32() { reader.BaseStream.Position = reader.BaseStream.Position + 4; } /// <summary> /// Skips an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public override void SkipUInt64() { reader.BaseStream.Position = reader.BaseStream.Position + 8; } #endregion } }
#pragma warning disable 109, 114, 219, 429, 168, 162 public class IntIterator : global::haxe.lang.HxObject { public IntIterator(global::haxe.lang.EmptyObject empty) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" { } } #line default } public IntIterator(int min, int max) { unchecked { #line 44 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" global::IntIterator.__hx_ctor__IntIterator(this, min, max); } #line default } public static void __hx_ctor__IntIterator(global::IntIterator __temp_me6, int min, int max) { unchecked { #line 45 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" __temp_me6.min = min; __temp_me6.max = max; } #line default } public static new object __hx_createEmpty() { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return new global::IntIterator(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return new global::IntIterator(((int) (global::haxe.lang.Runtime.toInt(arr[0])) ), ((int) (global::haxe.lang.Runtime.toInt(arr[1])) )); } #line default } public int min; public int max; public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" switch (hash) { case 5442212: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" this.max = ((int) (@value) ); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return @value; } case 5443986: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" this.min = ((int) (@value) ); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return @value; } default: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return base.__hx_setField_f(field, hash, @value, handleProperties); } } } #line default } public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" switch (hash) { case 5442212: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" this.max = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return @value; } case 5443986: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" this.min = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return @value; } default: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return base.__hx_setField(field, hash, @value, handleProperties); } } } #line default } public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" switch (hash) { case 5442212: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return this.max; } case 5443986: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return this.min; } default: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties); } } } #line default } public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" switch (hash) { case 5442212: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return ((double) (this.max) ); } case 5443986: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return ((double) (this.min) ); } default: { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" return base.__hx_getField_f(field, hash, throwErrors, handleProperties); } } } #line default } public override void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" baseArr.push("max"); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" baseArr.push("min"); #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" { #line 34 "C:\\HaxeToolkit\\haxe\\std/IntIterator.hx" base.__hx_getFields(baseArr); } } #line default } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> [ExecuteInEditMode] public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> public Camera leftEyeCamera { get { return (usePerEyeCameras) ? _leftEyeCamera : _centerEyeCamera; } } /// <summary> /// The right eye camera. /// </summary> public Camera rightEyeCamera { get { return (usePerEyeCameras) ? _rightEyeCamera : _centerEyeCamera; } } /// <summary> /// Provides a root transform for all anchors in tracking space. /// </summary> public Transform trackingSpace { get; private set; } /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the left hand. /// </summary> public Transform leftHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right hand. /// </summary> public Transform rightHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the sensor. /// </summary> public Transform trackerAnchor { get; private set; } /// <summary> /// Occurs when the eye pose anchors have been set. /// </summary> public event System.Action<OVRCameraRig> UpdatedAnchors; /// <summary> /// If true, separate cameras will be used for the left and right eyes. /// </summary> public bool usePerEyeCameras = false; /// <summary> /// If true, all tracked anchors are updated in FixedUpdate instead of Update to favor physics fidelity. /// \note: If the fixed update rate doesn't match the rendering framerate (OVRManager.display.appFramerate), the anchors will visibly judder. /// </summary> public bool useFixedUpdateForTracking = false; private bool _skipUpdate = false; private readonly string trackingSpaceName = "TrackingSpace"; private readonly string trackerAnchorName = "TrackerAnchor"; private readonly string eyeAnchorName = "EyeAnchor"; private readonly string handAnchorName = "HandAnchor"; private readonly string legacyEyeAnchorName = "Camera"; private Camera _centerEyeCamera; private Camera _leftEyeCamera; private Camera _rightEyeCamera; #region Unity Messages private void Awake() { _skipUpdate = true; EnsureGameObjectIntegrity(); } private void Start() { UpdateAnchors(); } private void FixedUpdate() { if (useFixedUpdateForTracking) UpdateAnchors(); } private void Update() { _skipUpdate = false; if (!useFixedUpdateForTracking) UpdateAnchors(); } #endregion private void UpdateAnchors() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; if (_skipUpdate) { centerEyeAnchor.FromOVRPose(OVRPose.identity, true); leftEyeAnchor.FromOVRPose(OVRPose.identity, true); rightEyeAnchor.FromOVRPose(OVRPose.identity, true); return; } bool monoscopic = OVRManager.instance.monoscopic; OVRPose tracker = OVRManager.tracker.GetPose(); trackerAnchor.localRotation = tracker.orientation; centerEyeAnchor.localRotation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.CenterEye); leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.LeftEye); rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.RightEye); leftHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch); rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch); trackerAnchor.localPosition = tracker.position; centerEyeAnchor.localPosition = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.CenterEye); leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.LeftEye); rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.RightEye); leftHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch); rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch); if (UpdatedAnchors != null) { UpdatedAnchors(this); } } public void EnsureGameObjectIntegrity() { if (trackingSpace == null) trackingSpace = ConfigureRootAnchor(trackingSpaceName); if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, UnityEngine.XR.XRNode.LeftEye); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, UnityEngine.XR.XRNode.CenterEye); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, UnityEngine.XR.XRNode.RightEye); if (leftHandAnchor == null) leftHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandLeft); if (rightHandAnchor == null) rightHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandRight); if (trackerAnchor == null) trackerAnchor = ConfigureTrackerAnchor(trackingSpace); if (_centerEyeCamera == null || _leftEyeCamera == null || _rightEyeCamera == null) { _centerEyeCamera = centerEyeAnchor.GetComponent<Camera>(); _leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); _rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (_centerEyeCamera == null) { _centerEyeCamera = centerEyeAnchor.gameObject.AddComponent<Camera>(); _centerEyeCamera.tag = "MainCamera"; } if (_leftEyeCamera == null) { _leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); _leftEyeCamera.tag = "MainCamera"; #if !UNITY_5_4_OR_NEWER usePerEyeCameras = false; Debug.Log("Please set left eye Camera's Target Eye to Left before using."); #endif } if (_rightEyeCamera == null) { _rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); _rightEyeCamera.tag = "MainCamera"; #if !UNITY_5_4_OR_NEWER usePerEyeCameras = false; Debug.Log("Please set right eye Camera's Target Eye to Right before using."); #endif } #if UNITY_5_4_OR_NEWER _centerEyeCamera.stereoTargetEye = StereoTargetEyeMask.Both; _leftEyeCamera.stereoTargetEye = StereoTargetEyeMask.Left; _rightEyeCamera.stereoTargetEye = StereoTargetEyeMask.Right; #endif } if (_centerEyeCamera.enabled == usePerEyeCameras || _leftEyeCamera.enabled == !usePerEyeCameras || _rightEyeCamera.enabled == !usePerEyeCameras) { _skipUpdate = true; } _centerEyeCamera.enabled = !usePerEyeCameras; _leftEyeCamera.enabled = usePerEyeCameras; _rightEyeCamera.enabled = usePerEyeCameras; } private Transform ConfigureRootAnchor(string name) { Transform root = transform.Find(name); if (root == null) { root = new GameObject(name).transform; } root.parent = transform; root.localScale = Vector3.one; root.localPosition = Vector3.zero; root.localRotation = Quaternion.identity; return root; } private Transform ConfigureEyeAnchor(Transform root, UnityEngine.XR.XRNode eye) { string eyeName = (eye == UnityEngine.XR.XRNode.CenterEye) ? "Center" : (eye == UnityEngine.XR.XRNode.LeftEye) ? "Left" : "Right"; string name = eyeName + eyeAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { string legacyName = legacyEyeAnchorName + eye.ToString(); anchor = transform.Find(legacyName); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureHandAnchor(Transform root, OVRPlugin.Node hand) { string handName = (hand == OVRPlugin.Node.HandLeft) ? "Left" : "Right"; string name = handName + handAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureTrackerAnchor(Transform root) { string name = trackerAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = new GameObject(name).transform; } anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } public Matrix4x4 ComputeTrackReferenceMatrix() { if (centerEyeAnchor == null) { Debug.LogError("centerEyeAnchor is required"); return Matrix4x4.identity; } // The ideal approach would be using UnityEngine.VR.VRNode.TrackingReference, then we would not have to depend on the OVRCameraRig. Unfortunately, it is not available in Unity 5.4.3 OVRPose headPose; headPose.position = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.Head); headPose.orientation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.Head); OVRPose invHeadPose = headPose.Inverse(); Matrix4x4 invHeadMatrix = Matrix4x4.TRS(invHeadPose.position, invHeadPose.orientation, Vector3.one); Matrix4x4 ret = centerEyeAnchor.localToWorldMatrix * invHeadMatrix; return ret; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; namespace System.Data.Odbc { public sealed class OdbcConnectionStringBuilder : DbConnectionStringBuilder { private enum Keywords { // must maintain same ordering as s_validKeywords array Dsn, Driver, } private static readonly string[] s_validKeywords = new string[2] { DbConnectionStringKeywords.Dsn, // (int)Keywords.Dsn DbConnectionStringKeywords.Driver // (int)Keywords.Driver }; private static readonly Dictionary<string, Keywords> s_keywords = new Dictionary<string, Keywords>(2, StringComparer.OrdinalIgnoreCase) { { DbConnectionStringKeywords.Driver, Keywords.Driver }, { DbConnectionStringKeywords.Dsn, Keywords.Dsn } }; private string[] _knownKeywords; private string _dsn = DbConnectionStringDefaults.Dsn; private string _driver = DbConnectionStringDefaults.Driver; public OdbcConnectionStringBuilder() : this((string)null) { } public OdbcConnectionStringBuilder(string connectionString) : base(true) { if (!string.IsNullOrEmpty(connectionString)) { ConnectionString = connectionString; } } public override object this[string keyword] { get { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { return GetAt(index); } else { return base[keyword]; } } set { ADP.CheckArgumentNull(keyword, nameof(keyword)); if (null != value) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { switch (index) { case Keywords.Driver: Driver = ConvertToString(value); break; case Keywords.Dsn: Dsn = ConvertToString(value); break; default: Debug.Fail("unexpected keyword"); throw ADP.KeywordNotSupported(keyword); } } else { base[keyword] = value; ClearPropertyDescriptors(); _knownKeywords = null; } } else { Remove(keyword); } } } [DisplayName(DbConnectionStringKeywords.Driver)] public string Driver { get { return _driver; } set { SetValue(DbConnectionStringKeywords.Driver, value); _driver = value; } } [DisplayName(DbConnectionStringKeywords.Dsn)] public string Dsn { get { return _dsn; } set { SetValue(DbConnectionStringKeywords.Dsn, value); _dsn = value; } } public override ICollection Keys { get { string[] knownKeywords = _knownKeywords; if (null == knownKeywords) { knownKeywords = s_validKeywords; int count = 0; foreach (string keyword in base.Keys) { bool flag = true; foreach (string s in knownKeywords) { if (s == keyword) { flag = false; break; } } if (flag) { count++; } } if (0 < count) { string[] tmp = new string[knownKeywords.Length + count]; knownKeywords.CopyTo(tmp, 0); int index = knownKeywords.Length; foreach (string keyword in base.Keys) { bool flag = true; foreach (string s in knownKeywords) { if (s == keyword) { flag = false; break; } } if (flag) { tmp[index++] = keyword; } } knownKeywords = tmp; } _knownKeywords = knownKeywords; } return new ReadOnlyCollection<string>(knownKeywords); } } public override void Clear() { base.Clear(); for (int i = 0; i < s_validKeywords.Length; ++i) { Reset((Keywords)i); } _knownKeywords = s_validKeywords; } public override bool ContainsKey(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); return s_keywords.ContainsKey(keyword) || base.ContainsKey(keyword); } private static string ConvertToString(object value) { return DbConnectionStringBuilderUtil.ConvertToString(value); } private object GetAt(Keywords index) { switch (index) { case Keywords.Driver: return Driver; case Keywords.Dsn: return Dsn; default: Debug.Fail("unexpected keyword"); throw ADP.KeywordNotSupported(s_validKeywords[(int)index]); } } public override bool Remove(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); if (base.Remove(keyword)) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { Reset(index); } else { ClearPropertyDescriptors(); _knownKeywords = null; } return true; } return false; } private void Reset(Keywords index) { switch (index) { case Keywords.Driver: _driver = DbConnectionStringDefaults.Driver; break; case Keywords.Dsn: _dsn = DbConnectionStringDefaults.Dsn; break; default: Debug.Fail("unexpected keyword"); throw ADP.KeywordNotSupported(s_validKeywords[(int)index]); } } private void SetValue(string keyword, string value) { ADP.CheckArgumentNull(value, keyword); base[keyword] = value; } public override bool TryGetValue(string keyword, out object value) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { value = GetAt(index); return true; } return base.TryGetValue(keyword, out value); } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; using UnityEngine.Rendering; /// Camera component used for rendering exponential shadow maps. public class ShadowRendering : MonoBehaviour { /// Whether or not to render static shadows. /// If false, all shadows will be dynamic. public bool renderStaticShadows = true; /// Layer ID for dynamic shadow casters, if using mixed static /// and dynamic shadows. public int dynamicShadowCasterLayerID = 4; /// Changing this value adjusts shadow softness. public float shadowExponent; /// Set this to a similar value to the shadow camera's far clip plane. public float shadowDistance; /// Increasing blur iterations will result in softer, more expensive shadows. public int staticBlurIterations = 10; public int dynamicBlurIterations = 1; // This should be a default Unity quad. public Mesh quad; // Camera to be used for shadow casting. [SerializeField] private Camera camera; [SerializeField] private Shader depthShader; [SerializeField] private Material blurMaterial; [SerializeField] private Material combineBlurMaterial; [SerializeField] private Material blitMat; private RenderTexture shadowTexture; // Render texture used for static shadow pass. private RenderTexture staticShadowTexture; // Render textures used in shadow compositing ops. private RenderTexture shadowTextureA; private RenderTexture shadowTextureB; private RenderTexture shadowTextureDisplay; private const string SHADOW_CAMERA_MATRIX_NAME = "_ShadowCameraMatrix"; private const string SHADOW_MATRIX_NAME = "_ShadowMatrix"; private const string SHADOW_TEXTURE_NAME = "_ShadowTexture"; private const string SHADOW_DATA_NAME = "_ShadowData"; private int shadowCameraMatrixId; private int shadowMatrixId; private int shadowTextureId; private int shadowDataId; private int renderRes = 1024; private int texRes = 512; private Vector4 shadowData = new Vector4(); private CommandBuffer initMips; private CommandBuffer mips; private bool initialized = false; // The background color for the shadow camera. private Color almostWhite = new Color(0.99f,0.99f,0.99f,0.99f); void OnEnable() { if (renderStaticShadows == true) { staticShadowTexture = new RenderTexture(texRes, texRes, 0, RenderTextureFormat.ARGB32); } shadowTexture = new RenderTexture(renderRes, renderRes, 16, RenderTextureFormat.ARGB32); shadowTextureA = new RenderTexture(texRes, texRes,0, RenderTextureFormat.ARGB32); shadowTextureB = new RenderTexture(texRes, texRes,0, RenderTextureFormat.ARGB32); shadowTextureDisplay = new RenderTexture(texRes, texRes, 0, RenderTextureFormat.ARGB32); shadowTextureDisplay.useMipMap = true; shadowTextureDisplay.autoGenerateMips = false; shadowTextureDisplay.Create(); shadowTexture.Create(); shadowTextureA.Create(); shadowTextureB.Create(); if (renderStaticShadows == true) { staticShadowTexture.Create(); } shadowTextureDisplay.DiscardContents(); shadowTexture.DiscardContents(); shadowTextureA.DiscardContents(); shadowTextureB.DiscardContents(); if (renderStaticShadows == true) { staticShadowTexture.DiscardContents(); } camera.clearFlags = CameraClearFlags.SolidColor; camera.backgroundColor = almostWhite; camera.SetReplacementShader(depthShader,"RenderType"); shadowCameraMatrixId = Shader.PropertyToID(SHADOW_CAMERA_MATRIX_NAME); shadowMatrixId = Shader.PropertyToID(SHADOW_MATRIX_NAME); shadowTextureId = Shader.PropertyToID(SHADOW_TEXTURE_NAME); shadowDataId = Shader.PropertyToID(SHADOW_DATA_NAME); UpdateCameraParams(); initialized = false; } void OnDisable() { if (renderStaticShadows == true) { staticShadowTexture.Release(); } shadowTexture.Release(); shadowTextureA.Release(); shadowTextureB.Release(); shadowTextureDisplay.Release(); } void OnDestroy() { if (renderStaticShadows == true) { staticShadowTexture.Release(); Destroy(staticShadowTexture); } shadowTexture.Release(); shadowTextureA.Release(); shadowTextureB.Release(); shadowTextureDisplay.Release(); Destroy(shadowTexture); Destroy(shadowTextureA); Destroy(shadowTextureB); Destroy(shadowTextureDisplay); } void Initialize() { if(shadowTexture.IsCreated() && shadowTextureA.IsCreated() && shadowTextureB.IsCreated() && shadowTextureDisplay.IsCreated()) { RenderTexture current = RenderTexture.active; RenderTexture.active = shadowTexture; GL.Clear(true, true, almostWhite, 1); RenderTexture.active = shadowTextureA; GL.Clear(true, false, almostWhite); RenderTexture.active = shadowTextureB; GL.Clear(true, false, almostWhite); RenderTexture.active = shadowTextureDisplay; GL.Clear(true, false, almostWhite); if (renderStaticShadows == true) { RenderTexture.active = staticShadowTexture; GL.Clear(true, false, almostWhite); } RenderTexture.active = current; Shader.SetGlobalTexture(shadowTextureId, shadowTextureDisplay); ClearMips(); GenerateMips(); Graphics.ExecuteCommandBuffer(initMips); camera.targetTexture = shadowTexture; camera.enabled = true; initialized = true; // The static shadow pass is only performed once. if (renderStaticShadows == true) { RenderStaticLayer(); } } } void Update() { if(!initialized){ Initialize(); } else{ UpdateCameraParams(); } } void OnPostRender() { BlurLastRender(); } void UpdateCameraParams() { shadowData.x = shadowDistance; shadowData.y = shadowExponent; shadowData.z = Mathf.Exp(shadowExponent); shadowData.w = Mathf.Exp(-shadowExponent); Shader.SetGlobalVector(shadowDataId, shadowData); Shader.SetGlobalMatrix(shadowCameraMatrixId, camera.worldToCameraMatrix); Shader.SetGlobalMatrix(shadowMatrixId, camera.projectionMatrix * camera.worldToCameraMatrix); } void RenderStaticLayer() { // Exclude the layer from the shadow camera's culling mask that is being // used for dynamic shadow casters. camera.cullingMask &= ~(1<<dynamicShadowCasterLayerID); camera.Render(); Graphics.Blit(shadowTexture, shadowTextureA, blurMaterial, 0); RenderTexture current = shadowTextureA; RenderTexture target = shadowTextureB; // Blur static shadows. for(int i=0; i<staticBlurIterations; i++){ Graphics.Blit(current, target, blurMaterial, 0); RenderTexture tmp = current; current = target; target = tmp; } Graphics.Blit(current, staticShadowTexture, blurMaterial, 0); combineBlurMaterial.SetTexture("_MainTex2", staticShadowTexture); // Set the camera culling mask back to the layer being used for dynamic // shadow casters. camera.cullingMask = (1<<dynamicShadowCasterLayerID); } private void BlurLastRender() { /// Downsample and blur. // Discard render textures. shadowTextureA.DiscardContents(); shadowTextureB.DiscardContents(); shadowTextureDisplay.DiscardContents(); if (renderStaticShadows == true) { Graphics.Blit(shadowTexture, shadowTextureA, combineBlurMaterial,0); } else { Graphics.Blit(shadowTexture, shadowTextureA, blurMaterial, 0); } RenderTexture current = shadowTextureA; RenderTexture target = shadowTextureB; // Blur dynamic shadows. for(int i = 0; i < dynamicBlurIterations; i++){ Graphics.Blit(current, target, blurMaterial, 0); RenderTexture tmp = current; current = target; target = tmp; } // Blit the combined static and dynamic shadows to the final render // texture for display. Graphics.Blit(current, shadowTextureDisplay, blurMaterial, 0); blitMat.mainTexture = current; Graphics.ExecuteCommandBuffer(mips); } void GenerateMips() { mips = new CommandBuffer(); Matrix4x4 mat = Matrix4x4.identity; // 128 mips.SetRenderTarget(shadowTextureDisplay, 1); mips.DrawMesh(quad, mat, blitMat, 0, 0); // 64 mips.SetRenderTarget(shadowTextureDisplay, 2); mips.DrawMesh(quad, mat, blitMat, 0, 0); // 32 mips.SetRenderTarget(shadowTextureDisplay, 3); mips.DrawMesh(quad, mat, blitMat, 0, 0); // 16 mips.SetRenderTarget(shadowTextureDisplay, 4); mips.DrawMesh(quad, mat, blitMat, 0, 0); } void ClearMips() { initMips = new CommandBuffer(); Matrix4x4 mat = Matrix4x4.identity; initMips.SetRenderTarget(shadowTextureDisplay, 1); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 2); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 3); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 4); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 5); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 6); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 7); initMips.ClearRenderTarget(false, true, Color.white); initMips.SetRenderTarget(shadowTextureDisplay, 8); initMips.ClearRenderTarget(false, true, Color.white); } }
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs) //#define ProfileAstar //@SHOWINEDITOR //#define ASTAR_UNITY_PRO_PROFILER //@SHOWINEDITOR Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler. using System.Collections.Generic; using System; using UnityEngine; namespace Pathfinding { public class AstarProfiler { public class ProfilePoint { //public DateTime lastRecorded; //public TimeSpan totalTime; public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); public int totalCalls; public long tmpBytes; public long totalBytes; } static readonly Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>(); static DateTime startTime = DateTime.UtcNow; public static ProfilePoint[] fastProfiles; public static string[] fastProfileNames; private AstarProfiler() { } [System.Diagnostics.Conditional ("ProfileAstar")] public static void InitializeFastProfile (string[] profileNames) { fastProfileNames = new string[profileNames.Length+2]; Array.Copy (profileNames,fastProfileNames, profileNames.Length); fastProfileNames[fastProfileNames.Length-2] = "__Control1__"; fastProfileNames[fastProfileNames.Length-1] = "__Control2__"; fastProfiles = new ProfilePoint[fastProfileNames.Length]; for (int i=0;i<fastProfiles.Length;i++) fastProfiles[i] = new ProfilePoint(); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartFastProfile (int tag) { //profiles.TryGetValue(tag, out point); fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow; } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndFastProfile (int tag) { /*if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; }*/ ProfilePoint point = fastProfiles[tag]; point.totalCalls++; point.watch.Stop (); //DateTime now = DateTime.UtcNow; //point.totalTime += now - point.lastRecorded; //fastProfiles[tag] = point; } [System.Diagnostics.Conditional ("ASTAR_UNITY_PRO_PROFILER")] public static void EndProfile () { Profiler.EndSample (); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartProfile(string tag) { //Console.WriteLine ("Profile Start - " + tag); ProfilePoint point; profiles.TryGetValue(tag, out point); if (point == null) { point = new ProfilePoint(); profiles[tag] = point; } point.tmpBytes = GC.GetTotalMemory (false); point.watch.Start(); //point.lastRecorded = DateTime.UtcNow; //Debug.Log ("Starting " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndProfile(string tag) { if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; } //Console.WriteLine ("Profile End - " + tag); //DateTime now = DateTime.UtcNow; ProfilePoint point = profiles[tag]; //point.totalTime += now - point.lastRecorded; ++point.totalCalls; point.watch.Stop(); point.totalBytes += GC.GetTotalMemory (false) - point.tmpBytes; //profiles[tag] = point; //Debug.Log ("Ending " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void Reset () { profiles.Clear(); startTime = DateTime.UtcNow; if (fastProfiles != null) { for (int i=0;i<fastProfiles.Length;i++) { fastProfiles[i] = new ProfilePoint (); } } } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintFastResults () { StartFastProfile (fastProfiles.Length-2); for (int i=0;i<1000;i++) { StartFastProfile (fastProfiles.Length-1); EndFastProfile (fastProfiles.Length-1); } EndFastProfile (fastProfiles.Length-2); double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0; TimeSpan endTime = DateTime.UtcNow - startTime; var output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); output.Append ("Name | Total Time | Total Calls | Avg/Call | Bytes"); //foreach(KeyValuePair<string, ProfilePoint> pair in profiles) for (int i=0;i<fastProfiles.Length;i++) { string name = fastProfileNames[i]; ProfilePoint value = fastProfiles[i]; int totalCalls = value.totalCalls; double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls; if (totalCalls < 1) continue; output.Append ("\n").Append(name.PadLeft(10)).Append("| "); output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("| "); output.Append (totalCalls.ToString().PadLeft (10)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10)); /* output.Append("\nProfile"); output.Append(name); output.Append(" took \t"); output.Append(totalTime.ToString("0.0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging \t"); output.Append((totalTime / totalCalls).ToString("0.000")); output.Append(" ms per call"); */ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintResults () { TimeSpan endTime = DateTime.UtcNow - startTime; var output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); int maxLength = 5; foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { maxLength = Math.Max (pair.Key.Length,maxLength); } output.Append (" Name ".PadRight (maxLength)). Append("|").Append(" Total Time ".PadRight(20)). Append("|").Append(" Total Calls ".PadRight(20)). Append("|").Append(" Avg/Call ".PadRight(20)); foreach(var pair in profiles) { double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds; int totalCalls = pair.Value.totalCalls; if (totalCalls < 1) continue; string name = pair.Key; output.Append ("\n").Append(name.PadRight(maxLength)).Append("| "); output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| "); output.Append (totalCalls.ToString().PadRight (20)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20)); output.Append (AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10)); /*output.Append("\nProfile "); output.Append(pair.Key); output.Append(" took "); output.Append(totalTime.ToString("0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging "); output.Append((totalTime / totalCalls).ToString("0.0")); output.Append(" ms per call");*/ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Collections.Generic; namespace Mono.Cecil { public interface IAssemblyResolver { AssemblyDefinition Resolve (AssemblyNameReference name); AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters); AssemblyDefinition Resolve (string fullName); AssemblyDefinition Resolve (string fullName, ReaderParameters parameters); } public interface IMetadataResolver { TypeDefinition Resolve (TypeReference type); FieldDefinition Resolve (FieldReference field); MethodDefinition Resolve (MethodReference method); } #if !PCL [Serializable] #endif public class ResolutionException : Exception { readonly MemberReference member; public MemberReference Member { get { return member; } } public IMetadataScope Scope { get { var type = member as TypeReference; if (type != null) return type.Scope; var declaring_type = member.DeclaringType; if (declaring_type != null) return declaring_type.Scope; throw new NotSupportedException (); } } public ResolutionException (MemberReference member) : base ("Failed to resolve " + member.FullName) { if (member == null) throw new ArgumentNullException ("member"); this.member = member; } #if !PCL protected ResolutionException ( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (info, context) { } #endif } public class MetadataResolver : IMetadataResolver { readonly IAssemblyResolver assembly_resolver; public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } } public MetadataResolver (IAssemblyResolver assemblyResolver) { if (assemblyResolver == null) throw new ArgumentNullException ("assemblyResolver"); assembly_resolver = assemblyResolver; } public virtual TypeDefinition Resolve (TypeReference type) { if (type == null) throw new ArgumentNullException ("type"); type = type.GetElementType (); var scope = type.Scope; if (scope == null) return null; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: var assembly = assembly_resolver.Resolve ((AssemblyNameReference) scope); if (assembly == null) return null; return GetType (assembly.MainModule, type); case MetadataScopeType.ModuleDefinition: return GetType ((ModuleDefinition) scope, type); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference) scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules [i]; if (netmodule.Name == module_ref.Name) return GetType (netmodule, type); } break; } throw new NotSupportedException (); } static TypeDefinition GetType (ModuleDefinition module, TypeReference reference) { var type = GetTypeDefinition (module, reference); if (type != null) return type; if (!module.HasExportedTypes) return null; var exported_types = module.ExportedTypes; for (int i = 0; i < exported_types.Count; i++) { var exported_type = exported_types [i]; if (exported_type.Name != reference.Name) continue; if (exported_type.Namespace != reference.Namespace) continue; return exported_type.Resolve (); } return null; } static TypeDefinition GetTypeDefinition (ModuleDefinition module, TypeReference type) { if (!type.IsNested) return module.GetType (type.Namespace, type.Name); var declaring_type = type.DeclaringType.Resolve (); if (declaring_type == null) return null; return declaring_type.GetNestedType (type.TypeFullName ()); } public virtual FieldDefinition Resolve (FieldReference field) { if (field == null) throw new ArgumentNullException ("field"); var type = Resolve (field.DeclaringType); if (type == null) return null; if (!type.HasFields) return null; return GetField (type, field); } FieldDefinition GetField (TypeDefinition type, FieldReference reference) { while (type != null) { var field = GetField (type.Fields, reference); if (field != null) return field; if (type.BaseType == null) return null; type = Resolve (type.BaseType); } return null; } static FieldDefinition GetField (Collection<FieldDefinition> fields, FieldReference reference) { for (int i = 0; i < fields.Count; i++) { var field = fields [i]; if (field.Name != reference.Name) continue; if (!AreSame (field.FieldType, reference.FieldType)) continue; return field; } return null; } public virtual MethodDefinition Resolve (MethodReference method) { if (method == null) throw new ArgumentNullException ("method"); var type = Resolve (method.DeclaringType); if (type == null) return null; method = method.GetElementMethod (); if (!type.HasMethods) return null; return GetMethod (type, method); } MethodDefinition GetMethod (TypeDefinition type, MethodReference reference) { while (type != null) { var method = GetMethod (type.Methods, reference); if (method != null) return method; if (type.BaseType == null) return null; type = Resolve (type.BaseType); } return null; } public static MethodDefinition GetMethod (Collection<MethodDefinition> methods, MethodReference reference) { for (int i = 0; i < methods.Count; i++) { var method = methods [i]; if (method.Name != reference.Name) continue; if (method.HasGenericParameters != reference.HasGenericParameters) continue; if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count) continue; if (!AreSame (method.ReturnType, reference.ReturnType)) continue; if (method.IsVarArg () != reference.IsVarArg ()) continue; if (method.IsVarArg () && IsVarArgCallTo (method, reference)) return method; if (method.HasParameters != reference.HasParameters) continue; if (!method.HasParameters && !reference.HasParameters) return method; if (!AreSame (method.Parameters, reference.Parameters)) continue; return method; } return null; } static bool AreSame (Collection<ParameterDefinition> a, Collection<ParameterDefinition> b) { var count = a.Count; if (count != b.Count) return false; if (count == 0) return true; for (int i = 0; i < count; i++) if (!AreSame (a [i].ParameterType, b [i].ParameterType)) return false; return true; } private static bool IsVarArgCallTo (MethodDefinition method, MethodReference reference) { if (method.Parameters.Count >= reference.Parameters.Count) return false; if (reference.GetSentinelPosition () != method.Parameters.Count) return false; for (int i = 0; i < method.Parameters.Count; i++) if (!AreSame (method.Parameters [i].ParameterType, reference.Parameters [i].ParameterType)) return false; return true; } static bool AreSame (TypeSpecification a, TypeSpecification b) { if (!AreSame (a.ElementType, b.ElementType)) return false; if (a.IsGenericInstance) return AreSame ((GenericInstanceType) a, (GenericInstanceType) b); if (a.IsRequiredModifier || a.IsOptionalModifier) return AreSame ((IModifierType) a, (IModifierType) b); if (a.IsArray) return AreSame ((ArrayType) a, (ArrayType) b); return true; } static bool AreSame (ArrayType a, ArrayType b) { if (a.Rank != b.Rank) return false; // TODO: dimensions return true; } static bool AreSame (IModifierType a, IModifierType b) { return AreSame (a.ModifierType, b.ModifierType); } static bool AreSame (GenericInstanceType a, GenericInstanceType b) { if (a.GenericArguments.Count != b.GenericArguments.Count) return false; for (int i = 0; i < a.GenericArguments.Count; i++) if (!AreSame (a.GenericArguments [i], b.GenericArguments [i])) return false; return true; } static bool AreSame (GenericParameter a, GenericParameter b) { return a.Position == b.Position; } static bool AreSame (TypeReference a, TypeReference b) { if (ReferenceEquals (a, b)) return true; if (a == null || b == null) return false; if (a.etype != b.etype) return false; if (a.IsGenericParameter) return AreSame ((GenericParameter) a, (GenericParameter) b); if (a.IsTypeSpecification ()) return AreSame ((TypeSpecification) a, (TypeSpecification) b); if (a.Name != b.Name || a.Namespace != b.Namespace) return false; //TODO: check scope return AreSame (a.DeclaringType, b.DeclaringType); } } }
/* * Copyright (c) Contributors * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Mono.Addins; using System; using System.Reflection; using System.Threading; using System.Text; using System.Net; using System.Net.Sockets; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Scripting; using System.Collections.Generic; using System.Text.RegularExpressions; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "JsonStoreScriptModule")] public class JsonStoreScriptModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IConfig m_config = null; private bool m_enabled = false; private Scene m_scene = null; private IScriptModuleComms m_comms; private IJsonStoreModule m_store; private Dictionary<UUID,HashSet<UUID>> m_scriptStores = new Dictionary<UUID,HashSet<UUID>>(); #region Region Module interface // ----------------------------------------------------------------- /// <summary> /// Name of this shared module is it's class name /// </summary> // ----------------------------------------------------------------- public string Name { get { return this.GetType().Name; } } // ----------------------------------------------------------------- /// <summary> /// Initialise this shared module /// </summary> /// <param name="scene">this region is getting initialised</param> /// <param name="source">nini config, we are not using this</param> // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { try { if ((m_config = config.Configs["JsonStore"]) == null) { // There is no configuration, the module is disabled // m_log.InfoFormat("[JsonStoreScripts] no configuration info"); return; } m_enabled = m_config.GetBoolean("Enabled", m_enabled); } catch (Exception e) { m_log.ErrorFormat("[JsonStoreScripts]: initialization error: {0}", e.Message); return; } if (m_enabled) m_log.DebugFormat("[JsonStoreScripts]: module is enabled"); } // ----------------------------------------------------------------- /// <summary> /// everything is loaded, perform post load configuration /// </summary> // ----------------------------------------------------------------- public void PostInitialise() { } // ----------------------------------------------------------------- /// <summary> /// Nothing to do on close /// </summary> // ----------------------------------------------------------------- public void Close() { } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void AddRegion(Scene scene) { scene.EventManager.OnScriptReset += HandleScriptReset; scene.EventManager.OnRemoveScript += HandleScriptReset; } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public void RemoveRegion(Scene scene) { scene.EventManager.OnScriptReset -= HandleScriptReset; scene.EventManager.OnRemoveScript -= HandleScriptReset; // need to remove all references to the scene in the subscription // list to enable full garbage collection of the scene object } // ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- private void HandleScriptReset(uint localID, UUID itemID) { HashSet<UUID> stores; lock (m_scriptStores) { if (! m_scriptStores.TryGetValue(itemID, out stores)) return; m_scriptStores.Remove(itemID); } foreach (UUID id in stores) m_store.DestroyStore(id); } // ----------------------------------------------------------------- /// <summary> /// Called when all modules have been added for a region. This is /// where we hook up events /// </summary> // ----------------------------------------------------------------- public void RegionLoaded(Scene scene) { if (m_enabled) { m_scene = scene; m_comms = m_scene.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) { m_log.ErrorFormat("[JsonStoreScripts]: ScriptModuleComms interface not defined"); m_enabled = false; return; } m_store = m_scene.RequestModuleInterface<IJsonStoreModule>(); if (m_store == null) { m_log.ErrorFormat("[JsonStoreScripts]: JsonModule interface not defined"); m_enabled = false; return; } try { m_comms.RegisterScriptInvocations(this); m_comms.RegisterConstants(this); } catch (Exception e) { // See http://opensimulator.org/mantis/view.php?id=5971 for more information m_log.WarnFormat("[JsonStoreScripts]: script method registration failed; {0}", e.Message); m_enabled = false; } } } /// ----------------------------------------------------------------- /// <summary> /// </summary> // ----------------------------------------------------------------- public Type ReplaceableInterface { get { return null; } } #endregion #region ScriptConstantsInterface [ScriptConstant] public static readonly int JSON_NODETYPE_UNDEF = (int)JsonStoreNodeType.Undefined; [ScriptConstant] public static readonly int JSON_NODETYPE_OBJECT = (int)JsonStoreNodeType.Object; [ScriptConstant] public static readonly int JSON_NODETYPE_ARRAY = (int)JsonStoreNodeType.Array; [ScriptConstant] public static readonly int JSON_NODETYPE_VALUE = (int)JsonStoreNodeType.Value; [ScriptConstant] public static readonly int JSON_VALUETYPE_UNDEF = (int)JsonStoreValueType.Undefined; [ScriptConstant] public static readonly int JSON_VALUETYPE_BOOLEAN = (int)JsonStoreValueType.Boolean; [ScriptConstant] public static readonly int JSON_VALUETYPE_INTEGER = (int)JsonStoreValueType.Integer; [ScriptConstant] public static readonly int JSON_VALUETYPE_FLOAT = (int)JsonStoreValueType.Float; [ScriptConstant] public static readonly int JSON_VALUETYPE_STRING = (int)JsonStoreValueType.String; #endregion #region ScriptInvocationInteface // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonAttachObjectStore(UUID hostID, UUID scriptID) { UUID uuid = UUID.Zero; if (! m_store.AttachObjectStore(hostID)) GenerateRuntimeError("Failed to create Json store"); return hostID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonCreateStore(UUID hostID, UUID scriptID, string value) { UUID uuid = UUID.Zero; if (! m_store.CreateStore(value, ref uuid)) GenerateRuntimeError("Failed to create Json store"); lock (m_scriptStores) { if (! m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID] = new HashSet<UUID>(); m_scriptStores[scriptID].Add(uuid); } return uuid; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonDestroyStore(UUID hostID, UUID scriptID, UUID storeID) { lock(m_scriptStores) { if (m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID].Remove(storeID); } return m_store.DestroyStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonTestStore(UUID hostID, UUID scriptID, UUID storeID) { return m_store.TestStore(storeID) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonRezAtRoot(UUID hostID, UUID scriptID, string item, Vector3 pos, Vector3 vel, Quaternion rot, string param) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonRezObject(hostID, scriptID, reqID, item, pos, vel, rot, param), null, "JsonStoreScriptModule.DoJsonRezObject"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier), null, "JsonStoreScriptModule.JsonReadNotecard"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonWriteNotecard(UUID hostID, UUID scriptID, UUID storeID, string path, string name) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonWriteNotecard(reqID,hostID,scriptID,storeID,path,name), null, "JsonStoreScriptModule.DoJsonWriteNotecard"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonList2Path(UUID hostID, UUID scriptID, object[] pathlist) { string ipath = ConvertList2Path(pathlist); string opath; if (JsonStore.CanonicalPathExpression(ipath,out opath)) return opath; // This won't parse if passed to the other routines as opposed to // returning an empty string which is a valid path and would overwrite // the entire store return "**INVALID**"; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetNodeType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetNodeType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetValueType(UUID hostID, UUID scriptID, UUID storeID, string path) { return (int)m_store.GetValueType(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonSetValue(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,false) ? 1 : 0; } [ScriptInvocation] public int JsonSetJson(UUID hostID, UUID scriptID, UUID storeID, string path, string value) { return m_store.SetValue(storeID,path,value,true) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonRemoveValue(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.RemoveValue(storeID,path) ? 1 : 0; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public int JsonGetArrayLength(UUID hostID, UUID scriptID, UUID storeID, string path) { return m_store.GetArrayLength(storeID,path); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public string JsonGetValue(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,false,out value); return value; } [ScriptInvocation] public string JsonGetJson(UUID hostID, UUID scriptID, UUID storeID, string path) { string value = String.Empty; m_store.GetValue(storeID,path,true, out value); return value; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonTakeValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonTakeValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonTakeValue"); return reqID; } [ScriptInvocation] public UUID JsonTakeValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonTakeValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonTakeValueJson"); return reqID; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- [ScriptInvocation] public UUID JsonReadValue(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadValue(scriptID,reqID,storeID,path,false), null, "JsonStoreScriptModule.DoJsonReadValue"); return reqID; } [ScriptInvocation] public UUID JsonReadValueJson(UUID hostID, UUID scriptID, UUID storeID, string path) { UUID reqID = UUID.Random(); Util.FireAndForget( o => DoJsonReadValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonReadValueJson"); return reqID; } #endregion // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void GenerateRuntimeError(string msg) { m_log.InfoFormat("[JsonStore] runtime error: {0}",msg); throw new Exception("JsonStore Runtime Error: " + msg); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- protected void DispatchValue(UUID scriptID, UUID reqID, string value) { m_comms.DispatchReply(scriptID,1,value,reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.TakeValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) { try { m_store.ReadValue(storeID,path,useJson,delegate(string value) { DispatchValue(scriptID,reqID,value); }); return; } catch (Exception e) { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonReadNotecard( UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string notecardIdentifier) { UUID assetID; if (!UUID.TryParse(notecardIdentifier, out assetID)) { SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard); } AssetBase a = m_scene.AssetService.Get(assetID.ToString()); if (a == null) GenerateRuntimeError(String.Format("Unable to find notecard asset {0}", assetID)); if (a.Type != (sbyte)AssetType.Notecard) GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID)); m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID); try { string jsondata = SLUtil.ParseNotecardToString(a.Data); int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0; m_comms.DispatchReply(scriptID, result, "", reqID.ToString()); return; } catch(SLUtil.NotANotecardFormatException e) { m_log.WarnFormat("[JsonStoreScripts]: Notecard parsing failed; assetId {0} at line number {1}", assetID.ToString(), e.lineNumber); } catch (Exception e) { m_log.WarnFormat("[JsonStoreScripts]: Json parsing failed; {0}", e.Message); } GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID)); m_comms.DispatchReply(scriptID, 0, "", reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name) { string data; if (! m_store.GetValue(storeID,path,true, out data)) { m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString()); return; } SceneObjectPart host = m_scene.GetSceneObjectPart(hostID); // Create new asset UUID assetID = UUID.Random(); AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString()); asset.Description = "Json store"; int textLength = data.Length; data = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " + textLength.ToString() + "\n" + data + "}\n"; asset.Data = Util.UTF8.GetBytes(data); m_scene.AssetService.Store(asset); // Create Task Entry TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ResetIDs(host.UUID); taskItem.ParentID = host.UUID; taskItem.CreationDate = (uint)Util.UnixTimeSinceEpoch(); taskItem.Name = asset.Name; taskItem.Description = asset.Description; taskItem.Type = (int)AssetType.Notecard; taskItem.InvType = (int)InventoryType.Notecard; taskItem.OwnerID = host.OwnerID; taskItem.CreatorID = host.OwnerID; taskItem.BasePermissions = (uint)PermissionMask.All; taskItem.CurrentPermissions = (uint)PermissionMask.All; taskItem.EveryonePermissions = 0; taskItem.NextPermissions = (uint)PermissionMask.All; taskItem.GroupID = host.GroupID; taskItem.GroupPermissions = 0; taskItem.Flags = 0; taskItem.PermsGranter = UUID.Zero; taskItem.PermsMask = 0; taskItem.AssetID = asset.FullID; host.Inventory.AddInventoryItem(taskItem, false); m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString()); } // ----------------------------------------------------------------- /// <summary> /// Convert a list of values that are path components to a single string path /// </summary> // ----------------------------------------------------------------- protected static Regex m_ArrayPattern = new Regex("^([0-9]+|\\+)$"); private string ConvertList2Path(object[] pathlist) { string path = ""; for (int i = 0; i < pathlist.Length; i++) { string token = ""; if (pathlist[i] is string) { token = pathlist[i].ToString(); // Check to see if this is a bare number which would not be a valid // identifier otherwise if (m_ArrayPattern.IsMatch(token)) token = '[' + token + ']'; } else if (pathlist[i] is int) { token = "[" + pathlist[i].ToString() + "]"; } else { token = "." + pathlist[i].ToString() + "."; } path += token + "."; } return path; } // ----------------------------------------------------------------- /// <summary> /// /// </summary> // ----------------------------------------------------------------- private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param) { if (Double.IsNaN(rot.X) || Double.IsNaN(rot.Y) || Double.IsNaN(rot.Z) || Double.IsNaN(rot.W)) { GenerateRuntimeError("Invalid rez rotation"); return; } SceneObjectGroup host = m_scene.GetSceneObjectGroup(hostID); if (host == null) { GenerateRuntimeError(String.Format("Unable to find rezzing host '{0}'",hostID)); return; } // hpos = host.RootPart.GetWorldPosition() // float dist = (float)llVecDist(hpos, pos); // if (dist > m_ScriptDistanceFactor * 10.0f) // return; TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name); if (item == null) { GenerateRuntimeError(String.Format("Unable to find object to rez '{0}'",name)); return; } if (item.InvType != (int)InventoryType.Object) { GenerateRuntimeError("Can't create requested object; object is missing from database"); return; } List<SceneObjectGroup> objlist; List<Vector3> veclist; Vector3 bbox = new Vector3(); float offsetHeight; bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist, out bbox, out offsetHeight); if (! success) { GenerateRuntimeError("Failed to create object"); return; } int totalPrims = 0; foreach (SceneObjectGroup group in objlist) totalPrims += group.PrimCount; if (! m_scene.Permissions.CanRezObject(totalPrims, item.OwnerID, pos)) { GenerateRuntimeError("Not allowed to create the object"); return; } if (! m_scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) host.RootPart.Inventory.RemoveInventoryItem(item.ItemID); } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup group = objlist[i]; Vector3 curpos = pos + veclist[i]; if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } group.FromPartID = host.RootPart.UUID; m_scene.AddNewSceneObject(group, true, curpos, rot, vel); UUID storeID = group.UUID; if (! m_store.CreateStore(param, ref storeID)) { GenerateRuntimeError("Unable to create jsonstore for new object"); continue; } // We can only call this after adding the scene object, since the scene object references the scene // to find out if scripts should be activated at all. group.RootPart.SetDieAtEdge(true); group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 3); group.ResumeScripts(); group.ScheduleGroupForFullUpdate(); // send the reply back to the host object, use the integer param to indicate the number // of remaining objects m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString()); } } } }
//----------------------------------------------------------------------- // <copyright file="AnchorController.cs" company="Google LLC"> // // Copyright 2018 Google LLC. 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.CloudAnchors { using GoogleARCore; using GoogleARCore.CrossPlatform; using UnityEngine; using UnityEngine.Networking; /// <summary> /// A Controller for the Anchor object that handles hosting and resolving the Cloud Anchor. /// </summary> #pragma warning disable 618 public class AnchorController : NetworkBehaviour #pragma warning restore 618 { /// <summary> /// The customized timeout duration for resolving request to prevent retrying to resolve /// indefinitely. /// </summary> private const float k_ResolvingTimeout = 10.0f; /// <summary> /// The Cloud Anchor ID that will be used to host and resolve the Cloud Anchor. This /// variable will be syncrhonized over all clients. /// </summary> #pragma warning disable 618 [SyncVar(hook = "_OnChangeId")] #pragma warning restore 618 private string m_CloudAnchorId = string.Empty; /// <summary> /// Indicates whether this script is running in the Host. /// </summary> private bool m_IsHost = false; /// <summary> /// Indicates whether an attempt to resolve the Cloud Anchor should be made. /// </summary> private bool m_ShouldResolve = false; /// <summary> /// Record the time since started resolving. /// If it passed the resolving timeout, additional instruction displays. /// </summary> private float m_TimeSinceStartResolving = 0.0f; /// <summary> /// Indicates whether passes the resolving timeout duration or the anchor has been /// successfully resolved. /// </summary> private bool m_PassedResolvingTimeout = false; /// <summary> /// The anchor mesh object. /// In order to avoid placing the Anchor on identity pose, the mesh object should /// be disabled by default and enabled after hosted or resolved. /// </summary> private GameObject m_AnchorMesh; /// <summary> /// The Cloud Anchors example controller. /// </summary> private CloudAnchorsExampleController m_CloudAnchorsExampleController; /// <summary> /// The Unity Awake() method. /// </summary> public void Awake() { m_CloudAnchorsExampleController = GameObject.Find("CloudAnchorsExampleController") .GetComponent<CloudAnchorsExampleController>(); m_AnchorMesh = transform.Find("AnchorMesh").gameObject; m_AnchorMesh.SetActive(false); } /// <summary> /// The Unity OnStartClient() method. /// </summary> public override void OnStartClient() { if (m_CloudAnchorId != string.Empty) { m_ShouldResolve = true; } } /// <summary> /// The Unity Update() method. /// </summary> public void Update() { if (!m_ShouldResolve) { return; } if (!m_CloudAnchorsExampleController.IsResolvingPrepareTimePassed()) { return; } if (!m_PassedResolvingTimeout) { m_TimeSinceStartResolving += Time.deltaTime; if (m_TimeSinceStartResolving > k_ResolvingTimeout) { m_PassedResolvingTimeout = true; m_CloudAnchorsExampleController.OnResolvingTimeoutPassed(); } } _ResolveAnchorFromId(m_CloudAnchorId); } /// <summary> /// Command run on the server to set the Cloud Anchor Id. /// </summary> /// <param name="cloudAnchorId">The new Cloud Anchor Id.</param> #pragma warning disable 618 [Command] #pragma warning restore 618 public void CmdSetCloudAnchorId(string cloudAnchorId) { m_CloudAnchorId = cloudAnchorId; } /// <summary> /// Gets the Cloud Anchor Id. /// </summary> /// <returns>The Cloud Anchor Id.</returns> public string GetCloudAnchorId() { return m_CloudAnchorId; } /// <summary> /// Hosts the user placed cloud anchor and associates the resulting Id with this object. /// </summary> /// <param name="lastPlacedAnchor">The last placed anchor.</param> public void HostLastPlacedAnchor(Component lastPlacedAnchor) { m_IsHost = true; m_AnchorMesh.SetActive(true); #if !UNITY_IOS var anchor = (Anchor)lastPlacedAnchor; #elif ARCORE_IOS_SUPPORT var anchor = (UnityEngine.XR.iOS.UnityARUserAnchorComponent)lastPlacedAnchor; #endif #if !UNITY_IOS || ARCORE_IOS_SUPPORT XPSession.CreateCloudAnchor(anchor).ThenAction(result => { if (result.Response != CloudServiceResponse.Success) { Debug.Log(string.Format("Failed to host Cloud Anchor: {0}", result.Response)); m_CloudAnchorsExampleController.OnAnchorHosted( false, result.Response.ToString()); return; } Debug.Log(string.Format( "Cloud Anchor {0} was created and saved.", result.Anchor.CloudId)); CmdSetCloudAnchorId(result.Anchor.CloudId); m_CloudAnchorsExampleController.OnAnchorHosted(true, result.Response.ToString()); }); #endif } /// <summary> /// Resolves an anchor id and instantiates an Anchor prefab on it. /// </summary> /// <param name="cloudAnchorId">Cloud anchor id to be resolved.</param> private void _ResolveAnchorFromId(string cloudAnchorId) { m_CloudAnchorsExampleController.OnAnchorInstantiated(false); // If device is not tracking, let's wait to try to resolve the anchor. if (Session.Status != SessionStatus.Tracking) { return; } m_ShouldResolve = false; XPSession.ResolveCloudAnchor(cloudAnchorId).ThenAction( (System.Action<CloudAnchorResult>)(result => { if (result.Response != CloudServiceResponse.Success) { Debug.LogError(string.Format( "Client could not resolve Cloud Anchor {0}: {1}", cloudAnchorId, result.Response)); m_CloudAnchorsExampleController.OnAnchorResolved( false, result.Response.ToString()); m_ShouldResolve = true; return; } Debug.Log(string.Format( "Client successfully resolved Cloud Anchor {0}.", cloudAnchorId)); m_CloudAnchorsExampleController.OnAnchorResolved( true, result.Response.ToString()); _OnResolved(result.Anchor.transform); m_AnchorMesh.SetActive(true); })); } /// <summary> /// Callback invoked once the Cloud Anchor is resolved. /// </summary> /// <param name="anchorTransform">Transform of the resolved Cloud Anchor.</param> private void _OnResolved(Transform anchorTransform) { var cloudAnchorController = GameObject.Find("CloudAnchorsExampleController") .GetComponent<CloudAnchorsExampleController>(); cloudAnchorController.SetWorldOrigin(anchorTransform); // Mark resolving timeout passed so it won't fire OnResolvingTimeoutPassed event. m_PassedResolvingTimeout = true; } /// <summary> /// Callback invoked once the Cloud Anchor Id changes. /// </summary> /// <param name="newId">New identifier.</param> private void _OnChangeId(string newId) { if (!m_IsHost && newId != string.Empty) { m_CloudAnchorId = newId; m_ShouldResolve = true; } } } }
// // Created by Shopify. // Copyright (c) 2016 Shopify Inc. All rights reserved. // Copyright (c) 2016 Xamarin Inc. All rights reserved. // // 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.Threading.Tasks; using Android.App; using Android.Content; using Android.OS; using Android.Widget; using Square.Retrofit; using Shopify.Buy; using Shopify.Buy.DataProvider; using Shopify.Buy.Model; namespace ShopifyAndroidSample.Activities.Base { // Base class for all activities in the app. Manages the ProgressDialog that is displayed while network activity is occurring. public class SampleActivity : Activity { // The amount of time in milliseconds to delay between network calls when you are polling for Shipping Rates and Checkout Completion protected const int PollDelay = 500; private ProgressDialog progressDialog; private bool webCheckoutInProgress; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); InitializeProgressDialog(); } protected async override void OnResume() { base.OnResume(); // If we are being launched by a url scheme, check the scheme and retrieve the checkout token if provided var uri = Intent.Data; var scheme = GetString(Resource.String.web_return_to_scheme); if (uri != null && uri.Scheme == scheme) { webCheckoutInProgress = false; // If the app was launched using the scheme, we know we just successfully completed an order OnCheckoutComplete(); } else { // If a Web checkout was previously launched, we should check its status if (webCheckoutInProgress && SampleApplication.Checkout != null) { await PollCheckoutCompletionStatusAsync(SampleApplication.Checkout); } } } protected override void OnDestroy() { base.OnDestroy(); progressDialog?.Dismiss(); } protected SampleApplication SampleApplication { get { return (SampleApplication)Application; } } // Initializes a simple progress dialog that gets presented while the app is communicating with the server. private void InitializeProgressDialog() { progressDialog?.Dismiss(); progressDialog = new ProgressDialog(this); progressDialog.Indeterminate = true; progressDialog.SetTitle(GetString(Resource.String.please_wait)); progressDialog.SetCancelable(true); progressDialog.CancelEvent += delegate { Finish(); }; } // Present the progress dialog. protected void ShowLoadingDialog(int messageId) { progressDialog.SetMessage(GetString(messageId)); progressDialog.Show(); } protected void DismissLoadingDialog() { progressDialog.Dismiss(); } protected void OnError(RetrofitError error) { OnError(BuyClient.GetErrorBody(error)); } // When we encounter an error with one of our network calls, we abort and return to the previous activity. // In a production app, you'll want to handle these types of errors more gracefully. protected void OnError(string errorMessage) { progressDialog.Dismiss(); Console.WriteLine("Error: " + errorMessage); Toast.MakeText(this, Resource.String.error, ToastLength.Long).Show(); Finish(); } // Use the latest Checkout objects details to populate the text views in the order summary section. protected void UpdateOrderSummary() { var checkout = SampleApplication.Checkout; if (checkout == null) { return; } FindViewById<TextView>(Resource.Id.line_item_price_value).Text = checkout.Currency + " " + checkout.LineItems[0].Price; var totalDiscount = 0.0; var discount = checkout.Discount; if (discount != null && !string.IsNullOrEmpty(discount.Amount)) { totalDiscount += double.Parse(discount.Amount); } FindViewById<TextView>(Resource.Id.discount_value).Text = "-" + checkout.Currency + " " + totalDiscount; var totalGiftCards = 0.0; var giftCards = checkout.GiftCards; if (giftCards != null) { foreach (var giftCard in giftCards) { if (!string.IsNullOrEmpty(giftCard.AmountUsed)) { totalGiftCards += double.Parse(giftCard.AmountUsed); } } } FindViewById<TextView>(Resource.Id.gift_card_value).Text = "-" + checkout.Currency + " " + totalGiftCards; FindViewById<TextView>(Resource.Id.taxes_value).Text = checkout.Currency + " " + checkout.TotalTax; FindViewById<TextView>(Resource.Id.total_value).Text = checkout.Currency + " " + checkout.PaymentDue; if (checkout.ShippingRate != null) { FindViewById<TextView>(Resource.Id.shipping_value).Text = checkout.Currency + " " + checkout.ShippingRate.Price; } else { FindViewById<TextView>(Resource.Id.shipping_value).Text = "N/A"; } } // Polls until the web checkout has completed. protected async Task PollCheckoutCompletionStatusAsync(Checkout checkout) { ShowLoadingDialog(Resource.String.getting_checkout_status); try { bool complete; while (!(complete = await SampleApplication.GetCheckoutCompletionStatusAsync())) { await Task.Delay(PollDelay); } DismissLoadingDialog(); OnCheckoutComplete(); } catch (ShopifyException ex) { OnError(ex.Error); } } // When our polling determines that the checkout is completely processed, show a toast. private void OnCheckoutComplete() { DismissLoadingDialog(); webCheckoutInProgress = false; Toast.MakeText(this, Resource.String.checkout_complete, ToastLength.Long).Show(); } } }
// // System.Net.HttpConnection // // Author: // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com) // // Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; namespace Reactor.Net { public sealed class HttpConnection { private static AsyncCallback onread_cb = new AsyncCallback(OnRead); private const int BufferSize = 8192; private Socket sock; private Stream stream; private EndPointListener epl; private MemoryStream ms; private byte[] buffer; private HttpListenerContext context; private StringBuilder current_line; private ListenerPrefix prefix; private RequestStream i_stream; private ResponseStream o_stream; private bool chunked; private int reuses; private bool context_bound; private bool secure; private AsymmetricAlgorithm key; private int s_timeout = 90000; // 90k ms for first request, 15k ms from then on private Timer timer; private IPEndPoint local_ep; private HttpListener last_listener; private int[] client_cert_errors; private X509Certificate2 client_cert; public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key) { this.sock = sock; this.epl = epl; this.secure = secure; this.key = key; var networkstream = new NetworkStream(sock, false); if (secure) { var sslstream = new System.Net.Security.SslStream(networkstream); sslstream.AuthenticateAsServer(cert); stream = sslstream; } else { stream = networkstream; } timer = new Timer(OnTimeout, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); if (buffer == null) { buffer = new byte[BufferSize]; } Init(); } internal int[] ClientCertificateErrors { get { return client_cert_errors; } } internal X509Certificate2 ClientCertificate { get { return client_cert; } } bool OnClientCertificateValidation(X509Certificate certificate, int[] errors) { if (certificate == null) { return true; } X509Certificate2 cert = certificate as X509Certificate2; if (cert == null) { cert = new X509Certificate2(certificate.GetRawCertData()); } client_cert = cert; client_cert_errors = errors; return true; } AsymmetricAlgorithm OnPVKSelection(X509Certificate certificate, string targetHost) { return key; } void Init() { context_bound = false; i_stream = null; o_stream = null; prefix = null; chunked = false; ms = new MemoryStream(); position = 0; input_state = InputState.RequestLine; line_state = LineState.None; context = new HttpListenerContext(this); } public Stream Stream { get { return this.stream; } } public bool IsClosed { get { return (sock == null); } } public int Reuses { get { return reuses; } } public IPEndPoint LocalEndPoint { get { if (local_ep != null) { return local_ep; } local_ep = (IPEndPoint)sock.LocalEndPoint; return local_ep; } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)sock.RemoteEndPoint; } } public bool IsSecure { get { return secure; } } public ListenerPrefix Prefix { get { return prefix; } set { prefix = value; } } void OnTimeout(object unused) { CloseSocket(); Unbind(); } public void BeginReadRequest() { try { if (reuses == 1) { s_timeout = 15000; } timer.Change(s_timeout, System.Threading.Timeout.Infinite); stream.BeginRead(buffer, 0, BufferSize, onread_cb, this); } catch { timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); CloseSocket(); Unbind(); } } public RequestStream GetRequestStream(bool chunked, long contentlength) { if (i_stream == null) { byte[] buffer = ms.GetBuffer(); int length = (int)ms.Length; ms = null; if (chunked) { this.chunked = true; context.Response.SendChunked = true; i_stream = new ChunkedInputStream(context, stream, buffer, position, length - position); } else { i_stream = new RequestStream(stream, buffer, position, length - position, contentlength); } } return i_stream; } public ResponseStream GetResponseStream() { // TODO: can we get this stream before reading the input? if (o_stream == null) { HttpListener listener = context.Listener; bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions; o_stream = new ResponseStream(stream, context.Response, ign); } return o_stream; } static void OnRead(IAsyncResult ares) { HttpConnection cnc = (HttpConnection)ares.AsyncState; cnc.OnReadInternal(ares); } void OnReadInternal(IAsyncResult ares) { timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); int nread = -1; try { nread = stream.EndRead(ares); ms.Write(buffer, 0, nread); if (ms.Length > 32768) { SendError("Bad request", 400); Close(true); return; } } catch { if (ms != null && ms.Length > 0) { SendError(); } if (sock != null) { CloseSocket(); Unbind(); } return; } if (nread == 0) { //if (ms.Length > 0) // SendError (); // Why bother? CloseSocket(); Unbind(); return; } if (ProcessInput(ms)) { if (!context.HaveError) { context.Request.FinishInitialization(); } if (context.HaveError) { SendError(); Close(true); return; } if (!epl.BindContext(context)) { SendError("Invalid host", 400); Close(true); return; } HttpListener listener = context.Listener; if (last_listener != listener) { RemoveConnection(); listener.AddConnection(this); last_listener = listener; } context_bound = true; listener.RegisterContext(context); return; } stream.BeginRead(buffer, 0, BufferSize, onread_cb, this); } void RemoveConnection() { if (last_listener == null) { epl.RemoveConnection(this); } else { last_listener.RemoveConnection(this); } } enum InputState { RequestLine, Headers } enum LineState { None, CR, LF } InputState input_state = InputState.RequestLine; LineState line_state = LineState.None; int position; // true -> done processing // false -> need more input bool ProcessInput(MemoryStream ms) { byte[] buffer = ms.GetBuffer(); int len = (int)ms.Length; int used = 0; string line; try { line = ReadLine(buffer, position, len - position, ref used); position += used; } catch { context.ErrorMessage = "Bad request"; context.ErrorStatus = 400; return true; } do { if (line == null) { break; } if (line == "") { if (input_state == InputState.RequestLine) { continue; } current_line = null; ms = null; return true; } if (input_state == InputState.RequestLine) { context.Request.SetRequestLine(line); input_state = InputState.Headers; } else { try { context.Request.AddHeader(line); } catch (Exception e) { context.ErrorMessage = e.Message; context.ErrorStatus = 400; return true; } } if (context.HaveError) { return true; } if (position >= len) { break; } try { line = ReadLine(buffer, position, len - position, ref used); position += used; } catch { context.ErrorMessage = "Bad request"; context.ErrorStatus = 400; return true; } } while (line != null); if (used == len) { ms.SetLength(0); position = 0; } return false; } string ReadLine(byte[] buffer, int offset, int len, ref int used) { if (current_line == null) { current_line = new StringBuilder(128); } int last = offset + len; used = 0; for (int i = offset; i < last && line_state != LineState.LF; i++) { used++; byte b = buffer[i]; if (b == 13) { line_state = LineState.CR; } else if (b == 10) { line_state = LineState.LF; } else { current_line.Append((char)b); } } string result = null; if (line_state == LineState.LF) { line_state = LineState.None; result = current_line.ToString(); current_line.Length = 0; } return result; } public void SendError(string msg, int status) { try { HttpListenerResponse response = context.Response; response.StatusCode = status; response.ContentType = "text/html"; string description = HttpListenerResponse.GetStatusDescription(status); string str; if (msg != null) { str = String.Format("<h1>{0} ({1})</h1>", description, msg); } else { str = String.Format("<h1>{0}</h1>", description); } byte[] error = context.Response.ContentEncoding.GetBytes(str); response.Close(error, false); } catch { // response was already closed } } public void SendError() { SendError(context.ErrorMessage, context.ErrorStatus); } void Unbind() { if (context_bound) { epl.UnbindContext(context); context_bound = false; } } public void Close() { Close(false); } void CloseSocket() { if (sock == null) { return; } try { sock.Close(); } catch { } finally { sock = null; } RemoveConnection(); } internal void Close(bool force_close) { if (sock != null) { Stream st = GetResponseStream(); if (st != null) { st.Close(); } o_stream = null; } if (sock != null) { force_close |= !context.Request.KeepAlive; if (!force_close) { force_close = (context.Response.Headers["connection"] == "close"); } /* if (!force_close) { // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 || // status_code == 413 || status_code == 414 || status_code == 500 || // status_code == 503); force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10); } */ if (!force_close && context.Request.FlushInput()) { if (chunked && context.Response.ForceCloseChunked == false) { // Don't close. Keep working. reuses++; Unbind(); Init(); BeginReadRequest(); return; } reuses++; Unbind(); Init(); BeginReadRequest(); return; } Socket s = sock; sock = null; try { if (s != null) { s.Shutdown(SocketShutdown.Both); } } catch { } finally { if (s != null) { s.Close(); } } Unbind(); RemoveConnection(); try { this.timer.Dispose(); } catch { } return; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Tests.TestObjects.JsonTextReaderTests; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void BufferTest() { FakeArrayPool arrayPool = new FakeArrayPool(); string longString = new string('A', 2000); string longEscapedString = "Hello!" + new string('!', 50) + new string('\n', 1000) + "Good bye!"; string longerEscapedString = "Hello!" + new string('!', 2000) + new string('\n', 1000) + "Good bye!"; for (int i = 0; i < 1000; i++) { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue(longString); writer.WritePropertyName("Prop3"); writer.WriteValue(longEscapedString); writer.WritePropertyName("Prop4"); writer.WriteValue(longerEscapedString); writer.WriteEndObject(); } if ((i + 1) % 100 == 0) { Console.WriteLine("Allocated buffers: " + arrayPool.FreeArrays.Count); } } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(3, arrayPool.FreeArrays.Count); } [Test] public void BufferTest_WithError() { FakeArrayPool arrayPool = new FakeArrayPool(); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); try { // dispose will free used buffers using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)); writer.WritePropertyName("Prop2"); writer.WriteValue("This is an escaped \n string!"); writer.WriteValue("Error!"); } Assert.Fail(); } catch { } Assert.AreEqual(0, arrayPool.UsedArrays.Count); Assert.AreEqual(1, arrayPool.FreeArrays.Count); } #if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 [Test] public void BufferErroringWithInvalidSize() { JObject o = new JObject { {"BodyHtml", "<h3>Title!</h3>" + Environment.NewLine + new string(' ', 100) + "<p>Content!</p>"} }; JsonArrayPool arrayPool = new JsonArrayPool(); StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.ArrayPool = arrayPool; o.WriteTo(writer); } string result = o.ToString(); Assert.AreEqual(@"{ ""BodyHtml"": ""<h3>Title!</h3>\r\n <p>Content!</p>"" }", result); } #endif [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE) || NETSTANDARD2_0 [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } [Test] public void WriteTokenNullCheck() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null); }); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(null, true); }); } } [Test] public void TokenTypeOutOfRange() { using (JsonWriter jsonWriter = new JsonTextWriter(new StringWriter())) { ArgumentOutOfRangeException ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue)); Assert.AreEqual("token", ex.ParamName); ex = ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => jsonWriter.WriteToken((JsonToken)int.MinValue, "test")); Assert.AreEqual("token", ex.ParamName); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } [Test] public void WriteEndOnProperty_Close() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.Close(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } [Test] public void WriteEndOnProperty_Dispose() { StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); } Assert.AreEqual("{'Blah':null}", sw.ToString()); } [Test] public void AutoCompleteOnClose_False() { StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.AutoCompleteOnClose = false; writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); } Assert.AreEqual("{'Blah':", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] public void Culture() { CultureInfo culture = new CultureInfo("en-NZ"); culture.DateTimeFormat.AMDesignator = "a.m."; culture.DateTimeFormat.PMDesignator = "p.m."; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = culture; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) { throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); } c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) { unicodeBuffer = new char[6]; } StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } if (i > lastWritePosition) { if (chars == null) { chars = s.ToCharArray(); } // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) { writer.Write(escapedValue); } else { writer.Write(unicodeBuffer); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) { chars = s.ToCharArray(); } // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } [Test] public void DisposeSupressesFinalization() { UnmanagedResourceFakingJsonWriter.CreateAndDispose(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.AreEqual(1, UnmanagedResourceFakingJsonWriter.DisposalCalls); } } public class CustomJsonTextWriter : JsonTextWriter { protected readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) { _writer.Write(QuoteChar); } _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) { _writer.Write("}}}"); } else { base.WriteEnd(token); } } } public class UnmanagedResourceFakingJsonWriter : JsonWriter { public static int DisposalCalls; public static void CreateAndDispose() { ((IDisposable)new UnmanagedResourceFakingJsonWriter()).Dispose(); } public UnmanagedResourceFakingJsonWriter() { DisposalCalls = 0; } protected override void Dispose(bool disposing) { base.Dispose(disposing); ++DisposalCalls; } ~UnmanagedResourceFakingJsonWriter() { Dispose(false); } public override void Flush() { throw new NotImplementedException(); } } }
using System; using System.Globalization; using Prism.Events; using Prism.Logging; using Prism.Modularity; using Prism.Regions; using Prism.Unity.Properties; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using Prism.Mvvm; using Prism.Unity.Regions; namespace Prism.Unity { /// <summary> /// Base class that provides a basic bootstrapping sequence that /// registers most of the Prism Library assets /// in a <see cref="IUnityContainer"/>. /// </summary> /// <remarks> /// This class must be overridden to provide application specific configuration. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public abstract class UnityBootstrapper : Bootstrapper { private bool useDefaultConfiguration = true; /// <summary> /// Gets the default <see cref="IUnityContainer"/> for the application. /// </summary> /// <value>The default <see cref="IUnityContainer"/> instance.</value> public IUnityContainer Container { get; protected set; } /// <summary> /// Run the bootstrapper process. /// </summary> /// <param name="runWithDefaultConfiguration">If <see langword="true"/>, registers default Prism Library services in the container. This is the default behavior.</param> public override void Run(bool runWithDefaultConfiguration) { this.useDefaultConfiguration = runWithDefaultConfiguration; this.Logger = this.CreateLogger(); if (this.Logger == null) { throw new InvalidOperationException(Resources.NullLoggerFacadeException); } this.Logger.Log(Resources.LoggerCreatedSuccessfully, Category.Debug, Priority.Low); this.Logger.Log(Resources.CreatingModuleCatalog, Category.Debug, Priority.Low); this.ModuleCatalog = this.CreateModuleCatalog(); if (this.ModuleCatalog == null) { throw new InvalidOperationException(Resources.NullModuleCatalogException); } this.Logger.Log(Resources.ConfiguringModuleCatalog, Category.Debug, Priority.Low); this.ConfigureModuleCatalog(); this.Logger.Log(Resources.CreatingUnityContainer, Category.Debug, Priority.Low); this.Container = this.CreateContainer(); if (this.Container == null) { throw new InvalidOperationException(Resources.NullUnityContainerException); } this.Logger.Log(Resources.ConfiguringUnityContainer, Category.Debug, Priority.Low); this.ConfigureContainer(); this.Logger.Log(Resources.ConfiguringServiceLocatorSingleton, Category.Debug, Priority.Low); this.ConfigureServiceLocator(); this.Logger.Log(Resources.ConfiguringViewModelLocator, Category.Debug, Priority.Low); this.ConfigureViewModelLocator(); this.Logger.Log(Resources.ConfiguringRegionAdapters, Category.Debug, Priority.Low); this.ConfigureRegionAdapterMappings(); this.Logger.Log(Resources.ConfiguringDefaultRegionBehaviors, Category.Debug, Priority.Low); this.ConfigureDefaultRegionBehaviors(); this.Logger.Log(Resources.RegisteringFrameworkExceptionTypes, Category.Debug, Priority.Low); this.RegisterFrameworkExceptionTypes(); this.Logger.Log(Resources.CreatingShell, Category.Debug, Priority.Low); this.Shell = this.CreateShell(); if (this.Shell != null) { this.Logger.Log(Resources.SettingTheRegionManager, Category.Debug, Priority.Low); RegionManager.SetRegionManager(this.Shell, this.Container.Resolve<IRegionManager>()); this.Logger.Log(Resources.UpdatingRegions, Category.Debug, Priority.Low); RegionManager.UpdateRegions(); this.Logger.Log(Resources.InitializingShell, Category.Debug, Priority.Low); this.InitializeShell(); } if (this.Container.IsRegistered<IModuleManager>()) { this.Logger.Log(Resources.InitializingModules, Category.Debug, Priority.Low); this.InitializeModules(); } this.Logger.Log(Resources.BootstrapperSequenceCompleted, Category.Debug, Priority.Low); } /// <summary> /// Configures the LocatorProvider for the <see cref="ServiceLocator" />. /// </summary> protected override void ConfigureServiceLocator() { ServiceLocator.SetLocatorProvider(() => this.Container.Resolve<IServiceLocator>()); } /// <summary> /// Registers in the <see cref="IUnityContainer"/> the <see cref="Type"/> of the Exceptions /// that are not considered root exceptions by the <see cref="ExceptionExtensions"/>. /// </summary> protected override void RegisterFrameworkExceptionTypes() { base.RegisterFrameworkExceptionTypes(); ExceptionExtensions.RegisterFrameworkExceptionType( typeof(Microsoft.Practices.Unity.ResolutionFailedException)); } /// <summary> /// Configures the <see cref="IUnityContainer"/>. May be overwritten in a derived class to add specific /// type mappings required by the application. /// </summary> protected virtual void ConfigureContainer() { this.Logger.Log(Resources.AddingUnityBootstrapperExtensionToContainer, Category.Debug, Priority.Low); this.Container.AddNewExtension<UnityBootstrapperExtension>(); Container.RegisterInstance<ILoggerFacade>(Logger); this.Container.RegisterInstance(this.ModuleCatalog); if (useDefaultConfiguration) { RegisterTypeIfMissing(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), true); RegisterTypeIfMissing(typeof(IModuleInitializer), typeof(ModuleInitializer), true); RegisterTypeIfMissing(typeof(IModuleManager), typeof(ModuleManager), true); RegisterTypeIfMissing(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings), true); RegisterTypeIfMissing(typeof(IRegionManager), typeof(RegionManager), true); RegisterTypeIfMissing(typeof(IEventAggregator), typeof(EventAggregator), true); RegisterTypeIfMissing(typeof(IRegionViewRegistry), typeof(RegionViewRegistry), true); RegisterTypeIfMissing(typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory), true); RegisterTypeIfMissing(typeof(IRegionNavigationJournalEntry), typeof(RegionNavigationJournalEntry), false); RegisterTypeIfMissing(typeof(IRegionNavigationJournal), typeof(RegionNavigationJournal), false); RegisterTypeIfMissing(typeof(IRegionNavigationService), typeof(RegionNavigationService), false); RegisterTypeIfMissing(typeof(IRegionNavigationContentLoader), typeof(UnityRegionNavigationContentLoader), true); } } /// <summary> /// Initializes the modules. May be overwritten in a derived class to use a custom Modules Catalog /// </summary> protected override void InitializeModules() { IModuleManager manager; try { manager = this.Container.Resolve<IModuleManager>(); } catch (ResolutionFailedException ex) { if (ex.Message.Contains("IModuleCatalog")) { throw new InvalidOperationException(Resources.NullModuleCatalogException); } throw; } manager.Run(); } /// <summary> /// Creates the <see cref="IUnityContainer"/> that will be used as the default container. /// </summary> /// <returns>A new instance of <see cref="IUnityContainer"/>.</returns> protected virtual IUnityContainer CreateContainer() { return new UnityContainer(); } /// <summary> /// Registers a type in the container only if that type was not already registered. /// </summary> /// <param name="fromType">The interface type to register.</param> /// <param name="toType">The type implementing the interface.</param> /// <param name="registerAsSingleton">Registers the type as a singleton.</param> protected void RegisterTypeIfMissing(Type fromType, Type toType, bool registerAsSingleton) { if (fromType == null) { throw new ArgumentNullException("fromType"); } if (toType == null) { throw new ArgumentNullException("toType"); } if (Container.IsTypeRegistered(fromType)) { Logger.Log( String.Format(CultureInfo.CurrentCulture, Resources.TypeMappingAlreadyRegistered, fromType.Name), Category.Debug, Priority.Low); } else { if (registerAsSingleton) { Container.RegisterType(fromType, toType, new ContainerControlledLifetimeManager()); } else { Container.RegisterType(fromType, toType); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal sealed class PeWritingException : Exception { public PeWritingException(Exception inner) : base(inner.Message, inner) { } } internal sealed class PeWriter { private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; /// <summary> /// True if we should attempt to generate a deterministic output (no timestamps or random data). /// </summary> private readonly bool _deterministic; private readonly string _pdbPathOpt; private readonly bool _is32bit; private readonly ModulePropertiesForSerialization _properties; private readonly IEnumerable<IWin32Resource> _nativeResourcesOpt; private readonly ResourceSection _nativeResourceSectionOpt; private readonly BlobWriter _win32ResourceWriter = new BlobWriter(1024); private PeWriter( ModulePropertiesForSerialization properties, IEnumerable<IWin32Resource> nativeResourcesOpt, ResourceSection nativeResourceSectionOpt, string pdbPathOpt, bool deterministic) { _properties = properties; _pdbPathOpt = pdbPathOpt; _deterministic = deterministic; _nativeResourcesOpt = nativeResourcesOpt; _nativeResourceSectionOpt = nativeResourceSectionOpt; _is32bit = !_properties.Requires64bits; } private bool EmitPdb => _pdbPathOpt != null; public static bool WritePeToStream( EmitContext context, CommonMessageProvider messageProvider, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt, string pdbPathOpt, bool allowMissingMethodBodies, bool deterministic, CancellationToken cancellationToken) { // If PDB writer is given, we have to have PDB path. Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null); var peWriter = new PeWriter(context.Module.Properties, context.Module.Win32Resources, context.Module.Win32ResourceSection, pdbPathOpt, deterministic); var mdWriter = FullMetadataWriter.Create(context, messageProvider, allowMissingMethodBodies, deterministic, getPortablePdbStreamOpt != null, cancellationToken); return peWriter.WritePeToStream(mdWriter, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt); } private bool WritePeToStream(MetadataWriter mdWriter, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt) { // TODO: we can precalculate the exact size of IL stream var ilWriter = new BlobWriter(32 * 1024); var metadataWriter = new BlobWriter(16 * 1024); var mappedFieldDataWriter = new BlobWriter(); var managedResourceWriter = new BlobWriter(1024); var debugMetadataWriterOpt = (getPortablePdbStreamOpt != null) ? new BlobWriter(16 * 1024) : null; nativePdbWriterOpt?.SetMetadataEmitter(mdWriter); // Since we are producing a full assembly, we should not have a module version ID // imposed ahead-of time. Instead we will compute a deterministic module version ID // based on the contents of the generated stream. Debug.Assert(_properties.PersistentIdentifier == default(Guid)); int sectionCount = 1; if (_properties.RequiresStartupStub) sectionCount++; //.reloc if (!IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt) || _nativeResourceSectionOpt != null) sectionCount++; //.rsrc; int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount); int textSectionRva = BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment); int moduleVersionIdOffsetInMetadataStream; int methodBodyStreamRva = textSectionRva + OffsetToILStream; int entryPointToken; MetadataSizes metadataSizes; mdWriter.SerializeMetadataAndIL( metadataWriter, debugMetadataWriterOpt, nativePdbWriterOpt, ilWriter, mappedFieldDataWriter, managedResourceWriter, methodBodyStreamRva, mdSizes => CalculateMappedFieldDataStreamRva(textSectionRva, mdSizes), out moduleVersionIdOffsetInMetadataStream, out entryPointToken, out metadataSizes); ContentId nativePdbContentId; if (nativePdbWriterOpt != null) { if (entryPointToken != 0) { nativePdbWriterOpt.SetEntryPoint((uint)entryPointToken); } var assembly = mdWriter.Module.AsAssembly; if (assembly != null && assembly.Kind == OutputKind.WindowsRuntimeMetadata) { // Dev12: If compiling to winmdobj, we need to add to PDB source spans of // all types and members for better error reporting by WinMDExp. nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap()); } else { #if DEBUG // validate that all definitions are writable // if same scenario would happen in an winmdobj project nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap()); #endif } nativePdbContentId = nativePdbWriterOpt.GetContentId(); // the writer shall not be used after this point for writing: nativePdbWriterOpt = null; } else { nativePdbContentId = default(ContentId); } // Only the size of the fixed part of the debug table goes here. DirectoryEntry debugDirectory = default(DirectoryEntry); DirectoryEntry importTable = default(DirectoryEntry); DirectoryEntry importAddressTable = default(DirectoryEntry); int entryPointAddress = 0; if (EmitPdb) { debugDirectory = new DirectoryEntry(textSectionRva + ComputeOffsetToDebugTable(metadataSizes), ImageDebugDirectoryBaseSize); } if (_properties.RequiresStartupStub) { importAddressTable = new DirectoryEntry(textSectionRva, SizeOfImportAddressTable); entryPointAddress = CalculateMappedFieldDataStreamRva(textSectionRva, metadataSizes) - (_is32bit ? 6 : 10); // TODO: constants importTable = new DirectoryEntry(textSectionRva + ComputeOffsetToImportTable(metadataSizes), (_is32bit ? 66 : 70) + 13); // TODO: constants } var corHeaderDirectory = new DirectoryEntry(textSectionRva + SizeOfImportAddressTable, size: CorHeaderSize); long ntHeaderTimestampPosition; long metadataPosition; List<SectionHeader> sectionHeaders = CreateSectionHeaders(metadataSizes, sectionCount); CoffHeader coffHeader; NtHeader ntHeader; FillInNtHeader(sectionHeaders, entryPointAddress, corHeaderDirectory, importTable, importAddressTable, debugDirectory, out coffHeader, out ntHeader); Stream peStream = getPeStream(); if (peStream == null) { return false; } WriteHeaders(peStream, ntHeader, coffHeader, sectionHeaders, out ntHeaderTimestampPosition); WriteTextSection( peStream, sectionHeaders[0], importTable.RelativeVirtualAddress, importAddressTable.RelativeVirtualAddress, entryPointToken, metadataWriter, ilWriter, mappedFieldDataWriter, managedResourceWriter, metadataSizes, nativePdbContentId, out metadataPosition); var resourceSection = sectionHeaders.FirstOrDefault(s => s.Name == ResourceSectionName); if (resourceSection != null) { WriteResourceSection(peStream, resourceSection); } var relocSection = sectionHeaders.FirstOrDefault(s => s.Name == RelocationSectionName); if (relocSection != null) { WriteRelocSection(peStream, relocSection, entryPointAddress); } if (_deterministic) { var mvidPosition = metadataPosition + moduleVersionIdOffsetInMetadataStream; WriteDeterministicGuidAndTimestamps(peStream, mvidPosition, ntHeaderTimestampPosition); } return true; } private List<SectionHeader> CreateSectionHeaders(MetadataSizes metadataSizes, int sectionCount) { var sectionHeaders = new List<SectionHeader>(); SectionHeader lastSection; int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount); int sizeOfTextSection = ComputeSizeOfTextSection(metadataSizes); sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode, name: ".text", numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.FileAlignment), pointerToRelocations: 0, relativeVirtualAddress: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment), sizeOfRawData: BitArithmeticUtilities.Align(sizeOfTextSection, _properties.FileAlignment), virtualSize: sizeOfTextSection )); int resourcesRva = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment); int sizeOfWin32Resources = this.ComputeSizeOfWin32Resources(resourcesRva); if (sizeOfWin32Resources > 0) { sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData, name: ResourceSectionName, numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData, pointerToRelocations: 0, relativeVirtualAddress: resourcesRva, sizeOfRawData: BitArithmeticUtilities.Align(sizeOfWin32Resources, _properties.FileAlignment), virtualSize: sizeOfWin32Resources )); } if (_properties.RequiresStartupStub) { var size = (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) ? 14 : 12; // TODO: constants sectionHeaders.Add(lastSection = new SectionHeader( characteristics: SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData, name: RelocationSectionName, numberOfLinenumbers: 0, numberOfRelocations: 0, pointerToLinenumbers: 0, pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData, pointerToRelocations: 0, relativeVirtualAddress: BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment), sizeOfRawData: BitArithmeticUtilities.Align(size, _properties.FileAlignment), virtualSize: size)); } Debug.Assert(sectionHeaders.Count == sectionCount); return sectionHeaders; } private const string CorEntryPointDll = "mscoree.dll"; private string CorEntryPointName => (_properties.ImageCharacteristics & Characteristics.Dll) != 0 ? "_CorDllMain" : "_CorExeMain"; private int SizeOfImportAddressTable => _properties.RequiresStartupStub ? (_is32bit ? 2 * sizeof(uint) : 2 * sizeof(ulong)) : 0; // (_is32bit ? 66 : 70); private int SizeOfImportTable => sizeof(uint) + // RVA sizeof(uint) + // 0 sizeof(uint) + // 0 sizeof(uint) + // name RVA sizeof(uint) + // import address table RVA 20 + // ? (_is32bit ? 3 * sizeof(uint) : 2 * sizeof(ulong)) + // import lookup table sizeof(ushort) + // hint CorEntryPointName.Length + 1; // NUL private static int SizeOfNameTable => CorEntryPointDll.Length + 1 + sizeof(ushort); private int SizeOfRuntimeStartupStub => _is32bit ? 8 : 16; private int CalculateOffsetToMappedFieldDataStream(MetadataSizes metadataSizes) { int result = ComputeOffsetToImportTable(metadataSizes); if (_properties.RequiresStartupStub) { result += SizeOfImportTable + SizeOfNameTable; result = BitArithmeticUtilities.Align(result, _is32bit ? 4 : 8); //optional padding to make startup stub's target address align on word or double word boundary result += SizeOfRuntimeStartupStub; } return result; } private int CalculateMappedFieldDataStreamRva(int textSectionRva, MetadataSizes metadataSizes) { return textSectionRva + CalculateOffsetToMappedFieldDataStream(metadataSizes); } /// <summary> /// Compute a deterministic Guid and timestamp based on the contents of the stream, and replace /// the 16 zero bytes at the given position and one or two 4-byte values with that computed Guid and timestamp. /// </summary> /// <param name="peStream">PE stream.</param> /// <param name="mvidPosition">Position in the stream of 16 zero bytes to be replaced by a Guid</param> /// <param name="ntHeaderTimestampPosition">Position in the stream of four zero bytes to be replaced by a timestamp</param> private static void WriteDeterministicGuidAndTimestamps( Stream peStream, long mvidPosition, long ntHeaderTimestampPosition) { Debug.Assert(mvidPosition != 0); Debug.Assert(ntHeaderTimestampPosition != 0); var previousPosition = peStream.Position; // Compute and write deterministic guid data over the relevant portion of the stream peStream.Position = 0; var contentId = ContentId.FromHash(CryptographicHashProvider.ComputeSha1(peStream)); // The existing Guid should be zero. CheckZeroDataInStream(peStream, mvidPosition, contentId.Guid.Length); peStream.Position = mvidPosition; peStream.Write(contentId.Guid, 0, contentId.Guid.Length); // The existing timestamp should be zero. CheckZeroDataInStream(peStream, ntHeaderTimestampPosition, contentId.Stamp.Length); peStream.Position = ntHeaderTimestampPosition; peStream.Write(contentId.Stamp, 0, contentId.Stamp.Length); peStream.Position = previousPosition; } [Conditional("DEBUG")] private static void CheckZeroDataInStream(Stream stream, long position, int bytes) { stream.Position = position; for (int i = 0; i < bytes; i++) { int value = stream.ReadByte(); Debug.Assert(value == 0); } } private int ComputeOffsetToDebugTable(MetadataSizes metadataSizes) { Debug.Assert(metadataSizes.MetadataSize % 4 == 0); Debug.Assert(metadataSizes.ResourceDataSize % 4 == 0); return ComputeOffsetToMetadata(metadataSizes.ILStreamSize) + metadataSizes.MetadataSize + metadataSizes.ResourceDataSize + metadataSizes.StrongNameSignatureSize; } private int ComputeOffsetToImportTable(MetadataSizes metadataSizes) { return ComputeOffsetToDebugTable(metadataSizes) + ComputeSizeOfDebugDirectory(); } private const int CorHeaderSize = sizeof(int) + // header size sizeof(short) + // major runtime version sizeof(short) + // minor runtime version sizeof(long) + // metadata directory sizeof(int) + // COR flags sizeof(int) + // entry point sizeof(long) + // resources directory sizeof(long) + // strong name signature directory sizeof(long) + // code manager table directory sizeof(long) + // vtable fixups directory sizeof(long) + // export address table jumps directory sizeof(long); // managed-native header directory private int OffsetToILStream => SizeOfImportAddressTable + CorHeaderSize; private int ComputeOffsetToMetadata(int ilStreamLength) { return OffsetToILStream + BitArithmeticUtilities.Align(ilStreamLength, 4); } private const int ImageDebugDirectoryBaseSize = sizeof(uint) + // Characteristics sizeof(uint) + // TimeDataStamp sizeof(uint) + // Version sizeof(uint) + // Type sizeof(uint) + // SizeOfData sizeof(uint) + // AddressOfRawData sizeof(uint); // PointerToRawData private int ComputeSizeOfDebugDirectoryData() { return 4 + // 4B signature "RSDS" 16 + // GUID sizeof(uint) + // Age Encoding.UTF8.GetByteCount(_pdbPathOpt) + 1; // Null terminator } private int ComputeSizeOfDebugDirectory() { return EmitPdb ? ImageDebugDirectoryBaseSize + ComputeSizeOfDebugDirectoryData() : 0; } private int ComputeSizeOfPeHeaders(int sectionCount) { int sizeOfPeHeaders = 128 + 4 + 20 + 224 + 40 * sectionCount; // TODO: constants if (!_is32bit) { sizeOfPeHeaders += 16; } return sizeOfPeHeaders; } private int ComputeSizeOfTextSection(MetadataSizes metadataSizes) { Debug.Assert(metadataSizes.MappedFieldDataSize % MetadataWriter.MappedFieldDataAlignment == 0); return CalculateOffsetToMappedFieldDataStream(metadataSizes) + metadataSizes.MappedFieldDataSize; } private int ComputeSizeOfWin32Resources(int resourcesRva) { this.SerializeWin32Resources(resourcesRva); int result = 0; if (_win32ResourceWriter.Length > 0) { result += BitArithmeticUtilities.Align(_win32ResourceWriter.Length, 4); } // result += Align(this.win32ResourceWriter.Length+1, 8); return result; } private CorHeader CreateCorHeader(MetadataSizes metadataSizes, int textSectionRva, int entryPointToken) { int metadataRva = textSectionRva + ComputeOffsetToMetadata(metadataSizes.ILStreamSize); int resourcesRva = metadataRva + metadataSizes.MetadataSize; int signatureRva = resourcesRva + metadataSizes.ResourceDataSize; return new CorHeader( entryPointTokenOrRelativeVirtualAddress: entryPointToken, flags: _properties.GetCorHeaderFlags(), metadataDirectory: new DirectoryEntry(metadataRva, metadataSizes.MetadataSize), resourcesDirectory: new DirectoryEntry(resourcesRva, metadataSizes.ResourceDataSize), strongNameSignatureDirectory: new DirectoryEntry(signatureRva, metadataSizes.StrongNameSignatureSize)); } private void FillInNtHeader( List<SectionHeader> sectionHeaders, int entryPointAddress, DirectoryEntry corHeader, DirectoryEntry importTable, DirectoryEntry importAddressTable, DirectoryEntry debugTable, out CoffHeader coffHeader, out NtHeader ntHeader) { // In the PE File Header this is a "Time/Date Stamp" whose description is "Time and date // the file was created in seconds since January 1st 1970 00:00:00 or 0" // However, when we want to make it deterministic we fill it in (later) with bits from the hash of the full PE file. int timeStamp = _deterministic ? 0 : (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; short sectionCount = (short)sectionHeaders.Count; coffHeader = new CoffHeader( machine: (_properties.Machine == 0) ? Machine.I386 : _properties.Machine, numberOfSections: sectionCount, timeDateStamp: timeStamp, pointerToSymbolTable: 0, numberOfSymbols: 0, sizeOfOptionalHeader: (short)(_is32bit ? 224 : 240), // TODO: constants characteristics: _properties.ImageCharacteristics); SectionHeader codeSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsCode) != 0); SectionHeader dataSection = sectionHeaders.FirstOrDefault(sh => (sh.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0); ntHeader = new NtHeader(); ntHeader.Magic = _is32bit ? PEMagic.PE32 : PEMagic.PE32Plus; ntHeader.MajorLinkerVersion = _properties.LinkerMajorVersion; ntHeader.MinorLinkerVersion = _properties.LinkerMinorVersion; ntHeader.AddressOfEntryPoint = entryPointAddress; ntHeader.BaseOfCode = codeSection?.RelativeVirtualAddress ?? 0; ntHeader.BaseOfData = dataSection?.RelativeVirtualAddress ?? 0; ntHeader.ImageBase = _properties.BaseAddress; ntHeader.FileAlignment = _properties.FileAlignment; ntHeader.MajorSubsystemVersion = _properties.MajorSubsystemVersion; ntHeader.MinorSubsystemVersion = _properties.MinorSubsystemVersion; ntHeader.Subsystem = _properties.Subsystem; ntHeader.DllCharacteristics = _properties.DllCharacteristics; ntHeader.SizeOfStackReserve = _properties.SizeOfStackReserve; ntHeader.SizeOfStackCommit = _properties.SizeOfStackCommit; ntHeader.SizeOfHeapReserve = _properties.SizeOfHeapReserve; ntHeader.SizeOfHeapCommit = _properties.SizeOfHeapCommit; ntHeader.SizeOfCode = codeSection?.SizeOfRawData ?? 0; ntHeader.SizeOfInitializedData = sectionHeaders.Sum( sectionHeader => (sectionHeader.Characteristics & SectionCharacteristics.ContainsInitializedData) != 0 ? sectionHeader.SizeOfRawData : 0); ntHeader.SizeOfHeaders = BitArithmeticUtilities.Align(ComputeSizeOfPeHeaders(sectionCount), _properties.FileAlignment); var lastSection = sectionHeaders.Last(); ntHeader.SizeOfImage = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment); ntHeader.SizeOfUninitializedData = 0; ntHeader.ImportAddressTable = importAddressTable; ntHeader.CliHeaderTable = corHeader; ntHeader.ImportTable = importTable; var relocSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == RelocationSectionName); if (relocSection != null) { ntHeader.BaseRelocationTable = new DirectoryEntry(relocSection.RelativeVirtualAddress, relocSection.VirtualSize); } ntHeader.DebugTable = debugTable; var resourceSection = sectionHeaders.FirstOrDefault(sectionHeader => sectionHeader.Name == ResourceSectionName); if (resourceSection != null) { ntHeader.ResourceTable = new DirectoryEntry(resourceSection.RelativeVirtualAddress, resourceSection.VirtualSize); } } //// //// Resource Format. //// //// //// Resource directory consists of two counts, following by a variable length //// array of directory entries. The first count is the number of entries at //// beginning of the array that have actual names associated with each entry. //// The entries are in ascending order, case insensitive strings. The second //// count is the number of entries that immediately follow the named entries. //// This second count identifies the number of entries that have 16-bit integer //// Ids as their name. These entries are also sorted in ascending order. //// //// This structure allows fast lookup by either name or number, but for any //// given resource entry only one form of lookup is supported, not both. //// This is consistent with the syntax of the .RC file and the .RES file. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY { // DWORD Characteristics; // DWORD TimeDateStamp; // WORD MajorVersion; // WORD MinorVersion; // WORD NumberOfNamedEntries; // WORD NumberOfIdEntries; //// IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[]; //} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY; //#define IMAGE_RESOURCE_NAME_IS_STRING 0x80000000 //#define IMAGE_RESOURCE_DATA_IS_DIRECTORY 0x80000000 //// //// Each directory contains the 32-bit Name of the entry and an offset, //// relative to the beginning of the resource directory of the data associated //// with this directory entry. If the name of the entry is an actual text //// string instead of an integer Id, then the high order bit of the name field //// is set to one and the low order 31-bits are an offset, relative to the //// beginning of the resource directory of the string, which is of type //// IMAGE_RESOURCE_DIRECTORY_STRING. Otherwise the high bit is clear and the //// low-order 16-bits are the integer Id that identify this resource directory //// entry. If the directory entry is yet another resource directory (i.e. a //// subdirectory), then the high order bit of the offset field will be //// set to indicate this. Otherwise the high bit is clear and the offset //// field points to a resource data entry. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY { // union { // struct { // DWORD NameOffset:31; // DWORD NameIsString:1; // } DUMMYSTRUCTNAME; // DWORD Name; // WORD Id; // } DUMMYUNIONNAME; // union { // DWORD OffsetToData; // struct { // DWORD OffsetToDirectory:31; // DWORD DataIsDirectory:1; // } DUMMYSTRUCTNAME2; // } DUMMYUNIONNAME2; //} IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY; //// //// For resource directory entries that have actual string names, the Name //// field of the directory entry points to an object of the following type. //// All of these string objects are stored together after the last resource //// directory entry and before the first resource data object. This minimizes //// the impact of these variable length objects on the alignment of the fixed //// size directory entry objects. //// //typedef struct _IMAGE_RESOURCE_DIRECTORY_STRING { // WORD Length; // CHAR NameString[ 1 ]; //} IMAGE_RESOURCE_DIRECTORY_STRING, *PIMAGE_RESOURCE_DIRECTORY_STRING; //typedef struct _IMAGE_RESOURCE_DIR_STRING_U { // WORD Length; // WCHAR NameString[ 1 ]; //} IMAGE_RESOURCE_DIR_STRING_U, *PIMAGE_RESOURCE_DIR_STRING_U; //// //// Each resource data entry describes a leaf node in the resource directory //// tree. It contains an offset, relative to the beginning of the resource //// directory of the data for the resource, a size field that gives the number //// of bytes of data at that offset, a CodePage that should be used when //// decoding code point values within the resource data. Typically for new //// applications the code page would be the unicode code page. //// //typedef struct _IMAGE_RESOURCE_DATA_ENTRY { // DWORD OffsetToData; // DWORD Size; // DWORD CodePage; // DWORD Reserved; //} IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY; private class Directory { internal readonly string Name; internal readonly int ID; internal ushort NumberOfNamedEntries; internal ushort NumberOfIdEntries; internal readonly List<object> Entries; internal Directory(string name, int id) { this.Name = name; this.ID = id; this.Entries = new List<object>(); } } private static int CompareResources(IWin32Resource left, IWin32Resource right) { int result = CompareResourceIdentifiers(left.TypeId, left.TypeName, right.TypeId, right.TypeName); return (result == 0) ? CompareResourceIdentifiers(left.Id, left.Name, right.Id, right.Name) : result; } //when comparing a string vs ordinal, the string should always be less than the ordinal. Per the spec, //entries identified by string must precede those identified by ordinal. private static int CompareResourceIdentifiers(int xOrdinal, string xString, int yOrdinal, string yString) { if (xString == null) { if (yString == null) { return xOrdinal - yOrdinal; } else { return 1; } } else if (yString == null) { return -1; } else { return String.Compare(xString, yString, StringComparison.OrdinalIgnoreCase); } } //sort the resources by ID least to greatest then by NAME. //Where strings and ordinals are compared, strings are less than ordinals. internal static IEnumerable<IWin32Resource> SortResources(IEnumerable<IWin32Resource> resources) { return resources.OrderBy(CompareResources); } //Win32 resources are supplied to the compiler in one of two forms, .RES (the output of the resource compiler), //or .OBJ (the output of running cvtres.exe on a .RES file). A .RES file is parsed and processed into //a set of objects implementing IWin32Resources. These are then ordered and the final image form is constructed //and written to the resource section. Resources in .OBJ form are already very close to their final output //form. Rather than reading them and parsing them into a set of objects similar to those produced by //processing a .RES file, we process them like the native linker would, copy the relevant sections from //the .OBJ into our output and apply some fixups. private void SerializeWin32Resources(int resourcesRva) { if (_nativeResourceSectionOpt != null) { SerializeWin32Resources(_nativeResourceSectionOpt, resourcesRva); return; } if (IteratorHelper.EnumerableIsEmpty(_nativeResourcesOpt)) { return; } SerializeWin32Resources(_nativeResourcesOpt, resourcesRva); } private void SerializeWin32Resources(IEnumerable<IWin32Resource> theResources, int resourcesRva) { theResources = SortResources(theResources); Directory typeDirectory = new Directory(string.Empty, 0); Directory nameDirectory = null; Directory languageDirectory = null; int lastTypeID = int.MinValue; string lastTypeName = null; int lastID = int.MinValue; string lastName = null; uint sizeOfDirectoryTree = 16; //EDMAURER note that this list is assumed to be sorted lowest to highest //first by typeId, then by Id. foreach (IWin32Resource r in theResources) { bool typeDifferent = (r.TypeId < 0 && r.TypeName != lastTypeName) || r.TypeId > lastTypeID; if (typeDifferent) { lastTypeID = r.TypeId; lastTypeName = r.TypeName; if (lastTypeID < 0) { Debug.Assert(typeDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with types encoded as strings precede those encoded as ints"); typeDirectory.NumberOfNamedEntries++; } else { typeDirectory.NumberOfIdEntries++; } sizeOfDirectoryTree += 24; typeDirectory.Entries.Add(nameDirectory = new Directory(lastTypeName, lastTypeID)); } if (typeDifferent || (r.Id < 0 && r.Name != lastName) || r.Id > lastID) { lastID = r.Id; lastName = r.Name; if (lastID < 0) { Debug.Assert(nameDirectory.NumberOfIdEntries == 0, "Not all Win32 resources with names encoded as strings precede those encoded as ints"); nameDirectory.NumberOfNamedEntries++; } else { nameDirectory.NumberOfIdEntries++; } sizeOfDirectoryTree += 24; nameDirectory.Entries.Add(languageDirectory = new Directory(lastName, lastID)); } languageDirectory.NumberOfIdEntries++; sizeOfDirectoryTree += 8; languageDirectory.Entries.Add(r); } var dataWriter = BlobWriter.GetInstance(); //'dataWriter' is where opaque resource data goes as well as strings that are used as type or name identifiers this.WriteDirectory(typeDirectory, _win32ResourceWriter, 0, 0, sizeOfDirectoryTree, resourcesRva, dataWriter); dataWriter.WriteTo(_win32ResourceWriter); _win32ResourceWriter.WriteByte(0); while ((_win32ResourceWriter.Length % 4) != 0) { _win32ResourceWriter.WriteByte(0); } dataWriter.Free(); } private void WriteDirectory(Directory directory, BlobWriter writer, uint offset, uint level, uint sizeOfDirectoryTree, int virtualAddressBase, BlobWriter dataWriter) { writer.WriteUint(0); // Characteristics writer.WriteUint(0); // Timestamp writer.WriteUint(0); // Version writer.WriteUshort(directory.NumberOfNamedEntries); writer.WriteUshort(directory.NumberOfIdEntries); uint n = (uint)directory.Entries.Count; uint k = offset + 16 + n * 8; for (int i = 0; i < n; i++) { int id; string name; uint nameOffset = (uint)dataWriter.Position + sizeOfDirectoryTree; uint directoryOffset = k; Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { id = subDir.ID; name = subDir.Name; if (level == 0) { k += SizeOfDirectory(subDir); } else { k += 16 + 8 * (uint)subDir.Entries.Count; } } else { //EDMAURER write out an IMAGE_RESOURCE_DATA_ENTRY followed //immediately by the data that it refers to. This results //in a layout different than that produced by pulling the resources //from an OBJ. In that case all of the data bits of a resource are //contiguous in .rsrc$02. After processing these will end up at //the end of .rsrc following all of the directory //info and IMAGE_RESOURCE_DATA_ENTRYs IWin32Resource r = (IWin32Resource)directory.Entries[i]; id = level == 0 ? r.TypeId : level == 1 ? r.Id : (int)r.LanguageId; name = level == 0 ? r.TypeName : level == 1 ? r.Name : null; dataWriter.WriteUint((uint)(virtualAddressBase + sizeOfDirectoryTree + 16 + dataWriter.Position)); byte[] data = new List<byte>(r.Data).ToArray(); dataWriter.WriteUint((uint)data.Length); dataWriter.WriteUint(r.CodePage); dataWriter.WriteUint(0); dataWriter.WriteBytes(data); while ((dataWriter.Length % 4) != 0) { dataWriter.WriteByte(0); } } if (id >= 0) { writer.WriteInt(id); } else { if (name == null) { name = string.Empty; } writer.WriteUint(nameOffset | 0x80000000); dataWriter.WriteUshort((ushort)name.Length); dataWriter.WriteUTF16(name); } if (subDir != null) { writer.WriteUint(directoryOffset | 0x80000000); } else { writer.WriteUint(nameOffset); } } k = offset + 16 + n * 8; for (int i = 0; i < n; i++) { Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { this.WriteDirectory(subDir, writer, k, level + 1, sizeOfDirectoryTree, virtualAddressBase, dataWriter); if (level == 0) { k += SizeOfDirectory(subDir); } else { k += 16 + 8 * (uint)subDir.Entries.Count; } } } } private static uint SizeOfDirectory(Directory/*!*/ directory) { uint n = (uint)directory.Entries.Count; uint size = 16 + 8 * n; for (int i = 0; i < n; i++) { Directory subDir = directory.Entries[i] as Directory; if (subDir != null) { size += 16 + 8 * (uint)subDir.Entries.Count; } } return size; } private void SerializeWin32Resources(ResourceSection resourceSections, int resourcesRva) { _win32ResourceWriter.WriteBytes(resourceSections.SectionBytes); var savedPosition = _win32ResourceWriter.Position; var readStream = new MemoryStream(resourceSections.SectionBytes); var reader = new BinaryReader(readStream); foreach (int addressToFixup in resourceSections.Relocations) { _win32ResourceWriter.Position = addressToFixup; reader.BaseStream.Position = addressToFixup; _win32ResourceWriter.WriteUint(reader.ReadUInt32() + (uint)resourcesRva); } _win32ResourceWriter.Position = savedPosition; } //#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file. //#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // File is executable (i.e. no unresolved external references). //#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line numbers stripped from file. //#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // Local symbols stripped from file. //#define IMAGE_FILE_AGGRESIVE_WS_TRIM 0x0010 // Aggressively trim working set //#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // App can handle >2gb addresses //#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // Bytes of machine word are reversed. //#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine. //#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // Debugging info stripped from file in .DBG file //#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // If Image is on removable media, copy and run from the swap file. //#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // If Image is on Net, copy and run from the swap file. //#define IMAGE_FILE_SYSTEM 0x1000 // System File. //#define IMAGE_FILE_DLL 0x2000 // File is a DLL. //#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // File should only be run on a UP machine //#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // Bytes of machine word are reversed. private static readonly byte[] s_dosHeader = new byte[] { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; private void WriteHeaders(Stream peStream, NtHeader ntHeader, CoffHeader coffHeader, List<SectionHeader> sectionHeaders, out long ntHeaderTimestampPosition) { var writer = new BlobWriter(1024); // MS-DOS stub (128 bytes) writer.WriteBytes(s_dosHeader); // PE Signature "PE\0\0" writer.WriteUint(0x00004550); // COFF Header (20 bytes) writer.WriteUshort((ushort)coffHeader.Machine); writer.WriteUshort((ushort)coffHeader.NumberOfSections); ntHeaderTimestampPosition = writer.Position + peStream.Position; writer.WriteUint((uint)coffHeader.TimeDateStamp); writer.WriteUint((uint)coffHeader.PointerToSymbolTable); writer.WriteUint((uint)coffHeader.NumberOfSymbols); writer.WriteUshort((ushort)(_is32bit ? 224 : 240)); // SizeOfOptionalHeader writer.WriteUshort((ushort)coffHeader.Characteristics); // PE Headers: writer.WriteUshort((ushort)(_is32bit ? PEMagic.PE32 : PEMagic.PE32Plus)); // 2 writer.WriteByte(ntHeader.MajorLinkerVersion); // 3 writer.WriteByte(ntHeader.MinorLinkerVersion); // 4 writer.WriteUint((uint)ntHeader.SizeOfCode); // 8 writer.WriteUint((uint)ntHeader.SizeOfInitializedData); // 12 writer.WriteUint((uint)ntHeader.SizeOfUninitializedData); // 16 writer.WriteUint((uint)ntHeader.AddressOfEntryPoint); // 20 writer.WriteUint((uint)ntHeader.BaseOfCode); // 24 if (_is32bit) { writer.WriteUint((uint)ntHeader.BaseOfData); // 28 writer.WriteUint((uint)ntHeader.ImageBase); // 32 } else { writer.WriteUlong(ntHeader.ImageBase); // 32 } // NT additional fields: writer.WriteUint((uint)ntHeader.SectionAlignment); // 36 writer.WriteUint((uint)ntHeader.FileAlignment); // 40 writer.WriteUshort(ntHeader.MajorOperatingSystemVersion); // 42 writer.WriteUshort(ntHeader.MinorOperatingSystemVersion); // 44 writer.WriteUshort(ntHeader.MajorImageVersion); // 46 writer.WriteUshort(ntHeader.MinorImageVersion); // 48 writer.WriteUshort(ntHeader.MajorSubsystemVersion); // MajorSubsystemVersion 50 writer.WriteUshort(ntHeader.MinorSubsystemVersion); // MinorSubsystemVersion 52 // Win32VersionValue (reserved, should be 0) writer.WriteUint(0); // 56 writer.WriteUint((uint)ntHeader.SizeOfImage); // 60 writer.WriteUint((uint)ntHeader.SizeOfHeaders); // 64 writer.WriteUint(ntHeader.Checksum); // 68 writer.WriteUshort((ushort)ntHeader.Subsystem); // 70 writer.WriteUshort((ushort)ntHeader.DllCharacteristics); if (_is32bit) { writer.WriteUint((uint)ntHeader.SizeOfStackReserve); // 76 writer.WriteUint((uint)ntHeader.SizeOfStackCommit); // 80 writer.WriteUint((uint)ntHeader.SizeOfHeapReserve); // 84 writer.WriteUint((uint)ntHeader.SizeOfHeapCommit); // 88 } else { writer.WriteUlong(ntHeader.SizeOfStackReserve); // 80 writer.WriteUlong(ntHeader.SizeOfStackCommit); // 88 writer.WriteUlong(ntHeader.SizeOfHeapReserve); // 96 writer.WriteUlong(ntHeader.SizeOfHeapCommit); // 104 } // LoaderFlags writer.WriteUint(0); // 92|108 // The number of data-directory entries in the remainder of the header. writer.WriteUint(16); // 96|112 // directory entries: writer.WriteUint((uint)ntHeader.ExportTable.RelativeVirtualAddress); // 100|116 writer.WriteUint((uint)ntHeader.ExportTable.Size); // 104|120 writer.WriteUint((uint)ntHeader.ImportTable.RelativeVirtualAddress); // 108|124 writer.WriteUint((uint)ntHeader.ImportTable.Size); // 112|128 writer.WriteUint((uint)ntHeader.ResourceTable.RelativeVirtualAddress); // 116|132 writer.WriteUint((uint)ntHeader.ResourceTable.Size); // 120|136 writer.WriteUint((uint)ntHeader.ExceptionTable.RelativeVirtualAddress); // 124|140 writer.WriteUint((uint)ntHeader.ExceptionTable.Size); // 128|144 writer.WriteUint((uint)ntHeader.CertificateTable.RelativeVirtualAddress); // 132|148 writer.WriteUint((uint)ntHeader.CertificateTable.Size); // 136|152 writer.WriteUint((uint)ntHeader.BaseRelocationTable.RelativeVirtualAddress); // 140|156 writer.WriteUint((uint)ntHeader.BaseRelocationTable.Size); // 144|160 writer.WriteUint((uint)ntHeader.DebugTable.RelativeVirtualAddress); // 148|164 writer.WriteUint((uint)ntHeader.DebugTable.Size); // 152|168 writer.WriteUint((uint)ntHeader.CopyrightTable.RelativeVirtualAddress); // 156|172 writer.WriteUint((uint)ntHeader.CopyrightTable.Size); // 160|176 writer.WriteUint((uint)ntHeader.GlobalPointerTable.RelativeVirtualAddress); // 164|180 writer.WriteUint((uint)ntHeader.GlobalPointerTable.Size); // 168|184 writer.WriteUint((uint)ntHeader.ThreadLocalStorageTable.RelativeVirtualAddress); // 172|188 writer.WriteUint((uint)ntHeader.ThreadLocalStorageTable.Size); // 176|192 writer.WriteUint((uint)ntHeader.LoadConfigTable.RelativeVirtualAddress); // 180|196 writer.WriteUint((uint)ntHeader.LoadConfigTable.Size); // 184|200 writer.WriteUint((uint)ntHeader.BoundImportTable.RelativeVirtualAddress); // 188|204 writer.WriteUint((uint)ntHeader.BoundImportTable.Size); // 192|208 writer.WriteUint((uint)ntHeader.ImportAddressTable.RelativeVirtualAddress); // 196|212 writer.WriteUint((uint)ntHeader.ImportAddressTable.Size); // 200|216 writer.WriteUint((uint)ntHeader.DelayImportTable.RelativeVirtualAddress); // 204|220 writer.WriteUint((uint)ntHeader.DelayImportTable.Size); // 208|224 writer.WriteUint((uint)ntHeader.CliHeaderTable.RelativeVirtualAddress); // 212|228 writer.WriteUint((uint)ntHeader.CliHeaderTable.Size); // 216|232 writer.WriteUlong(0); // 224|240 // Section Headers foreach (var sectionHeader in sectionHeaders) { WriteSectionHeader(sectionHeader, writer); } writer.WriteTo(peStream); } private static void WriteSectionHeader(SectionHeader sectionHeader, BlobWriter writer) { if (sectionHeader.VirtualSize == 0) { return; } for (int j = 0, m = sectionHeader.Name.Length; j < 8; j++) { if (j < m) { writer.WriteByte((byte)sectionHeader.Name[j]); } else { writer.WriteByte(0); } } writer.WriteUint((uint)sectionHeader.VirtualSize); writer.WriteUint((uint)sectionHeader.RelativeVirtualAddress); writer.WriteUint((uint)sectionHeader.SizeOfRawData); writer.WriteUint((uint)sectionHeader.PointerToRawData); writer.WriteUint((uint)sectionHeader.PointerToRelocations); writer.WriteUint((uint)sectionHeader.PointerToLinenumbers); writer.WriteUshort(sectionHeader.NumberOfRelocations); writer.WriteUshort(sectionHeader.NumberOfLinenumbers); writer.WriteUint((uint)sectionHeader.Characteristics); } private void WriteTextSection( Stream peStream, SectionHeader textSection, int importTableRva, int importAddressTableRva, int entryPointToken, BlobWriter metadataWriter, BlobWriter ilWriter, BlobWriter mappedFieldDataWriter, BlobWriter managedResourceWriter, MetadataSizes metadataSizes, ContentId pdbContentId, out long metadataPosition) { // TODO: zero out all bytes: peStream.Position = textSection.PointerToRawData; if (_properties.RequiresStartupStub) { WriteImportAddressTable(peStream, importTableRva); } var corHeader = CreateCorHeader(metadataSizes, textSection.RelativeVirtualAddress, entryPointToken); WriteCorHeader(peStream, corHeader); // IL: ilWriter.Align(4); ilWriter.WriteTo(peStream); // metadata: metadataPosition = peStream.Position; Debug.Assert(metadataWriter.Length % 4 == 0); metadataWriter.WriteTo(peStream); // managed resources: Debug.Assert(managedResourceWriter.Length % 4 == 0); managedResourceWriter.WriteTo(peStream); // strong name signature: WriteSpaceForHash(peStream, metadataSizes.StrongNameSignatureSize); if (EmitPdb) { WriteDebugTable(peStream, textSection, pdbContentId, metadataSizes); } if (_properties.RequiresStartupStub) { WriteImportTable(peStream, importTableRva, importAddressTableRva); WriteNameTable(peStream); WriteRuntimeStartupStub(peStream, importAddressTableRva); } // mapped field data: mappedFieldDataWriter.WriteTo(peStream); // TODO: zero out all bytes: int alignedPosition = textSection.PointerToRawData + textSection.SizeOfRawData; if (peStream.Position != alignedPosition) { peStream.Position = alignedPosition - 1; peStream.WriteByte(0); } } private void WriteImportAddressTable(Stream peStream, int importTableRva) { var writer = new BlobWriter(SizeOfImportAddressTable); int ilRVA = importTableRva + 40; int hintRva = ilRVA + (_is32bit ? 12 : 16); // Import Address Table if (_is32bit) { writer.WriteUint((uint)hintRva); // 4 writer.WriteUint(0); // 8 } else { writer.WriteUlong((uint)hintRva); // 8 writer.WriteUlong(0); // 16 } Debug.Assert(writer.Length == SizeOfImportAddressTable); writer.WriteTo(peStream); } private void WriteImportTable(Stream peStream, int importTableRva, int importAddressTableRva) { var writer = new BlobWriter(SizeOfImportTable); int ilRVA = importTableRva + 40; int hintRva = ilRVA + (_is32bit ? 12 : 16); int nameRva = hintRva + 12 + 2; // Import table writer.WriteUint((uint)ilRVA); // 4 writer.WriteUint(0); // 8 writer.WriteUint(0); // 12 writer.WriteUint((uint)nameRva); // 16 writer.WriteUint((uint)importAddressTableRva); // 20 writer.Position += 20; // 40 // Import Lookup table if (_is32bit) { writer.WriteUint((uint)hintRva); // 44 writer.WriteUint(0); // 48 writer.WriteUint(0); // 52 } else { writer.WriteUlong((uint)hintRva); // 48 writer.WriteUlong(0); // 56 } // Hint table writer.WriteUshort(0); // Hint 54|58 foreach (char ch in CorEntryPointName) { writer.WriteByte((byte)ch); // 65|69 } writer.WriteByte(0); // 66|70 Debug.Assert(writer.Length == SizeOfImportTable); writer.WriteTo(peStream); } private static void WriteNameTable(Stream peStream) { var writer = new BlobWriter(SizeOfNameTable); foreach (char ch in CorEntryPointDll) { writer.WriteByte((byte)ch); } writer.WriteByte(0); writer.WriteUshort(0); Debug.Assert(writer.Length == SizeOfNameTable); writer.WriteTo(peStream); } private static void WriteCorHeader(Stream peStream, CorHeader corHeader) { var writer = new BlobWriter(CorHeaderSize); writer.WriteUint(CorHeaderSize); writer.WriteUshort(corHeader.MajorRuntimeVersion); writer.WriteUshort(corHeader.MinorRuntimeVersion); writer.WriteUint((uint)corHeader.MetadataDirectory.RelativeVirtualAddress); writer.WriteUint((uint)corHeader.MetadataDirectory.Size); writer.WriteUint((uint)corHeader.Flags); writer.WriteUint((uint)corHeader.EntryPointTokenOrRelativeVirtualAddress); writer.WriteUint((uint)(corHeader.ResourcesDirectory.Size == 0 ? 0 : corHeader.ResourcesDirectory.RelativeVirtualAddress)); // 28 writer.WriteUint((uint)corHeader.ResourcesDirectory.Size); writer.WriteUint((uint)(corHeader.StrongNameSignatureDirectory.Size == 0 ? 0 : corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress)); // 36 writer.WriteUint((uint)corHeader.StrongNameSignatureDirectory.Size); writer.WriteUint((uint)corHeader.CodeManagerTableDirectory.RelativeVirtualAddress); writer.WriteUint((uint)corHeader.CodeManagerTableDirectory.Size); writer.WriteUint((uint)corHeader.VtableFixupsDirectory.RelativeVirtualAddress); writer.WriteUint((uint)corHeader.VtableFixupsDirectory.Size); writer.WriteUint((uint)corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress); writer.WriteUint((uint)corHeader.ExportAddressTableJumpsDirectory.Size); writer.WriteUlong(0); Debug.Assert(writer.Length == CorHeaderSize); Debug.Assert(writer.Length % 4 == 0); writer.WriteTo(peStream); } private static void WriteSpaceForHash(Stream peStream, int strongNameSignatureSize) { while (strongNameSignatureSize > 0) { peStream.WriteByte(0); strongNameSignatureSize--; } } private void WriteDebugTable(Stream peStream, SectionHeader textSection, ContentId nativePdbContentId, MetadataSizes metadataSizes) { var writer = new BlobWriter(); // characteristics: writer.WriteUint(0); // PDB stamp writer.WriteBytes(nativePdbContentId.Stamp); // version writer.WriteUint(0); // type: const int ImageDebugTypeCodeView = 2; writer.WriteUint(ImageDebugTypeCodeView); // size of data: writer.WriteUint((uint)ComputeSizeOfDebugDirectoryData()); uint dataOffset = (uint)ComputeOffsetToDebugTable(metadataSizes) + ImageDebugDirectoryBaseSize; // PointerToRawData (RVA of the data): writer.WriteUint((uint)textSection.RelativeVirtualAddress + dataOffset); // AddressOfRawData (position of the data in the PE stream): writer.WriteUint((uint)textSection.PointerToRawData + dataOffset); writer.WriteByte((byte)'R'); writer.WriteByte((byte)'S'); writer.WriteByte((byte)'D'); writer.WriteByte((byte)'S'); // PDB id: writer.WriteBytes(nativePdbContentId.Guid); // age writer.WriteUint(PdbWriter.Age); // UTF-8 encoded zero-terminated path to PDB writer.WriteUTF8(_pdbPathOpt); writer.WriteByte(0); writer.WriteTo(peStream); writer.Free(); } private void WriteRuntimeStartupStub(Stream peStream, int importAddressTableRva) { var writer = new BlobWriter(16); // entry point code, consisting of a jump indirect to _CorXXXMain if (_is32bit) { //emit 0's (nops) to pad the entry point code so that the target address is aligned on a 4 byte boundary. for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 4) - peStream.Position); i < n; i++) { writer.WriteByte(0); } writer.WriteUshort(0); writer.WriteByte(0xff); writer.WriteByte(0x25); //4 writer.WriteUint((uint)importAddressTableRva + (uint)_properties.BaseAddress); //8 } else { //emit 0's (nops) to pad the entry point code so that the target address is aligned on a 8 byte boundary. for (uint i = 0, n = (uint)(BitArithmeticUtilities.Align((uint)peStream.Position, 8) - peStream.Position); i < n; i++) { writer.WriteByte(0); } writer.WriteUint(0); writer.WriteUshort(0); writer.WriteByte(0xff); writer.WriteByte(0x25); //8 writer.WriteUlong((ulong)importAddressTableRva + _properties.BaseAddress); //16 } writer.WriteTo(peStream); } private void WriteRelocSection(Stream peStream, SectionHeader relocSection, int entryPointAddress) { peStream.Position = relocSection.PointerToRawData; var writer = new BlobWriter(relocSection.SizeOfRawData); writer.WriteUint((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); writer.WriteUint(_properties.Requires64bits && !_properties.RequiresAmdInstructionSet ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = _properties.Requires64bits ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); writer.WriteUshort(s); if (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) { writer.WriteUint(relocType << 12); } writer.WriteUshort(0); // next chunk's RVA writer.Position = relocSection.SizeOfRawData; writer.WriteTo(peStream); } private void WriteResourceSection(Stream peStream, SectionHeader resourceSection) { peStream.Position = resourceSection.PointerToRawData; _win32ResourceWriter.Position = resourceSection.SizeOfRawData; _win32ResourceWriter.WriteTo(peStream); } } }
using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Diagnostics; namespace QuickGraphTest { using QuickGraph.Concepts; using QuickGraph.Concepts.Traversals; using QuickGraph.Algorithms.RandomWalks; using QuickGraph; using QuickGraph.Providers; using QuickGraph.Collections; using QuickGraph.Representations; /// <summary> /// Summary description for MazeGenerator. /// </summary> public class MazeGenerator { private BidirectionalGraph graph = null; private VertexEdgeDictionary successors = null; private NamedVertex[,] latice; private Hashtable vertexIndices = null; private EdgeCollection outPath = null; private float pointWidth = 5; private Color pointColor = Color.Black; private float wallWidth = 1; private Color wallColor = Color.Black; private Color pathColor = Color.Red; public MazeGenerator(int rows, int columns) { this.latice=new NamedVertex[rows,columns]; GenerateGraph(); } public int Rows { get { return this.latice.GetLength(0); } } public int Columns { get { return this.latice.GetLength(1); } } public float PointWidth { get { return this.pointWidth; } set { this.pointWidth = Math.Max(0,value); } } public Color PointColor { get { return this.pointColor; } set { this.pointColor = value; } } public float WallWidth { get { return this.wallWidth; } set { this.wallWidth = Math.Max(0,value); } } public Color PathColor { get { return this.pathColor; } set { this.pathColor = value; } } public Color WallColor { get { return this.wallColor; } set { this.wallColor = value; } } public EdgeCollection OutPath { get { return this.outPath; } } public void GenerateGraph() { this.vertexIndices = new Hashtable(); // create a new adjacency graph this.graph = new BidirectionalGraph( new NamedVertexProvider(), new EdgeProvider(), false); int rows = this.Rows; int columns = this.Columns; // adding vertices for(int i=0;i<rows;++i) { for(int j=0;j<columns;++j) { NamedVertex v =(NamedVertex)this.graph.AddVertex(); v.Name = String.Format("{0},{1}",i.ToString(),j.ToString()); latice[i,j] = v; vertexIndices[v]=new DictionaryEntry(i,j); } } // adding edges for(int i =0;i<rows-1;++i) { for(int j=0;j<columns-1;++j) { this.graph.AddEdge(latice[i,j], latice[i,j+1]); this.graph.AddEdge(latice[i,j+1], latice[i,j]); this.graph.AddEdge(latice[i,j], latice[i+1,j]); this.graph.AddEdge(latice[i+1,j], latice[i,j]); } } for(int j=0;j<columns-1;++j) { this.graph.AddEdge(latice[rows-1,j], latice[rows-1,j+1]); this.graph.AddEdge(latice[rows-1,j+1], latice[rows-1,j]); } for(int i=0;i<rows-1;++i) { this.graph.AddEdge(latice[i,columns-1], latice[i+1,columns-1]); this.graph.AddEdge(latice[i+1,columns-1], latice[i,columns-1]); } } public void GenerateWalls(int outi, int outj, int ini, int inj) { // here we use a uniform probability distribution among the out-edges CyclePoppingRandomTreeAlgorithm pop = new CyclePoppingRandomTreeAlgorithm(this.graph); // we can also weight the out-edges /* EdgeDoubleDictionary weights = new EdgeDoubleDictionary(); foreach(IEdge e in this.graph.Edges) weights[e]=1; pop.EdgeChain = new WeightedMarkovEdgeChain(weights); */ IVertex root = this.latice[outi,outj]; if (root==null) throw new ArgumentException("outi,outj vertex not found"); pop.RandomTreeWithRoot(this.latice[outi,outj]); this.successors = pop.Successors; // build the path to ini, inj IVertex v = this.latice[ini,inj]; if (v==null) throw new ArgumentException("ini,inj vertex not found"); this.outPath = new EdgeCollection(); while (v!=root) { IEdge e = this.successors[v]; if (e==null) throw new Exception(); this.outPath.Add(e); v = e.Target; } } public void Draw(Graphics g, RectangleF rect) { Debug.Assert(this.vertexIndices!=null); float dx = rect.Width/(this.Columns-1); float dy = rect.Width/(this.Rows-1); SolidBrush pointBrush = new SolidBrush(this.pointColor); Pen linePen = new Pen(this.wallColor, this.wallWidth); // linePen.EndCap = LineCap.ArrowAnchor; Pen pathPen = new Pen(this.pathColor, this.wallWidth+2); pathPen.EndCap = LineCap.ArrowAnchor; // draw points float x,y; for(int i=0;i<this.Rows;++i) { for (int j=0;j<this.Columns;++j) { x=rect.X+j*dx-pointWidth/2; y=rect.Y+i*dy-pointWidth/2; // draw vertex g.FillEllipse(pointBrush,x,y,pointWidth,pointWidth); } } // draw edges if (this.successors!=null) { foreach(IEdge e in this.successors.Values) { if (e==null) continue; DictionaryEntry s = (DictionaryEntry)vertexIndices[e.Source]; DictionaryEntry t = (DictionaryEntry)vertexIndices[e.Target]; float sx = rect.X + ((int)s.Value)*dx; float sy = rect.Y + ((int)s.Key)*dy; float tx = rect.X + ((int)t.Value)*dx; float ty = rect.Y + ((int)t.Key)*dy; g.DrawLine(linePen,sx,sy,tx,ty); } } else { foreach(IEdge e in this.graph.Edges) { if (e==null) continue; DictionaryEntry s = (DictionaryEntry)vertexIndices[e.Source]; DictionaryEntry t = (DictionaryEntry)vertexIndices[e.Target]; float sx = rect.X + ((int)s.Value)*dx; float sy = rect.Y + ((int)s.Key)*dy; float tx = rect.X + ((int)t.Value)*dx; float ty = rect.Y + ((int)t.Key)*dy; g.DrawLine(linePen,sx,sy,tx,ty); } } if (this.outPath!=null) { // draw path foreach(IEdge e in this.outPath) { DictionaryEntry s = (DictionaryEntry)vertexIndices[e.Source]; DictionaryEntry t = (DictionaryEntry)vertexIndices[e.Target]; float sx = rect.X + ((int)s.Value)*dx; float sy = rect.Y + ((int)s.Key)*dy; float tx = rect.X + ((int)t.Value)*dx; float ty = rect.Y + ((int)t.Key)*dy; g.DrawLine(pathPen,sx,sy,tx,ty); } } } public void Save( string fileName, ImageFormat format, int width, int height) { Bitmap bmp = new Bitmap(width,height); Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.AntiAlias; g.FillRectangle(Brushes.White,0,0,bmp.Width,bmp.Height); Draw(g,new RectangleF(pointWidth/2,pointWidth/2, bmp.Width-pointWidth, bmp.Height-pointWidth)); bmp.Save(fileName,format); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace System.Numerics.Matrices { /// <summary> /// Represents a matrix of double precision floating-point values defined by its number of columns and rows /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Matrix2x3: IEquatable<Matrix2x3>, IMatrix { public const int ColumnCount = 2; public const int RowCount = 3; static Matrix2x3() { Zero = new Matrix2x3(0); } /// <summary> /// Gets the smallest value used to determine equality /// </summary> public double Epsilon { get { return MatrixHelper.Epsilon; } } /// <summary> /// Constant Matrix2x3 with all values initialized to zero /// </summary> public static readonly Matrix2x3 Zero; /// <summary> /// Initializes a Matrix2x3 with all of it values specifically set /// </summary> /// <param name="m11">The column 1, row 1 value</param> /// <param name="m21">The column 2, row 1 value</param> /// <param name="m12">The column 1, row 2 value</param> /// <param name="m22">The column 2, row 2 value</param> /// <param name="m13">The column 1, row 3 value</param> /// <param name="m23">The column 2, row 3 value</param> public Matrix2x3(double m11, double m21, double m12, double m22, double m13, double m23) { M11 = m11; M21 = m21; M12 = m12; M22 = m22; M13 = m13; M23 = m23; } /// <summary> /// Initialized a Matrix2x3 with all values set to the same value /// </summary> /// <param name="value">The value to set all values to</param> public Matrix2x3(double value) { M11 = M21 = M12 = M22 = M13 = M23 = value; } public double M11; public double M21; public double M12; public double M22; public double M13; public double M23; public unsafe double this[int col, int row] { get { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix2x3* p = &this) { double* d = (double*)p; return d[row * ColumnCount + col]; } } set { if (col < 0 || col >= ColumnCount) throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col)); if (row < 0 || row >= RowCount) throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row)); fixed (Matrix2x3* p = &this) { double* d = (double*)p; d[row * ColumnCount + col] = value; } } } /// <summary> /// Gets the number of columns in the matrix /// </summary> public int Columns { get { return ColumnCount; } } /// <summary> /// Get the number of rows in the matrix /// </summary> public int Rows { get { return RowCount; } } /// <summary> /// Gets a new Matrix1x3 containing the values of column 1 /// </summary> public Matrix1x3 Column1 { get { return new Matrix1x3(M11, M12, M13); } } /// <summary> /// Gets a new Matrix1x3 containing the values of column 2 /// </summary> public Matrix1x3 Column2 { get { return new Matrix1x3(M21, M22, M23); } } /// <summary> /// Gets a new Matrix2x1 containing the values of column 1 /// </summary> public Matrix2x1 Row1 { get { return new Matrix2x1(M11, M21); } } /// <summary> /// Gets a new Matrix2x1 containing the values of column 2 /// </summary> public Matrix2x1 Row2 { get { return new Matrix2x1(M12, M22); } } /// <summary> /// Gets a new Matrix2x1 containing the values of column 3 /// </summary> public Matrix2x1 Row3 { get { return new Matrix2x1(M13, M23); } } public override bool Equals(object obj) { if (obj is Matrix2x3) return this == (Matrix2x3)obj; return false; } public bool Equals(Matrix2x3 other) { return this == other; } public unsafe override int GetHashCode() { fixed (Matrix2x3* p = &this) { int* x = (int*)p; unchecked { return 0xFFE1 + 7 * ((((x[00] ^ x[01]) << 0) + ((x[02] ^ x[03]) << 1)) << 0) + 7 * ((((x[02] ^ x[03]) << 0) + ((x[04] ^ x[05]) << 1)) << 1) + 7 * ((((x[04] ^ x[05]) << 0) + ((x[06] ^ x[07]) << 1)) << 2); } } } public override string ToString() { return "Matrix2x3: " + String.Format("{{|{0:00}|{1:00}|}}", M11, M21) + String.Format("{{|{0:00}|{1:00}|}}", M12, M22) + String.Format("{{|{0:00}|{1:00}|}}", M13, M23); } /// <summary> /// Creates and returns a transposed matrix /// </summary> /// <returns>Matrix with transposed values</returns> public Matrix3x2 Transpose() { return new Matrix3x2(M11, M12, M13, M21, M22, M23); } public static bool operator ==(Matrix2x3 matrix1, Matrix2x3 matrix2) { return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11) && MatrixHelper.AreEqual(matrix1.M21, matrix2.M21) && MatrixHelper.AreEqual(matrix1.M12, matrix2.M12) && MatrixHelper.AreEqual(matrix1.M22, matrix2.M22) && MatrixHelper.AreEqual(matrix1.M13, matrix2.M13) && MatrixHelper.AreEqual(matrix1.M23, matrix2.M23); } public static bool operator !=(Matrix2x3 matrix1, Matrix2x3 matrix2) { return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11) || MatrixHelper.NotEqual(matrix1.M21, matrix2.M21) || MatrixHelper.NotEqual(matrix1.M12, matrix2.M12) || MatrixHelper.NotEqual(matrix1.M22, matrix2.M22) || MatrixHelper.NotEqual(matrix1.M13, matrix2.M13) || MatrixHelper.NotEqual(matrix1.M23, matrix2.M23); } public static Matrix2x3 operator +(Matrix2x3 matrix1, Matrix2x3 matrix2) { double m11 = matrix1.M11 + matrix2.M11; double m21 = matrix1.M21 + matrix2.M21; double m12 = matrix1.M12 + matrix2.M12; double m22 = matrix1.M22 + matrix2.M22; double m13 = matrix1.M13 + matrix2.M13; double m23 = matrix1.M23 + matrix2.M23; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix2x3 operator -(Matrix2x3 matrix1, Matrix2x3 matrix2) { double m11 = matrix1.M11 - matrix2.M11; double m21 = matrix1.M21 - matrix2.M21; double m12 = matrix1.M12 - matrix2.M12; double m22 = matrix1.M22 - matrix2.M22; double m13 = matrix1.M13 - matrix2.M13; double m23 = matrix1.M23 - matrix2.M23; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix2x3 operator *(Matrix2x3 matrix, double scalar) { double m11 = matrix.M11 * scalar; double m21 = matrix.M21 * scalar; double m12 = matrix.M12 * scalar; double m22 = matrix.M22 * scalar; double m13 = matrix.M13 * scalar; double m23 = matrix.M23 * scalar; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix2x3 operator *(double scalar, Matrix2x3 matrix) { double m11 = scalar * matrix.M11; double m21 = scalar * matrix.M21; double m12 = scalar * matrix.M12; double m22 = scalar * matrix.M22; double m13 = scalar * matrix.M13; double m23 = scalar * matrix.M23; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix1x3 operator *(Matrix2x3 matrix1, Matrix1x2 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12; return new Matrix1x3(m11, m12, m13); } public static Matrix2x3 operator *(Matrix2x3 matrix1, Matrix2x2 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22; return new Matrix2x3(m11, m21, m12, m22, m13, m23); } public static Matrix3x3 operator *(Matrix2x3 matrix1, Matrix3x2 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22; double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22; double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22; double m33 = matrix1.M13 * matrix2.M31 + matrix1.M23 * matrix2.M32; return new Matrix3x3(m11, m21, m31, m12, m22, m32, m13, m23, m33); } public static Matrix4x3 operator *(Matrix2x3 matrix1, Matrix4x2 matrix2) { double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12; double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22; double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32; double m41 = matrix1.M11 * matrix2.M41 + matrix1.M21 * matrix2.M42; double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12; double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22; double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32; double m42 = matrix1.M12 * matrix2.M41 + matrix1.M22 * matrix2.M42; double m13 = matrix1.M13 * matrix2.M11 + matrix1.M23 * matrix2.M12; double m23 = matrix1.M13 * matrix2.M21 + matrix1.M23 * matrix2.M22; double m33 = matrix1.M13 * matrix2.M31 + matrix1.M23 * matrix2.M32; double m43 = matrix1.M13 * matrix2.M41 + matrix1.M23 * matrix2.M42; return new Matrix4x3(m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43); } } }
using Decal.Adapter; using Decal.Adapter.Wrappers; using Decal.Interop.Inject; using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Runtime.InteropServices; using Zegeger.Decal.Plugins.ZChatSystem.Diagnostics; namespace Zegeger.Decal.Plugins.ZChatSystem { internal partial class PluginCore : PluginBase { internal static PluginHost MyHost; internal static CoreManager MyCore; internal static bool initComplete; protected override void Startup() { string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Zegeger\ZChatSystem\"; TraceLogger.StartUp(appDataPath + @"Logs"); try { TraceLogger.Write("Enter"); initComplete = false; MyHost = Host; MyCore = Core; MainView.ViewInit(); ZChatSystem.initPerf(); initEchoFilter(); initCharStats(); initChatEvents(); ZChatSystem.initService(); ReadSettings(); Core.PluginInitComplete += new EventHandler<EventArgs>(MyCore_PluginInitComplete); ZChatSystem.Running = true; TraceLogger.Write( "Exit"); } catch (Exception ex) { TraceLogger.Write(ex); } } void MyCore_PluginInitComplete(object sender, EventArgs e) { TraceLogger.Write("Enter"); initComplete = true; TraceLogger.Write("Exit"); } protected override void Shutdown() { try { TraceLogger.Write( "Enter"); WriteSettings(); Core.PluginInitComplete -= new EventHandler<EventArgs>(MyCore_PluginInitComplete); ZChatSystem.destroyPerf(); ZChatSystem.destroyService(); destroyChatEvents(); destroyCharStats(); destroyEchoFilter(); MainView.ViewDestroy(); MyHost = null; MyCore = null; TraceLogger.Write( "Exit"); //TODO: Code for shutdown events } catch (Exception ex) { TraceLogger.Write(ex); } TraceLogger.ShutDown(); } internal static void WriteSettings() { try { TraceLogger.Write("Enter"); string filename = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Decal Plugins\\Zegeger\\ZChatSystem\\settings.xml"; TraceLogger.Write("Filename: " + filename); TraceLogger.Write("Start writing to temp: " + filename + ".tmp"); XmlDocument xmlWriter = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlWriter.CreateXmlDeclaration("1.0", "utf-8", null); xmlWriter.AppendChild(xmlWriter.CreateElement("ZChatSystem")); xmlWriter.InsertBefore(xmlDeclaration, xmlWriter.DocumentElement); XmlElement oPlugin; XmlElement zo = xmlWriter.CreateElement("Settings"); xmlWriter.DocumentElement.AppendChild(zo); TraceLogger.Write("Writing Settings Logging"); oPlugin = xmlWriter.CreateElement("Logging"); oPlugin.SetAttribute("tracingLevel", TraceLogger.LoggingLevel.ToString()); zo.AppendChild(oPlugin); XmlElement oi = xmlWriter.CreateElement("OrderInfo"); xmlWriter.DocumentElement.AppendChild(oi); XmlElement mo = xmlWriter.CreateElement("MessageOrder"); oi.AppendChild(mo); foreach (OrderData messagedata in ZChatSystem.MessageOrder) { TraceLogger.Write("Writing Message" + messagedata.plugin); oPlugin = xmlWriter.CreateElement("Plugin"); oPlugin.SetAttribute("enabled", messagedata.enabled.ToString()); oPlugin.SetAttribute("name", messagedata.plugin); mo.AppendChild(oPlugin); } XmlElement co = xmlWriter.CreateElement("ColorOrder"); oi.AppendChild(co); foreach (OrderData colordata in ZChatSystem.ColorOrder) { TraceLogger.Write("Writing Color" + colordata.plugin); oPlugin = xmlWriter.CreateElement("Plugin"); oPlugin.SetAttribute("enabled", colordata.enabled.ToString()); oPlugin.SetAttribute("name", colordata.plugin); co.AppendChild(oPlugin); } XmlElement wo = xmlWriter.CreateElement("WindowOrder"); oi.AppendChild(wo); foreach (OrderData windowdata in ZChatSystem.WindowOrder) { TraceLogger.Write("Writing Window" + windowdata.plugin); oPlugin = xmlWriter.CreateElement("Plugin"); oPlugin.SetAttribute("enabled", windowdata.enabled.ToString()); oPlugin.SetAttribute("name", windowdata.plugin); wo.AppendChild(oPlugin); } xmlWriter.Save(filename + ".tmp"); TraceLogger.Write("Finish writing to temp: " + filename + ".tmp"); TraceLogger.Write("Deleting old file: " + filename); System.IO.File.Delete(filename); TraceLogger.Write("Renaming \"" + filename + ".tmp" + "\" to \"" + filename + "\""); System.IO.File.Move(filename + ".tmp", filename); /*XmlTextWriter textWriter = new XmlTextWriter(filename + ".tmp", null); textWriter.WriteStartDocument(); textWriter.WriteStartElement("ZChatSystem"); textWriter.WriteStartElement("PluginOrder"); foreach (KeyValuePair<System.Guid, string> plugin in Plugins) { TraceLogger.Write("Writing " + plugin.Value); textWriter.WriteStartElement("Plugin"); textWriter.WriteValue(plugin.Value); textWriter.WriteEndElement(); } textWriter.WriteEndElement(); textWriter.WriteEndElement(); textWriter.WriteEndDocument(); textWriter.Close(); TraceLogger.Write("Finish writing to temp: " + filename + ".tmp"); TraceLogger.Write("Deleting old file: " + filename); System.IO.File.Delete(filename); TraceLogger.Write("Renaming \"" + filename + ".tmp" + "\" to \"" + filename + "\""); System.IO.File.Move(filename + ".tmp", filename); textWriter = null;*/ TraceLogger.Write("Exit"); } catch (Exception ex) { TraceLogger.Write(ex); } } internal void ReadSettings() { try { TraceLogger.Write("Enter"); string filename = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Decal Plugins\\Zegeger\\ZChatSystem\\settings.xml"; TraceLogger.Write("Filename: " + filename); XmlDocument doc = new XmlDocument(); TraceLogger.Write("Loading: " + filename); doc.Load(filename); XmlNode DocNode = doc.DocumentElement; XmlNodeList Settings = DocNode.ChildNodes; for (int w = 0; w < Settings.Count; w++) { if (Settings[w].Name.Equals("Settings")) { TraceLogger.Write("Handling Settings"); XmlNodeList SettingsList = Settings[w].ChildNodes; for (int v = 0; v < SettingsList.Count; v++) { TraceLogger.Write("Handling: " + SettingsList[v].Name); switch (SettingsList[v].Name) { case "Logging": string level = SettingsList[v].Attributes["tracingLevel"].Value; switch(level) { case "Off": TraceLogger.LoggingLevel = TraceLevel.Off; break; case "Noise": TraceLogger.LoggingLevel = TraceLevel.Noise; break; case "Verbose": TraceLogger.LoggingLevel = TraceLevel.Verbose; break; case "Info": TraceLogger.LoggingLevel = TraceLevel.Info; break; case "Warning": TraceLogger.LoggingLevel = TraceLevel.Warning; break; case "Error": TraceLogger.LoggingLevel = TraceLevel.Error; break; } break; } } } if (Settings[w].Name.Equals("OrderInfo")) { TraceLogger.Write("Handling OrderInfo"); XmlNodeList OrderInfo = Settings[w].ChildNodes; for (int x = 0; x < OrderInfo.Count; x++) { TraceLogger.Write("Handling: " + OrderInfo.Item(x).Name); XmlNodeList XmlPlugins = OrderInfo[x].ChildNodes; for (int y = 0; y < XmlPlugins.Count; y++) { TraceLogger.Write("Adding: " + XmlPlugins.Item(y).Attributes["name"].Value); if (!ZChatSystem.PluginsName.ContainsKey(XmlPlugins.Item(y).Attributes["name"].Value)) ZChatSystem.PluginsName.Add(XmlPlugins.Item(y).Attributes["name"].Value, Guid.Empty); OrderData neworder = new OrderData(); neworder.id = Guid.Empty; neworder.plugin = XmlPlugins.Item(y).Attributes["name"].Value; neworder.enabled = (XmlPlugins.Item(y).Attributes["enabled"].Value == "True"); switch (OrderInfo.Item(x).Name) { case "MessageOrder": ZChatSystem.MessageOrder.Add(neworder); break; case "ColorOrder": ZChatSystem.ColorOrder.Add(neworder); break; case "WindowOrder": ZChatSystem.WindowOrder.Add(neworder); break; } } } } } doc = null; ZChatSystem.updateMessageView(); ZChatSystem.updateWindowView(); ZChatSystem.updateColorView(); TraceLogger.Write("Exit"); } catch (Exception ex) { TraceLogger.Write(ex); } } } }
// dnlib: See LICENSE.txt for more info using System; using System.Threading; using dnlib.DotNet.MD; using dnlib.PE; using dnlib.Threading; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the Field table /// </summary> public abstract class FieldDef : IHasConstant, IHasCustomAttribute, IHasFieldMarshal, IMemberForwarded, IField, ITokenOperand, IMemberDef { /// <summary> /// The row id in its table /// </summary> protected uint rid; #if THREAD_SAFE readonly Lock theLock = Lock.Create(); #endif /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.Field, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <inheritdoc/> public int HasConstantTag { get { return 0; } } /// <inheritdoc/> public int HasCustomAttributeTag { get { return 1; } } /// <inheritdoc/> public int HasFieldMarshalTag { get { return 0; } } /// <inheritdoc/> public int MemberForwardedTag { get { return 0; } } /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes == null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() { Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); } /// <summary> /// From column Field.Flags /// </summary> public FieldAttributes Attributes { get { return (FieldAttributes)attributes; } set { attributes = (int)value; } } /// <summary>Attributes</summary> protected int attributes; /// <summary> /// From column Field.Name /// </summary> public UTF8String Name { get { return name; } set { name = value; } } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column Field.Signature /// </summary> public CallingConventionSig Signature { get { return signature; } set { signature = value; } } /// <summary/> protected CallingConventionSig signature; /// <summary> /// Gets/sets the field layout offset /// </summary> public uint? FieldOffset { get { if (!fieldOffset_isInitialized) InitializeFieldOffset(); return fieldOffset; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif fieldOffset = value; fieldOffset_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected uint? fieldOffset; /// <summary/> protected bool fieldOffset_isInitialized; void InitializeFieldOffset() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (fieldOffset_isInitialized) return; fieldOffset = GetFieldOffset_NoLock(); fieldOffset_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="fieldOffset"/></summary> protected virtual uint? GetFieldOffset_NoLock() { return null; } /// <inheritdoc/> public MarshalType MarshalType { get { if (!marshalType_isInitialized) InitializeMarshalType(); return marshalType; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif marshalType = value; marshalType_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected MarshalType marshalType; /// <summary/> protected bool marshalType_isInitialized; void InitializeMarshalType() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (marshalType_isInitialized) return; marshalType = GetMarshalType_NoLock(); marshalType_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="marshalType"/></summary> protected virtual MarshalType GetMarshalType_NoLock() { return null; } /// <summary> /// Gets/sets the field RVA /// </summary> public RVA RVA { get { if (!rva_isInitialized) InitializeRVA(); return rva; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif rva = value; rva_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected RVA rva; /// <summary/> protected bool rva_isInitialized; void InitializeRVA() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (rva_isInitialized) return; rva = GetRVA_NoLock(); rva_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="rva"/></summary> protected virtual RVA GetRVA_NoLock() { return 0; } /// <summary> /// Gets/sets the initial value. Be sure to set <see cref="HasFieldRVA"/> to <c>true</c> if /// you write to this field. /// </summary> public byte[] InitialValue { get { if (!initialValue_isInitialized) InitializeInitialValue(); return initialValue; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif initialValue = value; initialValue_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected byte[] initialValue; /// <summary/> protected bool initialValue_isInitialized; void InitializeInitialValue() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (initialValue_isInitialized) return; initialValue = GetInitialValue_NoLock(); initialValue_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="initialValue"/></summary> protected virtual byte[] GetInitialValue_NoLock() { return null; } /// <inheritdoc/> public ImplMap ImplMap { get { if (!implMap_isInitialized) InitializeImplMap(); return implMap; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif implMap = value; implMap_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected ImplMap implMap; /// <summary/> protected bool implMap_isInitialized; void InitializeImplMap() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (implMap_isInitialized) return; implMap = GetImplMap_NoLock(); implMap_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="implMap"/></summary> protected virtual ImplMap GetImplMap_NoLock() { return null; } /// <inheritdoc/> public Constant Constant { get { if (!constant_isInitialized) InitializeConstant(); return constant; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif constant = value; constant_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected Constant constant; /// <summary/> protected bool constant_isInitialized; void InitializeConstant() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (constant_isInitialized) return; constant = GetConstant_NoLock(); constant_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="constant"/></summary> protected virtual Constant GetConstant_NoLock() { return null; } /// <inheritdoc/> public bool HasCustomAttributes { get { return CustomAttributes.Count > 0; } } /// <inheritdoc/> public bool HasImplMap { get { return ImplMap != null; } } /// <summary> /// Gets/sets the declaring type (owner type) /// </summary> public TypeDef DeclaringType { get { return declaringType2; } set { var currentDeclaringType = DeclaringType2; if (currentDeclaringType == value) return; if (currentDeclaringType != null) currentDeclaringType.Fields.Remove(this); // Will set DeclaringType2 = null if (value != null) value.Fields.Add(this); // Will set DeclaringType2 = value } } /// <inheritdoc/> ITypeDefOrRef IMemberRef.DeclaringType { get { return declaringType2; } } /// <summary> /// Called by <see cref="DeclaringType"/> and should normally not be called by any user /// code. Use <see cref="DeclaringType"/> instead. Only call this if you must set the /// declaring type without inserting it in the declaring type's method list. /// </summary> public TypeDef DeclaringType2 { get { return declaringType2; } set { declaringType2 = value; } } /// <summary/> protected TypeDef declaringType2; /// <summary> /// Gets/sets the <see cref="FieldSig"/> /// </summary> public FieldSig FieldSig { get { return signature as FieldSig; } set { signature = value; } } /// <inheritdoc/> public ModuleDef Module { get { var dt = declaringType2; return dt == null ? null : dt.Module; } } bool IIsTypeOrMethod.IsType { get { return false; } } bool IIsTypeOrMethod.IsMethod { get { return false; } } bool IMemberRef.IsField { get { return true; } } bool IMemberRef.IsTypeSpec { get { return false; } } bool IMemberRef.IsTypeRef { get { return false; } } bool IMemberRef.IsTypeDef { get { return false; } } bool IMemberRef.IsMethodSpec { get { return false; } } bool IMemberRef.IsMethodDef { get { return false; } } bool IMemberRef.IsMemberRef { get { return false; } } bool IMemberRef.IsFieldDef { get { return true; } } bool IMemberRef.IsPropertyDef { get { return false; } } bool IMemberRef.IsEventDef { get { return false; } } bool IMemberRef.IsGenericParam { get { return false; } } /// <summary> /// <c>true</c> if <see cref="FieldOffset"/> is not <c>null</c> /// </summary> public bool HasLayoutInfo { get { return FieldOffset != null; } } /// <summary> /// <c>true</c> if <see cref="Constant"/> is not <c>null</c> /// </summary> public bool HasConstant { get { return Constant != null; } } /// <summary> /// Gets the constant element type or <see cref="dnlib.DotNet.ElementType.End"/> if there's no constant /// </summary> public ElementType ElementType { get { var c = Constant; return c == null ? ElementType.End : c.Type; } } /// <summary> /// <c>true</c> if <see cref="MarshalType"/> is not <c>null</c> /// </summary> public bool HasMarshalType { get { return MarshalType != null; } } /// <summary> /// Gets/sets the field type /// </summary> public TypeSig FieldType { get { return FieldSig.GetFieldType(); } set { var sig = FieldSig; if (sig != null) sig.Type = value; } } /// <summary> /// Modify <see cref="attributes"/> field: <see cref="attributes"/> = /// (<see cref="attributes"/> &amp; <paramref name="andMask"/>) | <paramref name="orMask"/>. /// </summary> /// <param name="andMask">Value to <c>AND</c></param> /// <param name="orMask">Value to OR</param> void ModifyAttributes(FieldAttributes andMask, FieldAttributes orMask) { #if THREAD_SAFE int origVal, newVal; do { origVal = attributes; newVal = (origVal & (int)andMask) | (int)orMask; } while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal); #else attributes = (attributes & (int)andMask) | (int)orMask; #endif } /// <summary> /// Set or clear flags in <see cref="attributes"/> /// </summary> /// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should /// be cleared</param> /// <param name="flags">Flags to set or clear</param> void ModifyAttributes(bool set, FieldAttributes flags) { #if THREAD_SAFE int origVal, newVal; do { origVal = attributes; if (set) newVal = origVal | (int)flags; else newVal = origVal & ~(int)flags; } while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal); #else if (set) attributes |= (int)flags; else attributes &= ~(int)flags; #endif } /// <summary> /// Gets/sets the field access /// </summary> public FieldAttributes Access { get { return (FieldAttributes)attributes & FieldAttributes.FieldAccessMask; } set { ModifyAttributes(~FieldAttributes.FieldAccessMask, value & FieldAttributes.FieldAccessMask); } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set /// </summary> public bool IsCompilerControlled { get { return IsPrivateScope; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set /// </summary> public bool IsPrivateScope { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.PrivateScope; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.Private"/> is set /// </summary> public bool IsPrivate { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.FamANDAssem"/> is set /// </summary> public bool IsFamilyAndAssembly { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.Assembly"/> is set /// </summary> public bool IsAssembly { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.Family"/> is set /// </summary> public bool IsFamily { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.FamORAssem"/> is set /// </summary> public bool IsFamilyOrAssembly { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } } /// <summary> /// <c>true</c> if <see cref="FieldAttributes.Public"/> is set /// </summary> public bool IsPublic { get { return ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.Static"/> bit /// </summary> public bool IsStatic { get { return ((FieldAttributes)attributes & FieldAttributes.Static) != 0; } set { ModifyAttributes(value, FieldAttributes.Static); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.InitOnly"/> bit /// </summary> public bool IsInitOnly { get { return ((FieldAttributes)attributes & FieldAttributes.InitOnly) != 0; } set { ModifyAttributes(value, FieldAttributes.InitOnly); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.Literal"/> bit /// </summary> public bool IsLiteral { get { return ((FieldAttributes)attributes & FieldAttributes.Literal) != 0; } set { ModifyAttributes(value, FieldAttributes.Literal); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.NotSerialized"/> bit /// </summary> public bool IsNotSerialized { get { return ((FieldAttributes)attributes & FieldAttributes.NotSerialized) != 0; } set { ModifyAttributes(value, FieldAttributes.NotSerialized); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.SpecialName"/> bit /// </summary> public bool IsSpecialName { get { return ((FieldAttributes)attributes & FieldAttributes.SpecialName) != 0; } set { ModifyAttributes(value, FieldAttributes.SpecialName); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.PinvokeImpl"/> bit /// </summary> public bool IsPinvokeImpl { get { return ((FieldAttributes)attributes & FieldAttributes.PinvokeImpl) != 0; } set { ModifyAttributes(value, FieldAttributes.PinvokeImpl); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.RTSpecialName"/> bit /// </summary> public bool IsRuntimeSpecialName { get { return ((FieldAttributes)attributes & FieldAttributes.RTSpecialName) != 0; } set { ModifyAttributes(value, FieldAttributes.RTSpecialName); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.HasFieldMarshal"/> bit /// </summary> public bool HasFieldMarshal { get { return ((FieldAttributes)attributes & FieldAttributes.HasFieldMarshal) != 0; } set { ModifyAttributes(value, FieldAttributes.HasFieldMarshal); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.HasDefault"/> bit /// </summary> public bool HasDefault { get { return ((FieldAttributes)attributes & FieldAttributes.HasDefault) != 0; } set { ModifyAttributes(value, FieldAttributes.HasDefault); } } /// <summary> /// Gets/sets the <see cref="FieldAttributes.HasFieldRVA"/> bit /// </summary> public bool HasFieldRVA { get { return ((FieldAttributes)attributes & FieldAttributes.HasFieldRVA) != 0; } set { ModifyAttributes(value, FieldAttributes.HasFieldRVA); } } /// <summary> /// Returns the full name of this field /// </summary> public string FullName { get { var dt = declaringType2; return FullNameCreator.FieldFullName(dt == null ? null : dt.FullName, name, FieldSig); } } /// <summary> /// Gets the size of this field in bytes or <c>0</c> if unknown. /// </summary> public uint GetFieldSize() { uint size; if (!GetFieldSize(out size)) return 0; return size; } /// <summary> /// Gets the size of this field in bytes or <c>0</c> if unknown. /// </summary> /// <param name="size">Updated with size</param> /// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns> public bool GetFieldSize(out uint size) { return GetFieldSize(declaringType2, FieldSig, out size); } /// <summary> /// Gets the size of this field in bytes or <c>0</c> if unknown. /// </summary> /// <param name="declaringType">The declaring type of <c>this</c></param> /// <param name="fieldSig">The field signature of <c>this</c></param> /// <param name="size">Updated with size</param> /// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns> protected bool GetFieldSize(TypeDef declaringType, FieldSig fieldSig, out uint size) { size = 0; if (fieldSig == null) return false; return GetClassSize(declaringType, fieldSig.Type, out size); } bool GetClassSize(TypeDef declaringType, TypeSig ts, out uint size) { size = 0; ts = ts.RemovePinnedAndModifiers(); if (ts == null) return false; int size2 = ts.ElementType.GetPrimitiveSize(GetPointerSize(declaringType)); if (size2 >= 0) { size = (uint)size2; return true; } var tdrs = ts as TypeDefOrRefSig; if (tdrs == null) return false; var td = tdrs.TypeDef; if (td != null) return TypeDef.GetClassSize(td, out size); var tr = tdrs.TypeRef; if (tr != null) return TypeDef.GetClassSize(tr.Resolve(), out size); return false; } int GetPointerSize(TypeDef declaringType) { if (declaringType == null) return 4; var module = declaringType.Module; if (module == null) return 4; return module.GetPointerSize(); } /// <inheritdoc/> public override string ToString() { return FullName; } } /// <summary> /// A Field row created by the user and not present in the original .NET file /// </summary> public class FieldDefUser : FieldDef { /// <summary> /// Default constructor /// </summary> public FieldDefUser() { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> public FieldDefUser(UTF8String name) : this(name, null) { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> /// <param name="signature">Signature</param> public FieldDefUser(UTF8String name, FieldSig signature) : this(name, signature, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> /// <param name="signature">Signature</param> /// <param name="attributes">Flags</param> public FieldDefUser(UTF8String name, FieldSig signature, FieldAttributes attributes) { this.name = name; this.signature = signature; this.attributes = (int)attributes; } } /// <summary> /// Created from a row in the Field table /// </summary> sealed class FieldDefMD : FieldDef, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; readonly FieldAttributes origAttributes; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.MetaData.GetCustomAttributeRidList(Table.Field, origRid); var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override uint? GetFieldOffset_NoLock() { return readerModule.TablesStream.ReadFieldLayoutRow2(readerModule.MetaData.GetFieldLayoutRid(origRid)); } /// <inheritdoc/> protected override MarshalType GetMarshalType_NoLock() { return readerModule.ReadMarshalType(Table.Field, origRid, new GenericParamContext(declaringType2)); } /// <inheritdoc/> protected override RVA GetRVA_NoLock() { RVA rva2; GetFieldRVA_NoLock(out rva2); return rva2; } /// <inheritdoc/> protected override byte[] GetInitialValue_NoLock() { RVA rva2; if (!GetFieldRVA_NoLock(out rva2)) return null; return ReadInitialValue_NoLock(rva2); } /// <inheritdoc/> protected override ImplMap GetImplMap_NoLock() { return readerModule.ResolveImplMap(readerModule.MetaData.GetImplMapRid(Table.Field, origRid)); } /// <inheritdoc/> protected override Constant GetConstant_NoLock() { return readerModule.ResolveConstant(readerModule.MetaData.GetConstantRid(Table.Field, origRid)); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>Field</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public FieldDefMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.FieldTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("Field rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; uint name; uint signature = readerModule.TablesStream.ReadFieldRow(origRid, out this.attributes, out name); this.name = readerModule.StringsStream.ReadNoNull(name); this.origAttributes = (FieldAttributes)attributes; this.declaringType2 = readerModule.GetOwnerType(this); this.signature = readerModule.ReadSignature(signature, new GenericParamContext(declaringType2)); } internal FieldDefMD InitializeAll() { MemberMDInitializer.Initialize(CustomAttributes); MemberMDInitializer.Initialize(Attributes); MemberMDInitializer.Initialize(Name); MemberMDInitializer.Initialize(Signature); MemberMDInitializer.Initialize(FieldOffset); MemberMDInitializer.Initialize(MarshalType); MemberMDInitializer.Initialize(RVA); MemberMDInitializer.Initialize(InitialValue); MemberMDInitializer.Initialize(ImplMap); MemberMDInitializer.Initialize(Constant); MemberMDInitializer.Initialize(DeclaringType); return this; } bool GetFieldRVA_NoLock(out RVA rva) { if ((origAttributes & FieldAttributes.HasFieldRVA) == 0) { rva = 0; return false; } return readerModule.TablesStream.ReadFieldRVARow(readerModule.MetaData.GetFieldRVARid(origRid), out rva); } byte[] ReadInitialValue_NoLock(RVA rva) { uint size; if (!GetFieldSize(declaringType2, signature as FieldSig, out size)) return null; if (size >= int.MaxValue) return null; return readerModule.ReadDataAt(rva, (int)size); } } }
using System; using System.Collections.Generic; namespace SilentOrbit.ProtocolBuffers { /// <summary> /// A protobuf message or enum /// </summary> abstract class ProtoType { public ProtoMessage Parent { get; set; } /// <summary> /// Name used in the .proto file, /// </summary> public string ProtoName { get; set; } /// <summary> /// Based on ProtoType and Rule according to the protocol buffers specification /// </summary> public abstract Wire WireType { get; } /// <summary> /// The c# type name /// </summary> public virtual string CsType { get; set; } /// <summary> /// The C# namespace for this item /// </summary> public virtual string CsNamespace { get { if (OptionNamespace == null) { if (Parent is ProtoCollection) return Parent.CsNamespace; else return Parent.CsNamespace + "." + Parent.CsType; } else return OptionNamespace; } } public virtual string FullCsType { get { if ( CsNamespace == "global" ) return CsNamespace + "::" + CsType; return CsNamespace + "." + CsType; } } /// <summary> /// The C# namespace for this item /// </summary> public virtual string FullProtoName { get { if (Parent is ProtoCollection) return Package + "." + ProtoName; return Parent.FullProtoName + "." + ProtoName; } } /// <summary> /// .proto package option /// </summary> public string Package { get; set; } #region Local options public string OptionNamespace { get; set; } /// <summary> /// (C#) access modifier: public(default)/protected/private /// </summary> public string OptionAccess { get; set; } /// <summary> /// Call triggers before/after serialization. /// </summary> public bool OptionTriggers { get; set; } /// <summary> /// Keep unknown fields when deserializing and send them back when serializing. /// This will generate field to store any unknown keys and their value. /// </summary> public bool OptionPreserveUnknown { get; set; } /// <summary> /// Don't create class/struct, only serializing code, useful when serializing types in external DLL /// </summary> public bool OptionExternal { get; set; } /// <summary> /// Don't create partial classes.. because this class/struct/whatever is external /// </summary> public bool OptionNoPartials { get; set; } /// <summary> /// Don't create new instances of this class /// </summary> public bool OptionNoInstancing { get; set; } /// <summary> /// Use a message table to serialize / deserialize this interface. /// </summary> public bool OptionMessageTableInterface { get; set; } /// <summary> /// Can be "class", "struct" or "interface" /// </summary> public string OptionType { get; set; } /// <summary> /// This classes base class /// </summary> public string OptionBase { get; set; } /// <summary> /// [MessageIdent] attribute value, or zero to omit /// </summary> public uint OptionIdentifier { get; set; } /// <summary> /// Initial capacity of allocated MemoryStream when Serializing this object. /// Size in bytes. /// </summary> public int BufferSize { get; set; } #endregion /// <summary> /// Used by types within a namespace /// </summary> public ProtoType(ProtoMessage parent, string package) : this() { if (this is ProtoCollection == false) { if (parent == null) throw new ArgumentNullException("parent"); if (package == null) throw new ArgumentNullException("package"); } this.Parent = parent; this.Package = package; } public ProtoType() { this.OptionNamespace = null; this.OptionAccess = "public"; this.OptionTriggers = false; this.OptionPreserveUnknown = false; this.OptionExternal = false; this.OptionNoPartials = false; this.OptionNoInstancing = false; this.OptionIdentifier = 0; this.OptionType = null; } public bool Nullable { get { if (ProtoName == ProtoBuiltin.String) return true; if (ProtoName == ProtoBuiltin.Bytes) return true; if (this is ProtoMessage) { if (OptionType == "class") return true; if (OptionType == "interface") return true; } return false; } } /// <summary> /// If constant size, return the size, if not return -1. /// </summary> public virtual int WireSize { get { if (WireType == Wire.Fixed32) return 4; if (WireType == Wire.Fixed64) return 8; if (WireType == Wire.Varint) return -1; if (WireType == Wire.LengthDelimited) return -1; return -1; } } } }
//----------------------------------------------------------------------- // <copyright file="BuildingManager.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Singleton building manager. /// </summary> public class BuildingManager : MonoBehaviour { public GameObject[] buildingPrototypes; public List<Building> buildingList = new List<Building>(); public GameObject goundObject; public Camera mainCamera; public Camera uiCamera; public Building curBuldingObject; public Color buildingErrorColor; public Color buildingCorrectColor; public GameObject placeBuildingButton; public GameObject cancelBuildingButton; private static BuildingManager m_instance; private bool[] occupancyIndex = new bool[400 * 400]; /// <summary> /// Gets the singleton instance. /// </summary> /// <value>The instance.</value> public static BuildingManager Instance { get { if (m_instance == null) { m_instance = GameObject.FindObjectOfType<BuildingManager>(); DontDestroyOnLoad(m_instance.gameObject); } return m_instance; } } /// <summary> /// Called before Start(). /// </summary> public void Awake() { if (m_instance == null) { m_instance = this; DontDestroyOnLoad(this); } else { if (this != m_instance) { Destroy(this.gameObject); } } } /// <summary> /// Use this for initialization. /// </summary> public void Start() { EventManager.TangoPoseStateChanged += TangoStateChanged; // Null terminator cause problem in the file system. Statics.curADFId = Statics.curADFId.Replace("\0", string.Empty); string path = Application.persistentDataPath + "/" + Statics.curADFId; FileParser.GetVectorListFromPath(out buildingList, path); SetAllBuildingActive(false); } private Vector2 hitPoint = new Vector2(); private int index = 0; /// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (Statics.isPlacingObject) { if (Input.GetKey(KeyCode.Mouse0)) { if (RayCastGroud(out hitPoint)) { hitPoint = FindContainningGrid(out index, hitPoint.x, hitPoint.y); curBuldingObject.buildingObject.transform.position = new Vector3(hitPoint.x, 0.0f, hitPoint.y); } } if (!occupancyIndex[index]) { // make the building red. curBuldingObject.buildingObject.GetComponent<BuildingController>().SetBuildingOutfitColor(buildingCorrectColor); } else { // make building green. curBuldingObject.buildingObject.GetComponent<BuildingController>().SetBuildingOutfitColor(buildingErrorColor); } } } /// <summary> /// Sets all buildings' active state. /// </summary> /// <param name="isActive">If set to <c>true</c> is active.</param> public void SetAllBuildingActive(bool isActive) { foreach (Building building in buildingList) { building.SetBuildingActive(isActive); } } /// <summary> /// Place a new building. /// </summary> public void PlaceBuilding() { if (occupancyIndex[index]) { // not placeable. return; } occupancyIndex[index] = true; curBuldingObject.buildingObject.GetComponent<BuildingController>().buildingOutfit.SetActive(false); Statics.isPlacingObject = false; placeBuildingButton.SetActive(false); cancelBuildingButton.SetActive(false); buildingList.Add(curBuldingObject); } /// <summary> /// Cancel the placement of a building. /// </summary> public void CancelBuildingPlacement() { Statics.isPlacingObject = false; placeBuildingButton.SetActive(false); cancelBuildingButton.SetActive(false); DestroyImmediate(curBuldingObject.buildingObject); } /// <summary> /// Create a building in one place. /// </summary> /// <param name="index">Index.</param> public void CreateBulding(int index) { if (Statics.isPlacingObject) { // place on bulding at a time. return; } curBuldingObject = InstantiateBuilding(index, 0.0f, 0.0f); Statics.isPlacingObject = true; placeBuildingButton.SetActive(true); cancelBuildingButton.SetActive(true); } /// <summary> /// Get a new building object at a specific index / coordinate. /// </summary> /// <returns>The building.</returns> /// <param name="index">Index.</param> /// <param name="x">The x coordinate.</param> /// <param name="z">The z coordinate.</param> public Building InstantiateBuilding(int index, float x, float z) { GameObject buildingObj = (GameObject)Instantiate(buildingPrototypes[index]); Building building = new Building(); building.buildingObject = buildingObj; building.buildingObject.transform.position = new Vector3(x, 0.0f, z); building.buildingId = index; return building; } /// <summary> /// Clear all buildings. /// </summary> public void ResetBuildingManager() { buildingList = new List<Building>(); } /// <summary> /// Finds the correct grid cell for this position. /// </summary> /// <returns>The containning grid cell.</returns> /// <param name="index">Index of the grid cell.</param> /// <param name="x">The x coordinate.</param> /// <param name="z">The z coordinate.</param> private Vector2 FindContainningGrid(out int index, float x, float z) { float iterX = -50.0f; float iterY = -50.0f; int indexX = 0; int indexY = 0; while (iterX < x) { iterX += 0.25f; indexX++; } iterX = iterX - 0.125f; while (iterY < z) { iterY += 0.25f; indexY++; } iterY = iterY - 0.125f; index = (indexY * 400) + indexX; return new Vector2(iterX, iterY); } /// <summary> /// Called up update the Tango state. /// </summary> /// <param name="curState">Current state.</param> private void TangoStateChanged(TangoPoseStates curState) { if (curState == TangoPoseStates.Running) { SetAllBuildingActive(true); } else { SetAllBuildingActive(false); } } /// <summary> /// Raycast from the "mouse" to the ground. /// </summary> /// <returns><c>true</c>, if cast groud was rayed, <c>false</c> otherwise.</returns> /// <param name="outHitPoint">Out hit point.</param> private bool RayCastGroud(out Vector2 outHitPoint) { RaycastHit hit = new RaycastHit(); Vector3 screenPosition = Input.mousePosition; if (Physics.Raycast(uiCamera.ScreenPointToRay(screenPosition), out hit, Mathf.Infinity)) { outHitPoint = new Vector2(); return false; } if (Physics.Raycast(mainCamera.ScreenPointToRay(screenPosition), out hit, Mathf.Infinity)) { Debug.DrawRay(mainCamera.transform.position, hit.point - mainCamera.transform.position, Color.red); if (hit.transform.gameObject == goundObject) { outHitPoint = new Vector2(hit.point.x, hit.point.z); return true; } } outHitPoint = new Vector2(); return false; } } /// <summary> /// A single building. /// </summary> public class Building : MonoBehaviour { public GameObject buildingObject; public int buildingId; /// <summary> /// Initializes a new instance of the <see cref="Building"/> class. /// </summary> public Building() { } /// <summary> /// Sets the building active. /// </summary> /// <param name="isActive">If set to <c>true</c> is active.</param> public void SetBuildingActive(bool isActive) { buildingObject.SetActive(isActive); } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the <see cref="Building"/> is /// reclaimed by garbage collection. /// </summary> ~Building() { DestroyObject(buildingObject); } }
// // AGraphElement.cs // // Author: // Henning Rauch <Henning@RauchEntwicklung.biz> // // Copyright (c) 2012 Henning Rauch // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #region Usings using System; using System.Collections.ObjectModel; using NoSQL.GraphDB.Error; using NoSQL.GraphDB.Helper; #endregion namespace NoSQL.GraphDB.Model { /// <summary> /// A graph element. /// </summary> public abstract class AGraphElement : AThreadSafeElement { #region Data /// <summary> /// The identifier of this graph element. /// </summary> public Int32 Id; /// <summary> /// The creation date. /// </summary> public readonly UInt32 CreationDate; /// <summary> /// The modification date. /// </summary> public UInt32 ModificationDate; /// <summary> /// The properties. /// </summary> private PropertyContainer[] _properties; #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="AGraphElement" /> class. /// </summary> /// <param name='id'> Identifier. </param> /// <param name='creationDate'> Creation date. </param> /// <param name='properties'> Properties. </param> protected AGraphElement(Int32 id, UInt32 creationDate, PropertyContainer[] properties) { Id = id; CreationDate = creationDate; ModificationDate = 0; _properties = properties; } #endregion #region public methods /// <summary> /// Gets the creation date /// </summary> /// <returns> Creation date </returns> public DateTime GetCreationDate() { if (ReadResource()) { try { var creationDate = DateHelper.GetDateTimeFromUnixTimeStamp(CreationDate); return creationDate; } finally { FinishReadResource(); } } throw new CollisionException(this); } /// <summary> /// Gets the modification date /// </summary> /// <returns> Modification date </returns> public DateTime GetModificationDate() { if (ReadResource()) { try { var modificationDate = DateHelper.GetDateTimeFromUnixTimeStamp(CreationDate + ModificationDate); return modificationDate; } finally { FinishReadResource(); } } throw new CollisionException(this); } /// <summary> /// Returns the count of properties /// </summary> /// <returns> Count of Properties </returns> public Int32 GetPropertyCount() { if (ReadResource()) { try { var count = _properties.Length; return count; } finally { FinishReadResource(); } } throw new CollisionException(this); } /// <summary> /// Gets all properties. /// </summary> /// <returns> All properties. </returns> public ReadOnlyCollection<PropertyContainer> GetAllProperties() { if (ReadResource()) { try { var result = _properties != null ? new ReadOnlyCollection<PropertyContainer>(_properties) : new ReadOnlyCollection<PropertyContainer>(new PropertyContainer[0]); return result; } finally { FinishReadResource(); } } throw new CollisionException(this); } /// <summary> /// Tries the get property. /// </summary> /// <typeparam name="TProperty"> Type of the property </typeparam> /// <param name="result"> Result. </param> /// <param name="propertyId"> Property identifier. </param> /// <returns> <c>true</c> if something was found; otherwise, <c>false</c> . </returns> public Boolean TryGetProperty<TProperty>(out TProperty result, UInt16 propertyId) { if (ReadResource()) { try { if (_properties != null) { for (var i = 0; i < _properties.Length; i++) { var aPropContainer = _properties[i]; if (aPropContainer.Value != null && aPropContainer.PropertyId == propertyId) { result = (TProperty)aPropContainer.Value; return true; } } } result = default(TProperty); return false; } finally { FinishReadResource(); } } throw new CollisionException(this); } #endregion #region internal methods /// <summary> /// Trims the graph element /// </summary> internal virtual void Trim() { //do nothing } /// <summary> /// Tries to add a property. /// </summary> /// <returns> <c>true</c> if it was an update; otherwise, <c>false</c> . </returns> /// <param name='propertyId'> If set to <c>true</c> property identifier. </param> /// <param name='property'> If set to <c>true</c> property. </param> /// <exception cref='CollisionException'>Is thrown when the collision exception.</exception> internal bool TryAddProperty(UInt16 propertyId, object property) { if (WriteResource()) { try { var foundProperty = false; var idx = 0; if (_properties != null) { for (var i = 0; i < _properties.Length; i++) { if (_properties[i].PropertyId == propertyId) { foundProperty = true; idx = i; break; } } if (!foundProperty) { //resize var newProperties = new PropertyContainer[_properties.Length + 1]; Array.Copy(_properties, newProperties, _properties.Length); newProperties[_properties.Length] = new PropertyContainer { PropertyId = propertyId, Value = property }; _properties = newProperties; } else { _properties[idx] = new PropertyContainer { PropertyId = propertyId, Value = property }; } } else { _properties = new PropertyContainer[0]; _properties[0] = new PropertyContainer { PropertyId = propertyId, Value = property }; } //set the modificationdate ModificationDate = DateHelper.GetModificationDate(CreationDate); return foundProperty; } finally { FinishWriteResource(); } } throw new CollisionException(this); } /// <summary> /// Tries to remove a property. /// </summary> /// <returns> <c>true</c> if the property was removed; otherwise, <c>false</c> if there was no such property. </returns> /// <param name='propertyId'> If set to <c>true</c> property identifier. </param> /// <exception cref='CollisionException'>Is thrown when the collision exception.</exception> internal bool TryRemoveProperty(UInt16 propertyId) { if (WriteResource()) { try { var removedSomething = false; if (_properties != null) { var toBeRemovedIdx = 0; for (var i = 0; i < _properties.Length; i++) { if (_properties[i].PropertyId == propertyId) { toBeRemovedIdx = i; removedSomething = true; break; } } if (removedSomething) { //resize var newProperties = new PropertyContainer[_properties.Length - 1]; if (newProperties.Length != 0) { //everything until the to be removed item Array.Copy(_properties, newProperties, toBeRemovedIdx); if (toBeRemovedIdx > newProperties.Length) { //everything after the removed item Array.Copy(_properties, toBeRemovedIdx + 1, newProperties, toBeRemovedIdx, _properties.Length - toBeRemovedIdx); } _properties = newProperties; } //set the modificationdate ModificationDate = DateHelper.GetModificationDate(CreationDate); } } return removedSomething; } finally { FinishWriteResource(); } } throw new CollisionException(this); } /// <summary> /// Sets the id of the element /// </summary> /// <param name="newId">The new id</param> internal void SetId(Int32 newId) { if (WriteResource()) { Id = newId; FinishWriteResource(); return; } throw new CollisionException(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) 2003 Patrick Kalkman // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; using System.ComponentModel; using System.IO; namespace System.Data.Tests { public class DataViewTest : IDisposable { private DataTable _dataTable; private DataView _dataView; private Random _rndm; private int _seed,_rowCount; private ListChangedEventArgs _listChangedArgs; private TextWriter _eventWriter; private DataColumn _dc1; private DataColumn _dc2; private DataColumn _dc3; private DataColumn _dc4; public DataViewTest() { _dataTable = new DataTable("itemTable"); _dc1 = new DataColumn("itemId"); _dc2 = new DataColumn("itemName"); _dc3 = new DataColumn("itemPrice"); _dc4 = new DataColumn("itemCategory"); _dataTable.Columns.Add(_dc1); _dataTable.Columns.Add(_dc2); _dataTable.Columns.Add(_dc3); _dataTable.Columns.Add(_dc4); DataRow dr; _seed = 123; _rowCount = 5; _rndm = new Random(_seed); for (int i = 1; i <= _rowCount; i++) { dr = _dataTable.NewRow(); dr["itemId"] = "item " + i; dr["itemName"] = "name " + _rndm.Next(); dr["itemPrice"] = "Rs. " + (_rndm.Next() % 1000); dr["itemCategory"] = "Cat " + ((_rndm.Next() % 10) + 1); _dataTable.Rows.Add(dr); } _dataTable.AcceptChanges(); _dataView = new DataView(_dataTable); _dataView.ListChanged += new ListChangedEventHandler(OnListChanged); _listChangedArgs = null; } protected void OnListChanged(object sender, ListChangedEventArgs args) { _listChangedArgs = args; } private void PrintTableOrView(DataTable t, string label) { Console.WriteLine("\n" + label); for (int i = 0; i < t.Rows.Count; i++) { foreach (DataColumn dc in t.Columns) Console.Write(t.Rows[i][dc] + "\t"); Console.WriteLine(""); } Console.WriteLine(); } private void PrintTableOrView(DataView dv, string label) { Console.WriteLine("\n" + label); Console.WriteLine("Sort Key :: " + dv.Sort); for (int i = 0; i < dv.Count; i++) { foreach (DataColumn dc in dv.Table.Columns) Console.Write(dv[i].Row[dc] + "\t"); Console.WriteLine(""); } Console.WriteLine(); } public void Dispose() { _dataTable = null; _dataView = null; } [Fact] public void TestSortWithoutTable() { DataView dv = new DataView(); Assert.Throws<DataException>(() => dv.Sort = "abc"); } [Fact] public void TestSort() { DataView dv = new DataView(); dv.Table = new DataTable("dummy"); dv.Table.Columns.Add("abc"); dv.Sort = "abc"; dv.Sort = string.Empty; dv.Sort = "abc"; Assert.Equal("abc", dv.Sort); } [Fact] public void DataView() { DataView dv1, dv2, dv3; dv1 = new DataView(); // AssertEquals ("test#01",null,dv1.Table); Assert.Equal(true, dv1.AllowNew); Assert.Equal(true, dv1.AllowEdit); Assert.Equal(true, dv1.AllowDelete); Assert.Equal(false, dv1.ApplyDefaultSort); Assert.Equal(string.Empty, dv1.RowFilter); Assert.Equal(DataViewRowState.CurrentRows, dv1.RowStateFilter); Assert.Equal(string.Empty, dv1.Sort); dv2 = new DataView(_dataTable); Assert.Equal("itemTable", dv2.Table.TableName); Assert.Equal(string.Empty, dv2.Sort); Assert.Equal(false, dv2.ApplyDefaultSort); Assert.Equal(_dataTable.Rows[0], dv2[0].Row); dv3 = new DataView(_dataTable, "", "itemId DESC", DataViewRowState.CurrentRows); Assert.Equal("", dv3.RowFilter); Assert.Equal("itemId DESC", dv3.Sort); Assert.Equal(DataViewRowState.CurrentRows, dv3.RowStateFilter); //AssertEquals ("test#16",dataTable.Rows.[(dataTable.Rows.Count-1)],dv3[0]); } [Fact] public void TestValue() { DataView TestView = new DataView(_dataTable); Assert.Equal("item 1", TestView[0]["itemId"]); } [Fact] public void TestCount() { DataView TestView = new DataView(_dataTable); Assert.Equal(5, TestView.Count); } [Fact] public void AllowNew() { Assert.Equal(true, _dataView.AllowNew); } [Fact] public void ApplyDefaultSort() { UniqueConstraint uc = new UniqueConstraint(_dataTable.Columns["itemId"]); _dataTable.Constraints.Add(uc); _dataView.ApplyDefaultSort = true; // dataView.Sort = "itemName"; // AssertEquals ("test#01","item 1",dataView[0]["itemId"]); Assert.Equal(ListChangedType.Reset, _listChangedArgs.ListChangedType); // UnComment the line below to see if dataView is sorted // PrintTableOrView (dataView,"* OnApplyDefaultSort"); } [Fact] public void RowStateFilter() { _dataView.RowStateFilter = DataViewRowState.Deleted; Assert.Equal(ListChangedType.Reset, _listChangedArgs.ListChangedType); } [Fact] public void RowStateFilter_2() { DataSet dataset = new DataSet("new"); DataTable dt = new DataTable("table1"); dataset.Tables.Add(dt); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Rows.Add(new object[] { 1, 1 }); dt.Rows.Add(new object[] { 1, 2 }); dt.Rows.Add(new object[] { 1, 3 }); dataset.AcceptChanges(); DataView dataView = new DataView(dataset.Tables[0]); // 'new' table in this sample contains 6 records dataView.AllowEdit = true; dataView.AllowDelete = true; string v; // Editing the row dataView[0]["col1"] = -1; dataView.RowStateFilter = DataViewRowState.ModifiedOriginal; v = dataView[0][0].ToString(); Assert.Equal(1, dataView.Count); Assert.Equal("1", v); // Deleting the row dataView.Delete(0); dataView.RowStateFilter = DataViewRowState.Deleted; v = dataView[0][0].ToString(); Assert.Equal(1, dataView.Count); Assert.Equal("1", v); } [Fact] public void Bug18898() { var table = new DataTable(); table.Columns.Add("col1"); table.Columns.Add("col2"); table.Rows.Add("1", "2"); table.Rows.Add("4", "3"); table.AcceptChanges(); table.Rows.Add("5", "6"); DataView dv = new DataView(table, string.Empty, string.Empty, DataViewRowState.Added); dv.AllowNew = true; var new_row = dv.AddNew(); new_row[0] = "7"; new_row[1] = "8"; var another_new_row = dv.AddNew(); another_new_row[0] = "9"; another_new_row[1] = "10"; Assert.Equal(dv[2][0], "9"); //This should not throw a System.Data.VersionNotFoundException: "There is no Proposed data to accces" Assert.Equal(dv[1][0], "7"); } [Fact] public void NullTableGetItemPropertiesTest() { DataView dataview = new DataView(); PropertyDescriptorCollection col = ((ITypedList)dataview).GetItemProperties(null); Assert.Equal(0, col.Count); } #region Sort Tests [Fact] public void SortListChangedTest() { _dataView.Sort = "itemName DESC"; Assert.Equal(ListChangedType.Reset, _listChangedArgs.ListChangedType); // UnComment the line below to see if dataView is sorted // PrintTableOrView (dataView); } [Fact] public void SortTestWeirdColumnName() { DataTable dt = new DataTable(); dt.Columns.Add("id]", typeof(int)); dt.Columns.Add("[id", typeof(int)); DataView dv = dt.DefaultView; dv.Sort = "id]"; //dv.Sort = "[id"; // this is not allowed dv.Sort = "[id]]"; dv.Sort = "[[id]"; dv.Sort = "id] ASC"; dv.Sort = "[id]] DESC"; dv.Sort = "[[id] ASC"; } [Fact] public void SortTests() { DataTable dataTable = new DataTable("itemTable"); DataColumn dc1 = new DataColumn("itemId", typeof(int)); DataColumn dc2 = new DataColumn("itemName", typeof(string)); dataTable.Columns.Add(dc1); dataTable.Columns.Add(dc2); dataTable.Rows.Add(new object[2] { 1, "First entry" }); dataTable.Rows.Add(new object[2] { 0, "Second entry" }); dataTable.Rows.Add(new object[2] { 3, "Third entry" }); dataTable.Rows.Add(new object[2] { 2, "Fourth entry" }); DataView dataView = dataTable.DefaultView; string s = "Default sorting: "; Assert.Equal(1, dataView[0][0]); Assert.Equal(0, dataView[1][0]); Assert.Equal(3, dataView[2][0]); Assert.Equal(2, dataView[3][0]); s = "Ascending sorting 1: "; dataView.Sort = "itemId ASC"; Assert.Equal(0, dataView[0][0]); Assert.Equal(1, dataView[1][0]); Assert.Equal(2, dataView[2][0]); Assert.Equal(3, dataView[3][0]); s = "Ascending sorting 2: "; dataView.Sort = "itemId ASC"; Assert.Equal(0, dataView[0][0]); Assert.Equal(1, dataView[1][0]); Assert.Equal(2, dataView[2][0]); Assert.Equal(3, dataView[3][0]); s = "Ascending sorting 3: "; dataView.Sort = "[itemId] ASC"; Assert.Equal(0, dataView[0][0]); Assert.Equal(1, dataView[1][0]); Assert.Equal(2, dataView[2][0]); Assert.Equal(3, dataView[3][0]); s = "Ascending sorting 4: "; dataView.Sort = "[itemId] ASC"; Assert.Equal(0, dataView[0][0]); Assert.Equal(1, dataView[1][0]); Assert.Equal(2, dataView[2][0]); Assert.Equal(3, dataView[3][0]); s = "Ascending sorting 5: "; try { dataView.Sort = "itemId \tASC"; Assert.Equal(true, false); } catch (IndexOutOfRangeException e) { } s = "Descending sorting : "; dataView.Sort = "itemId DESC"; Assert.Equal(3, dataView[0][0]); Assert.Equal(2, dataView[1][0]); Assert.Equal(1, dataView[2][0]); Assert.Equal(0, dataView[3][0]); s = "Reverted to default sorting: "; dataView.Sort = null; Assert.Equal(1, dataView[0][0]); Assert.Equal(0, dataView[1][0]); Assert.Equal(3, dataView[2][0]); Assert.Equal(2, dataView[3][0]); } #endregion // Sort Tests [Fact] public void AddNew_1() { Assert.Throws<DataException>(() => { _dataView.AllowNew = false; DataRowView drv = _dataView.AddNew(); }); } [Fact] public void AddNew_2() { _dataView.AllowNew = true; DataRowView drv = _dataView.AddNew(); Assert.Equal(ListChangedType.ItemAdded, _listChangedArgs.ListChangedType); Assert.Equal(-1, _listChangedArgs.OldIndex); Assert.Equal(5, _listChangedArgs.NewIndex); Assert.Equal(drv["itemName"], _dataView[_dataView.Count - 1]["itemName"]); _listChangedArgs = null; drv["itemId"] = "item " + 1001; drv["itemName"] = "name " + _rndm.Next(); drv["itemPrice"] = "Rs. " + (_rndm.Next() % 1000); drv["itemCategory"] = "Cat " + ((_rndm.Next() % 10) + 1); // Actually no events are arisen when items are set. Assert.Null(_listChangedArgs); drv.CancelEdit(); Assert.Equal(ListChangedType.ItemDeleted, _listChangedArgs.ListChangedType); Assert.Equal(-1, _listChangedArgs.OldIndex); Assert.Equal(5, _listChangedArgs.NewIndex); } [Fact] public void BeginInit() { DataTable table = new DataTable("table"); DataView dv = new DataView(); DataColumn col1 = new DataColumn("col1"); DataColumn col2 = new DataColumn("col2"); dv.BeginInit(); table.BeginInit(); table.Columns.AddRange(new DataColumn[] { col1, col2 }); dv.Table = table; Assert.Null(dv.Table); dv.EndInit(); Assert.Null(dv.Table); Assert.Equal(0, table.Columns.Count); table.EndInit(); Assert.Equal(table, dv.Table); Assert.Equal(2, table.Columns.Count); } private bool _dvInitialized; private void OnDataViewInitialized(object src, EventArgs args) { _dvInitialized = true; } [Fact] public void BeginInit2() { DataTable table = new DataTable("table"); DataView dv = new DataView(); DataColumn col1 = new DataColumn("col1"); DataColumn col2 = new DataColumn("col2"); _dvInitialized = false; dv.Initialized += new EventHandler(OnDataViewInitialized); dv.BeginInit(); table.BeginInit(); table.Columns.AddRange(new DataColumn[] { col1, col2 }); dv.Table = table; Assert.Null(dv.Table); dv.EndInit(); Assert.Null(dv.Table); Assert.Equal(0, table.Columns.Count); table.EndInit(); dv.Initialized -= new EventHandler(OnDataViewInitialized); // this should not be unregistered before table.EndInit(). Assert.Equal(2, table.Columns.Count); Assert.Equal(table, dv.Table); Assert.Equal(true, _dvInitialized); } [Fact] public void Find_1() { Assert.Throws<ArgumentException>(() => { /* since the sort key is not specified. Must raise a ArgumentException */ int sIndex = _dataView.Find("abc"); }); } [Fact] public void Find_2() { int randInt; DataRowView drv; randInt = _rndm.Next() % _rowCount; _dataView.Sort = "itemId"; drv = _dataView[randInt]; Assert.Equal(randInt, _dataView.Find(drv["itemId"])); _dataView.Sort = "itemId DESC"; drv = _dataView[randInt]; Assert.Equal(randInt, _dataView.Find(drv["itemId"])); _dataView.Sort = "itemId, itemName"; drv = _dataView[randInt]; object[] keys = new object[2]; keys[0] = drv["itemId"]; keys[1] = drv["itemName"]; Assert.Equal(randInt, _dataView.Find(keys)); _dataView.Sort = "itemId"; Assert.Equal(-1, _dataView.Find("no item")); } [Fact] public void Find_3() { Assert.Throws<ArgumentException>(() => { _dataView.Sort = "itemID, itemName"; /* expecting order key count mismatch */ _dataView.Find("itemValue"); }); } [Fact] public void ToStringTest() { Assert.Equal("System.Data.DataView", _dataView.ToString()); } [Fact] public void TestingEventHandling() { _dataView.Sort = "itemId"; DataRow dr; dr = _dataTable.NewRow(); dr["itemId"] = "item 0"; dr["itemName"] = "name " + _rndm.Next(); dr["itemPrice"] = "Rs. " + (_rndm.Next() % 1000); dr["itemCategory"] = "Cat " + ((_rndm.Next() % 10) + 1); _dataTable.Rows.Add(dr); //PrintTableOrView(dataView, "ItemAdded"); Assert.Equal(ListChangedType.ItemAdded, _listChangedArgs.ListChangedType); _listChangedArgs = null; dr["itemId"] = "aitem 0"; // PrintTableOrView(dataView, "ItemChanged"); Assert.Equal(ListChangedType.ItemChanged, _listChangedArgs.ListChangedType); _listChangedArgs = null; dr["itemId"] = "zitem 0"; // PrintTableOrView(dataView, "ItemMoved"); Assert.Equal(ListChangedType.ItemMoved, _listChangedArgs.ListChangedType); _listChangedArgs = null; _dataTable.Rows.Remove(dr); // PrintTableOrView(dataView, "ItemDeleted"); Assert.Equal(ListChangedType.ItemDeleted, _listChangedArgs.ListChangedType); _listChangedArgs = null; DataColumn dc5 = new DataColumn("itemDesc"); _dataTable.Columns.Add(dc5); // PrintTableOrView(dataView, "PropertyDescriptorAdded"); Assert.Equal(ListChangedType.PropertyDescriptorAdded, _listChangedArgs.ListChangedType); _listChangedArgs = null; dc5.ColumnName = "itemDescription"; // PrintTableOrView(dataView, "PropertyDescriptorChanged"); // Assert.Equal ("test#06",ListChangedType.PropertyDescriptorChanged); _listChangedArgs = null; _dataTable.Columns.Remove(dc5); // PrintTableOrView(dataView, "PropertyDescriptorDeleted"); Assert.Equal(ListChangedType.PropertyDescriptorDeleted, _listChangedArgs.ListChangedType); } [Fact] public void TestFindRows() { DataView TestView = new DataView(_dataTable); TestView.Sort = "itemId"; DataRowView[] Result = TestView.FindRows("item 3"); Assert.Equal(1, Result.Length); Assert.Equal("item 3", Result[0]["itemId"]); } [Fact] public void FindRowsWithoutSort() { Assert.Throws<ArgumentException>(() => { DataTable dt = new DataTable("table"); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(new object[] { 1, 2, 3 }); dt.Rows.Add(new object[] { 4, 5, 6 }); dt.Rows.Add(new object[] { 4, 7, 8 }); dt.Rows.Add(new object[] { 5, 7, 8 }); dt.Rows.Add(new object[] { 4, 8, 9 }); DataView dv = new DataView(dt); dv.Find(1); }); } [Fact] public void FindRowsInconsistentKeyLength() { Assert.Throws<ArgumentException>(() => { DataTable dt = new DataTable("table"); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(new object[] { 1, 2, 3 }); dt.Rows.Add(new object[] { 4, 5, 6 }); dt.Rows.Add(new object[] { 4, 7, 8 }); dt.Rows.Add(new object[] { 5, 7, 8 }); dt.Rows.Add(new object[] { 4, 8, 9 }); DataView dv = new DataView(dt, null, "col1", DataViewRowState.CurrentRows); dv.FindRows(new object[] { 1, 2, 3 }); }); } [Fact] public void TestDelete() { Assert.Throws<DeletedRowInaccessibleException>(() => { DataView TestView = new DataView(_dataTable); TestView.Delete(0); DataRow r = TestView.Table.Rows[0]; Assert.True(!((string)r["itemId"] == "item 1")); }); } [Fact] public void TestDeleteOutOfBounds() { Assert.Throws<IndexOutOfRangeException>(() => { DataView TestView = new DataView(_dataTable); TestView.Delete(100); }); } [Fact] public void TestDeleteNotAllowed() { Assert.Throws<DataException>(() => { DataView TestView = new DataView(_dataTable); TestView.AllowDelete = false; TestView.Delete(0); }); } [Fact] public void TestDeleteClosed() { Assert.Throws<IndexOutOfRangeException>(() => { DataView TestView = new DataView(_dataTable); TestView.Dispose(); // Close the table TestView.Delete(0); // cannot access to item at 0. }); } [Fact] public void TestDeleteAndCount() { DataSet dataset = new DataSet("new"); DataTable dt = new DataTable("table1"); dataset.Tables.Add(dt); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Rows.Add(new object[] { 1, 1 }); dt.Rows.Add(new object[] { 1, 2 }); dt.Rows.Add(new object[] { 1, 3 }); DataView dataView = new DataView(dataset.Tables[0]); Assert.Equal(3, dataView.Count); dataView.AllowDelete = true; // Deleting the first row dataView.Delete(0); Assert.Equal(2, dataView.Count); } [Fact] public void ListChangeOnSetItem() { DataTable dt = new DataTable("table"); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(new object[] { 1, 2, 3 }); dt.AcceptChanges(); DataView dv = new DataView(dt); dv.ListChanged += new ListChangedEventHandler(OnChange); dv[0]["col1"] = 4; } private ListChangedEventArgs _listChangeArgOnSetItem; private void OnChange(object o, ListChangedEventArgs e) { if (_listChangeArgOnSetItem != null) throw new Exception("The event is already fired."); _listChangeArgOnSetItem = e; } [Fact] public void CancelEditAndEvents() { string reference = " =====ItemAdded:3 ------4 =====ItemAdded:3 =====ItemAdded:4 ------5 =====ItemAdded:4 =====ItemAdded:5 ------6 =====ItemDeleted:5 ------5 =====ItemAdded:5"; _eventWriter = new StringWriter(); DataTable dt = new DataTable(); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Rows.Add(new object[] { 1, 2, 3 }); dt.Rows.Add(new object[] { 1, 2, 3 }); dt.Rows.Add(new object[] { 1, 2, 3 }); DataView dv = new DataView(dt); dv.ListChanged += new ListChangedEventHandler(ListChanged); DataRowView a1 = dv.AddNew(); _eventWriter.Write(" ------" + dv.Count); // I wonder why but MS fires another event here. a1 = dv.AddNew(); _eventWriter.Write(" ------" + dv.Count); // I wonder why but MS fires another event here. DataRowView a2 = dv.AddNew(); _eventWriter.Write(" ------" + dv.Count); a2.CancelEdit(); _eventWriter.Write(" ------" + dv.Count); DataRowView a3 = dv.AddNew(); Assert.Equal(reference, _eventWriter.ToString()); GC.KeepAlive(dv); } [Fact] public void ColumnChangeName() { string result = @"setting table... ---- OnListChanged PropertyDescriptorChanged,0,0 ---- OnListChanged Reset,-1,-1 table was set. ---- OnListChanged PropertyDescriptorChanged,0,0 "; _eventWriter = new StringWriter(); ComplexEventSequence1View dv = new ComplexEventSequence1View(_dataTable, _eventWriter); _dc2.ColumnName = "new_column_name"; Assert.Equal(result.Replace("\r\n", "\n"), _eventWriter.ToString().Replace("\r\n", "\n")); GC.KeepAlive(dv); } private void ListChanged(object o, ListChangedEventArgs e) { _eventWriter.Write(" =====" + e.ListChangedType + ":" + e.NewIndex); } [Fact] public void DefaultColumnNameAddListChangedTest() { string result = @"setting table... ---- OnListChanged PropertyDescriptorChanged,0,0 ---- OnListChanged Reset,-1,-1 table was set. ---- OnListChanged PropertyDescriptorAdded,0,0 default named column added. ---- OnListChanged PropertyDescriptorAdded,0,0 non-default named column added. ---- OnListChanged PropertyDescriptorAdded,0,0 another default named column added (Column2). ---- OnListChanged PropertyDescriptorAdded,0,0 add a column with the same name as the default columnnames. ---- OnListChanged PropertyDescriptorAdded,0,0 add a column with a null name. ---- OnListChanged PropertyDescriptorAdded,0,0 add a column with an empty name. "; _eventWriter = new StringWriter(); DataTable dt = new DataTable("table"); ComplexEventSequence1View dv = new ComplexEventSequence1View(dt, _eventWriter); dt.Columns.Add(); _eventWriter.WriteLine(" default named column added."); dt.Columns.Add("non-defaultNamedColumn"); _eventWriter.WriteLine(" non-default named column added."); DataColumn c = dt.Columns.Add(); _eventWriter.WriteLine(" another default named column added ({0}).", c.ColumnName); dt.Columns.Add("Column3"); _eventWriter.WriteLine(" add a column with the same name as the default columnnames."); dt.Columns.Add((string)null); _eventWriter.WriteLine(" add a column with a null name."); dt.Columns.Add(""); _eventWriter.WriteLine(" add a column with an empty name."); Assert.Equal(result.Replace("\r\n", "\n"), _eventWriter.ToString().Replace("\r\n", "\n")); GC.KeepAlive(dv); } public class ComplexEventSequence1View : DataView { private TextWriter _w; public ComplexEventSequence1View(DataTable dt, TextWriter w) : base() { _w = w; w.WriteLine("setting table..."); Table = dt; w.WriteLine("table was set."); } protected override void OnListChanged(ListChangedEventArgs e) { if (_w != null) _w.WriteLine("---- OnListChanged " + e.ListChangedType + "," + e.NewIndex + "," + e.OldIndex); base.OnListChanged(e); } protected override void UpdateIndex(bool force) { if (_w != null) _w.WriteLine("----- UpdateIndex : " + force); base.UpdateIndex(force); } } } }
namespace BooCompiler.Tests { using NUnit.Framework; using Boo.Lang.Compiler; using Boo.Lang.Compiler.Pipelines; [TestFixture] public class DuckyTestFixture : AbstractCompilerTestCase { protected override void CustomizeCompilerParameters() { _parameters.Ducky = true; } [Test] public void BOO_827_1() { RunCompilerTestCase(@"BOO-827-1.boo"); } [Test] public void callable_1() { RunCompilerTestCase(@"callable-1.boo"); } [Test] public void duck_12() { RunCompilerTestCase(@"duck-12.boo"); } [Test] public void duck_slice_1() { RunCompilerTestCase(@"duck-slice-1.boo"); } [Test] public void ducky_1() { RunCompilerTestCase(@"ducky-1.boo"); } [Test] public void ducky_10() { RunCompilerTestCase(@"ducky-10.boo"); } [Test] public void ducky_11() { RunCompilerTestCase(@"ducky-11.boo"); } [Test] public void ducky_2() { RunCompilerTestCase(@"ducky-2.boo"); } [Test] public void ducky_3() { RunCompilerTestCase(@"ducky-3.boo"); } [Test] public void ducky_4() { RunCompilerTestCase(@"ducky-4.boo"); } [Test] public void ducky_5() { RunCompilerTestCase(@"ducky-5.boo"); } [Test] public void ducky_6() { RunCompilerTestCase(@"ducky-6.boo"); } [Test] public void ducky_7() { RunCompilerTestCase(@"ducky-7.boo"); } [Test] public void ducky_8() { RunCompilerTestCase(@"ducky-8.boo"); } [Test] public void ducky_9() { RunCompilerTestCase(@"ducky-9.boo"); } [Test] public void implicit_1() { RunCompilerTestCase(@"implicit-1.boo"); } [Test] public void implicit_2() { RunCompilerTestCase(@"implicit-2.boo"); } [Test] public void implicit_3() { RunCompilerTestCase(@"implicit-3.boo"); } [Test] public void method_dispatch_1() { RunCompilerTestCase(@"method-dispatch-1.boo"); } [Test] public void method_dispatch_10() { RunCompilerTestCase(@"method-dispatch-10.boo"); } [Test] public void method_dispatch_11() { RunCompilerTestCase(@"method-dispatch-11.boo"); } [Test] public void method_dispatch_12() { RunCompilerTestCase(@"method-dispatch-12.boo"); } [Test] public void method_dispatch_2() { RunCompilerTestCase(@"method-dispatch-2.boo"); } [Test] public void method_dispatch_3() { RunCompilerTestCase(@"method-dispatch-3.boo"); } [Test] public void method_dispatch_4() { RunCompilerTestCase(@"method-dispatch-4.boo"); } [Test] public void method_dispatch_5() { RunCompilerTestCase(@"method-dispatch-5.boo"); } [Test] public void method_dispatch_6() { RunCompilerTestCase(@"method-dispatch-6.boo"); } [Test] public void method_dispatch_7() { RunCompilerTestCase(@"method-dispatch-7.boo"); } [Test] public void method_dispatch_8() { RunCompilerTestCase(@"method-dispatch-8.boo"); } [Test] public void method_dispatch_9() { RunCompilerTestCase(@"method-dispatch-9.boo"); } [Test] public void null_initializer_1() { RunCompilerTestCase(@"null-initializer-1.boo"); } [Test] public void object_construction_1() { RunCompilerTestCase(@"object-construction-1.boo"); } [Test] public void object_overloads_1() { RunCompilerTestCase(@"object-overloads-1.boo"); } override protected string GetRelativeTestCasesPath() { return "ducky"; } } }