context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Text; using System.Web; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Orders; using Nop.Core.Html; using Nop.Services.Directory; using Nop.Services.Localization; using Nop.Services.Media; using Nop.Services.Tax; namespace Nop.Services.Catalog { /// <summary> /// Product attribute formatter /// </summary> public partial class ProductAttributeFormatter : IProductAttributeFormatter { private readonly IWorkContext _workContext; private readonly IProductAttributeService _productAttributeService; private readonly IProductAttributeParser _productAttributeParser; private readonly ICurrencyService _currencyService; private readonly ILocalizationService _localizationService; private readonly ITaxService _taxService; private readonly IPriceFormatter _priceFormatter; private readonly IDownloadService _downloadService; private readonly IWebHelper _webHelper; private readonly IPriceCalculationService _priceCalculationService; private readonly ShoppingCartSettings _shoppingCartSettings; public ProductAttributeFormatter(IWorkContext workContext, IProductAttributeService productAttributeService, IProductAttributeParser productAttributeParser, ICurrencyService currencyService, ILocalizationService localizationService, ITaxService taxService, IPriceFormatter priceFormatter, IDownloadService downloadService, IWebHelper webHelper, IPriceCalculationService priceCalculationService, ShoppingCartSettings shoppingCartSettings) { this._workContext = workContext; this._productAttributeService = productAttributeService; this._productAttributeParser = productAttributeParser; this._currencyService = currencyService; this._localizationService = localizationService; this._taxService = taxService; this._priceFormatter = priceFormatter; this._downloadService = downloadService; this._webHelper = webHelper; this._priceCalculationService = priceCalculationService; this._shoppingCartSettings = shoppingCartSettings; } /// <summary> /// Formats attributes /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Attributes</returns> public string FormatAttributes(Product product, string attributesXml) { var customer = _workContext.CurrentCustomer; return FormatAttributes(product, attributesXml, customer); } /// <summary> /// Formats attributes /// </summary> /// <param name="product">Product</param> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customer">Customer</param> /// <param name="serapator">Serapator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param> /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param> /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param> /// <returns>Attributes</returns> public string FormatAttributes(Product product, string attributesXml, Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool renderProductAttributes = true, bool renderGiftCardAttributes = true, bool allowHyperlinks = true) { var result = new StringBuilder(); //attributes if (renderProductAttributes) { var attributes = _productAttributeParser.ParseProductAttributeMappings(attributesXml); for (int i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; var valuesStr = _productAttributeParser.ParseValues(attributesXml, attribute.Id); for (int j = 0; j < valuesStr.Count; j++) { string valueStr = valuesStr[j]; string formattedAttribute = string.Empty; if (!attribute.ShouldHaveValues()) { //no values if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox var attributeName = attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) attributeName = HttpUtility.HtmlEncode(attributeName); formattedAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr, false, true, false, false, false, false)); //we never encode multiline textbox input } else if (attribute.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid downloadGuid; Guid.TryParse(valueStr, out downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string attributeText = ""; var fileName = string.Format("{0}{1}", download.Filename ?? download.DownloadGuid.ToString(), download.Extension); //encode (if required) if (htmlEncode) fileName = HttpUtility.HtmlEncode(fileName); if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { //hyperlinks aren't allowed attributeText = fileName; } var attributeName = attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) attributeName = HttpUtility.HtmlEncode(attributeName); formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText); } } else { //other attributes (textbox, datepicker) formattedAttribute = string.Format("{0}: {1}", attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr); //encode (if required) if (htmlEncode) formattedAttribute = HttpUtility.HtmlEncode(formattedAttribute); } } else { //attributes with values int attributeValueId; if (int.TryParse(valueStr, out attributeValueId)) { var attributeValue = _productAttributeService.GetProductAttributeValueById(attributeValueId); if (attributeValue != null) { formattedAttribute = string.Format("{0}: {1}", attribute.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)); if (renderPrices) { decimal taxRate; decimal attributeValuePriceAdjustment = _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue); decimal priceAdjustmentBase = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out taxRate); decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false); formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr); } else if (priceAdjustmentBase < decimal.Zero) { string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false); formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr); } } //display quantity if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity && attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct) { //render only when more than 1 if (attributeValue.Quantity > 1) { //TODO localize resource formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity); } } } //encode (if required) if (htmlEncode) formattedAttribute = HttpUtility.HtmlEncode(formattedAttribute); } } if (!String.IsNullOrEmpty(formattedAttribute)) { if (i != 0 || j != 0) result.Append(serapator); result.Append(formattedAttribute); } } } } //gift cards if (renderGiftCardAttributes) { if (product.IsGiftCard) { string giftCardRecipientName; string giftCardRecipientEmail; string giftCardSenderName; string giftCardSenderEmail; string giftCardMessage; _productAttributeParser.GetGiftCardAttribute(attributesXml, out giftCardRecipientName, out giftCardRecipientEmail, out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage); //sender var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName); //recipient var giftCardFor = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName); //encode (if required) if (htmlEncode) { giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom); giftCardFor = HttpUtility.HtmlEncode(giftCardFor); } if (!String.IsNullOrEmpty(result.ToString())) { result.Append(serapator); } result.Append(giftCardFrom); result.Append(serapator); result.Append(giftCardFor); } } return result.ToString(); } } }
/* '=============================================================================== ' Generated From - CSharp_dOOdads_BusinessEntity.vbgen ' ' ** IMPORTANT ** ' How to Generate your stored procedures: ' ' SQL = SQL_StoredProcs.vbgen ' ACCESS = Access_StoredProcs.vbgen ' ORACLE = Oracle_StoredProcs.vbgen ' FIREBIRD = FirebirdStoredProcs.vbgen ' POSTGRESQL = PostgreSQL_StoredProcs.vbgen ' ' The supporting base class SqlClientEntity is in the Architecture directory in "dOOdads". ' ' This object is 'abstract' which means you need to inherit from it to be able ' to instantiate it. This is very easilly done. You can override properties and ' methods in your derived class, this allows you to regenerate this class at any ' time and not worry about overwriting custom code. ' ' NEVER EDIT THIS FILE. ' ' public class YourObject : _YourObject ' { ' ' } ' '=============================================================================== */ // Generated by MyGeneration Version # (1.3.0.3) using System; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Specialized; using MyGeneration.dOOdads; namespace nTier.Entity { public abstract class _Orders : SqlClientEntity { public _Orders() { this.QuerySource = "Orders"; this.MappingName = "Orders"; } //================================================================= // public Overrides void AddNew() //================================================================= // //================================================================= public override void AddNew() { base.AddNew(); } public override void FlushData() { this._whereClause = null; this._aggregateClause = null; base.FlushData(); } //================================================================= // public Function LoadAll() As Boolean //================================================================= // Loads all of the records in the database, and sets the currentRow to the first row //================================================================= public bool LoadAll() { ListDictionary parameters = null; return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_OrdersLoadAll]", parameters); } //================================================================= // public Overridable Function LoadByPrimaryKey() As Boolean //================================================================= // Loads a single row of via the primary key //================================================================= public virtual bool LoadByPrimaryKey(int OrderID) { ListDictionary parameters = new ListDictionary(); parameters.Add(Parameters.OrderID, OrderID); return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_OrdersLoadByPrimaryKey]", parameters); } #region Parameters protected class Parameters { public static SqlParameter OrderID { get { return new SqlParameter("@OrderID", SqlDbType.Int, 0); } } public static SqlParameter CustomerID { get { return new SqlParameter("@CustomerID", SqlDbType.NChar, 5); } } public static SqlParameter EmployeeID { get { return new SqlParameter("@EmployeeID", SqlDbType.Int, 0); } } public static SqlParameter OrderDate { get { return new SqlParameter("@OrderDate", SqlDbType.DateTime, 0); } } public static SqlParameter RequiredDate { get { return new SqlParameter("@RequiredDate", SqlDbType.DateTime, 0); } } public static SqlParameter ShippedDate { get { return new SqlParameter("@ShippedDate", SqlDbType.DateTime, 0); } } public static SqlParameter ShipVia { get { return new SqlParameter("@ShipVia", SqlDbType.Int, 0); } } public static SqlParameter Freight { get { return new SqlParameter("@Freight", SqlDbType.Money, 0); } } public static SqlParameter ShipName { get { return new SqlParameter("@ShipName", SqlDbType.NVarChar, 40); } } public static SqlParameter ShipAddress { get { return new SqlParameter("@ShipAddress", SqlDbType.NVarChar, 60); } } public static SqlParameter ShipCity { get { return new SqlParameter("@ShipCity", SqlDbType.NVarChar, 15); } } public static SqlParameter ShipRegion { get { return new SqlParameter("@ShipRegion", SqlDbType.NVarChar, 15); } } public static SqlParameter ShipPostalCode { get { return new SqlParameter("@ShipPostalCode", SqlDbType.NVarChar, 10); } } public static SqlParameter ShipCountry { get { return new SqlParameter("@ShipCountry", SqlDbType.NVarChar, 15); } } } #endregion #region ColumnNames public class ColumnNames { public const string OrderID = "OrderID"; public const string CustomerID = "CustomerID"; public const string EmployeeID = "EmployeeID"; public const string OrderDate = "OrderDate"; public const string RequiredDate = "RequiredDate"; public const string ShippedDate = "ShippedDate"; public const string ShipVia = "ShipVia"; public const string Freight = "Freight"; public const string ShipName = "ShipName"; public const string ShipAddress = "ShipAddress"; public const string ShipCity = "ShipCity"; public const string ShipRegion = "ShipRegion"; public const string ShipPostalCode = "ShipPostalCode"; public const string ShipCountry = "ShipCountry"; static public string ToPropertyName(string columnName) { if(ht == null) { ht = new Hashtable(); ht[OrderID] = _Orders.PropertyNames.OrderID; ht[CustomerID] = _Orders.PropertyNames.CustomerID; ht[EmployeeID] = _Orders.PropertyNames.EmployeeID; ht[OrderDate] = _Orders.PropertyNames.OrderDate; ht[RequiredDate] = _Orders.PropertyNames.RequiredDate; ht[ShippedDate] = _Orders.PropertyNames.ShippedDate; ht[ShipVia] = _Orders.PropertyNames.ShipVia; ht[Freight] = _Orders.PropertyNames.Freight; ht[ShipName] = _Orders.PropertyNames.ShipName; ht[ShipAddress] = _Orders.PropertyNames.ShipAddress; ht[ShipCity] = _Orders.PropertyNames.ShipCity; ht[ShipRegion] = _Orders.PropertyNames.ShipRegion; ht[ShipPostalCode] = _Orders.PropertyNames.ShipPostalCode; ht[ShipCountry] = _Orders.PropertyNames.ShipCountry; } return (string)ht[columnName]; } static private Hashtable ht = null; } #endregion #region PropertyNames public class PropertyNames { public const string OrderID = "OrderID"; public const string CustomerID = "CustomerID"; public const string EmployeeID = "EmployeeID"; public const string OrderDate = "OrderDate"; public const string RequiredDate = "RequiredDate"; public const string ShippedDate = "ShippedDate"; public const string ShipVia = "ShipVia"; public const string Freight = "Freight"; public const string ShipName = "ShipName"; public const string ShipAddress = "ShipAddress"; public const string ShipCity = "ShipCity"; public const string ShipRegion = "ShipRegion"; public const string ShipPostalCode = "ShipPostalCode"; public const string ShipCountry = "ShipCountry"; static public string ToColumnName(string propertyName) { if(ht == null) { ht = new Hashtable(); ht[OrderID] = _Orders.ColumnNames.OrderID; ht[CustomerID] = _Orders.ColumnNames.CustomerID; ht[EmployeeID] = _Orders.ColumnNames.EmployeeID; ht[OrderDate] = _Orders.ColumnNames.OrderDate; ht[RequiredDate] = _Orders.ColumnNames.RequiredDate; ht[ShippedDate] = _Orders.ColumnNames.ShippedDate; ht[ShipVia] = _Orders.ColumnNames.ShipVia; ht[Freight] = _Orders.ColumnNames.Freight; ht[ShipName] = _Orders.ColumnNames.ShipName; ht[ShipAddress] = _Orders.ColumnNames.ShipAddress; ht[ShipCity] = _Orders.ColumnNames.ShipCity; ht[ShipRegion] = _Orders.ColumnNames.ShipRegion; ht[ShipPostalCode] = _Orders.ColumnNames.ShipPostalCode; ht[ShipCountry] = _Orders.ColumnNames.ShipCountry; } return (string)ht[propertyName]; } static private Hashtable ht = null; } #endregion #region StringPropertyNames public class StringPropertyNames { public const string OrderID = "s_OrderID"; public const string CustomerID = "s_CustomerID"; public const string EmployeeID = "s_EmployeeID"; public const string OrderDate = "s_OrderDate"; public const string RequiredDate = "s_RequiredDate"; public const string ShippedDate = "s_ShippedDate"; public const string ShipVia = "s_ShipVia"; public const string Freight = "s_Freight"; public const string ShipName = "s_ShipName"; public const string ShipAddress = "s_ShipAddress"; public const string ShipCity = "s_ShipCity"; public const string ShipRegion = "s_ShipRegion"; public const string ShipPostalCode = "s_ShipPostalCode"; public const string ShipCountry = "s_ShipCountry"; } #endregion #region Properties public virtual int? OrderID { get { return base.Getint(ColumnNames.OrderID); } set { base.Setint(ColumnNames.OrderID, value); } } public virtual string CustomerID { get { return base.Getstring(ColumnNames.CustomerID); } set { base.Setstring(ColumnNames.CustomerID, value); } } public virtual int? EmployeeID { get { return base.Getint(ColumnNames.EmployeeID); } set { base.Setint(ColumnNames.EmployeeID, value); } } public virtual DateTime? OrderDate { get { return base.GetDateTime(ColumnNames.OrderDate); } set { base.SetDateTime(ColumnNames.OrderDate, value); } } public virtual DateTime? RequiredDate { get { return base.GetDateTime(ColumnNames.RequiredDate); } set { base.SetDateTime(ColumnNames.RequiredDate, value); } } public virtual DateTime? ShippedDate { get { return base.GetDateTime(ColumnNames.ShippedDate); } set { base.SetDateTime(ColumnNames.ShippedDate, value); } } public virtual int? ShipVia { get { return base.Getint(ColumnNames.ShipVia); } set { base.Setint(ColumnNames.ShipVia, value); } } public virtual decimal? Freight { get { return base.Getdecimal(ColumnNames.Freight); } set { base.Setdecimal(ColumnNames.Freight, value); } } public virtual string ShipName { get { return base.Getstring(ColumnNames.ShipName); } set { base.Setstring(ColumnNames.ShipName, value); } } public virtual string ShipAddress { get { return base.Getstring(ColumnNames.ShipAddress); } set { base.Setstring(ColumnNames.ShipAddress, value); } } public virtual string ShipCity { get { return base.Getstring(ColumnNames.ShipCity); } set { base.Setstring(ColumnNames.ShipCity, value); } } public virtual string ShipRegion { get { return base.Getstring(ColumnNames.ShipRegion); } set { base.Setstring(ColumnNames.ShipRegion, value); } } public virtual string ShipPostalCode { get { return base.Getstring(ColumnNames.ShipPostalCode); } set { base.Setstring(ColumnNames.ShipPostalCode, value); } } public virtual string ShipCountry { get { return base.Getstring(ColumnNames.ShipCountry); } set { base.Setstring(ColumnNames.ShipCountry, value); } } #endregion #region String Properties public virtual string s_OrderID { get { return this.IsColumnNull(ColumnNames.OrderID) ? string.Empty : base.GetintAsString(ColumnNames.OrderID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.OrderID); else this.OrderID = base.SetintAsString(ColumnNames.OrderID, value); } } public virtual string s_CustomerID { get { return this.IsColumnNull(ColumnNames.CustomerID) ? string.Empty : base.GetstringAsString(ColumnNames.CustomerID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.CustomerID); else this.CustomerID = base.SetstringAsString(ColumnNames.CustomerID, value); } } public virtual string s_EmployeeID { get { return this.IsColumnNull(ColumnNames.EmployeeID) ? string.Empty : base.GetintAsString(ColumnNames.EmployeeID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.EmployeeID); else this.EmployeeID = base.SetintAsString(ColumnNames.EmployeeID, value); } } public virtual string s_OrderDate { get { return this.IsColumnNull(ColumnNames.OrderDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.OrderDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.OrderDate); else this.OrderDate = base.SetDateTimeAsString(ColumnNames.OrderDate, value); } } public virtual string s_RequiredDate { get { return this.IsColumnNull(ColumnNames.RequiredDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.RequiredDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.RequiredDate); else this.RequiredDate = base.SetDateTimeAsString(ColumnNames.RequiredDate, value); } } public virtual string s_ShippedDate { get { return this.IsColumnNull(ColumnNames.ShippedDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.ShippedDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShippedDate); else this.ShippedDate = base.SetDateTimeAsString(ColumnNames.ShippedDate, value); } } public virtual string s_ShipVia { get { return this.IsColumnNull(ColumnNames.ShipVia) ? string.Empty : base.GetintAsString(ColumnNames.ShipVia); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipVia); else this.ShipVia = base.SetintAsString(ColumnNames.ShipVia, value); } } public virtual string s_Freight { get { return this.IsColumnNull(ColumnNames.Freight) ? string.Empty : base.GetdecimalAsString(ColumnNames.Freight); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Freight); else this.Freight = base.SetdecimalAsString(ColumnNames.Freight, value); } } public virtual string s_ShipName { get { return this.IsColumnNull(ColumnNames.ShipName) ? string.Empty : base.GetstringAsString(ColumnNames.ShipName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipName); else this.ShipName = base.SetstringAsString(ColumnNames.ShipName, value); } } public virtual string s_ShipAddress { get { return this.IsColumnNull(ColumnNames.ShipAddress) ? string.Empty : base.GetstringAsString(ColumnNames.ShipAddress); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipAddress); else this.ShipAddress = base.SetstringAsString(ColumnNames.ShipAddress, value); } } public virtual string s_ShipCity { get { return this.IsColumnNull(ColumnNames.ShipCity) ? string.Empty : base.GetstringAsString(ColumnNames.ShipCity); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipCity); else this.ShipCity = base.SetstringAsString(ColumnNames.ShipCity, value); } } public virtual string s_ShipRegion { get { return this.IsColumnNull(ColumnNames.ShipRegion) ? string.Empty : base.GetstringAsString(ColumnNames.ShipRegion); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipRegion); else this.ShipRegion = base.SetstringAsString(ColumnNames.ShipRegion, value); } } public virtual string s_ShipPostalCode { get { return this.IsColumnNull(ColumnNames.ShipPostalCode) ? string.Empty : base.GetstringAsString(ColumnNames.ShipPostalCode); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipPostalCode); else this.ShipPostalCode = base.SetstringAsString(ColumnNames.ShipPostalCode, value); } } public virtual string s_ShipCountry { get { return this.IsColumnNull(ColumnNames.ShipCountry) ? string.Empty : base.GetstringAsString(ColumnNames.ShipCountry); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ShipCountry); else this.ShipCountry = base.SetstringAsString(ColumnNames.ShipCountry, value); } } #endregion #region Where Clause public class WhereClause { public WhereClause(BusinessEntity entity) { this._entity = entity; } public TearOffWhereParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffWhereParameter(this); } return _tearOff; } } #region WhereParameter TearOff's public class TearOffWhereParameter { public TearOffWhereParameter(WhereClause clause) { this._clause = clause; } public WhereParameter OrderID { get { WhereParameter where = new WhereParameter(ColumnNames.OrderID, Parameters.OrderID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter CustomerID { get { WhereParameter where = new WhereParameter(ColumnNames.CustomerID, Parameters.CustomerID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter EmployeeID { get { WhereParameter where = new WhereParameter(ColumnNames.EmployeeID, Parameters.EmployeeID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter OrderDate { get { WhereParameter where = new WhereParameter(ColumnNames.OrderDate, Parameters.OrderDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter RequiredDate { get { WhereParameter where = new WhereParameter(ColumnNames.RequiredDate, Parameters.RequiredDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShippedDate { get { WhereParameter where = new WhereParameter(ColumnNames.ShippedDate, Parameters.ShippedDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipVia { get { WhereParameter where = new WhereParameter(ColumnNames.ShipVia, Parameters.ShipVia); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Freight { get { WhereParameter where = new WhereParameter(ColumnNames.Freight, Parameters.Freight); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipName { get { WhereParameter where = new WhereParameter(ColumnNames.ShipName, Parameters.ShipName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipAddress { get { WhereParameter where = new WhereParameter(ColumnNames.ShipAddress, Parameters.ShipAddress); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipCity { get { WhereParameter where = new WhereParameter(ColumnNames.ShipCity, Parameters.ShipCity); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipRegion { get { WhereParameter where = new WhereParameter(ColumnNames.ShipRegion, Parameters.ShipRegion); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipPostalCode { get { WhereParameter where = new WhereParameter(ColumnNames.ShipPostalCode, Parameters.ShipPostalCode); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ShipCountry { get { WhereParameter where = new WhereParameter(ColumnNames.ShipCountry, Parameters.ShipCountry); this._clause._entity.Query.AddWhereParameter(where); return where; } } private WhereClause _clause; } #endregion public WhereParameter OrderID { get { if(_OrderID_W == null) { _OrderID_W = TearOff.OrderID; } return _OrderID_W; } } public WhereParameter CustomerID { get { if(_CustomerID_W == null) { _CustomerID_W = TearOff.CustomerID; } return _CustomerID_W; } } public WhereParameter EmployeeID { get { if(_EmployeeID_W == null) { _EmployeeID_W = TearOff.EmployeeID; } return _EmployeeID_W; } } public WhereParameter OrderDate { get { if(_OrderDate_W == null) { _OrderDate_W = TearOff.OrderDate; } return _OrderDate_W; } } public WhereParameter RequiredDate { get { if(_RequiredDate_W == null) { _RequiredDate_W = TearOff.RequiredDate; } return _RequiredDate_W; } } public WhereParameter ShippedDate { get { if(_ShippedDate_W == null) { _ShippedDate_W = TearOff.ShippedDate; } return _ShippedDate_W; } } public WhereParameter ShipVia { get { if(_ShipVia_W == null) { _ShipVia_W = TearOff.ShipVia; } return _ShipVia_W; } } public WhereParameter Freight { get { if(_Freight_W == null) { _Freight_W = TearOff.Freight; } return _Freight_W; } } public WhereParameter ShipName { get { if(_ShipName_W == null) { _ShipName_W = TearOff.ShipName; } return _ShipName_W; } } public WhereParameter ShipAddress { get { if(_ShipAddress_W == null) { _ShipAddress_W = TearOff.ShipAddress; } return _ShipAddress_W; } } public WhereParameter ShipCity { get { if(_ShipCity_W == null) { _ShipCity_W = TearOff.ShipCity; } return _ShipCity_W; } } public WhereParameter ShipRegion { get { if(_ShipRegion_W == null) { _ShipRegion_W = TearOff.ShipRegion; } return _ShipRegion_W; } } public WhereParameter ShipPostalCode { get { if(_ShipPostalCode_W == null) { _ShipPostalCode_W = TearOff.ShipPostalCode; } return _ShipPostalCode_W; } } public WhereParameter ShipCountry { get { if(_ShipCountry_W == null) { _ShipCountry_W = TearOff.ShipCountry; } return _ShipCountry_W; } } private WhereParameter _OrderID_W = null; private WhereParameter _CustomerID_W = null; private WhereParameter _EmployeeID_W = null; private WhereParameter _OrderDate_W = null; private WhereParameter _RequiredDate_W = null; private WhereParameter _ShippedDate_W = null; private WhereParameter _ShipVia_W = null; private WhereParameter _Freight_W = null; private WhereParameter _ShipName_W = null; private WhereParameter _ShipAddress_W = null; private WhereParameter _ShipCity_W = null; private WhereParameter _ShipRegion_W = null; private WhereParameter _ShipPostalCode_W = null; private WhereParameter _ShipCountry_W = null; public void WhereClauseReset() { _OrderID_W = null; _CustomerID_W = null; _EmployeeID_W = null; _OrderDate_W = null; _RequiredDate_W = null; _ShippedDate_W = null; _ShipVia_W = null; _Freight_W = null; _ShipName_W = null; _ShipAddress_W = null; _ShipCity_W = null; _ShipRegion_W = null; _ShipPostalCode_W = null; _ShipCountry_W = null; this._entity.Query.FlushWhereParameters(); } private BusinessEntity _entity; private TearOffWhereParameter _tearOff; } public WhereClause Where { get { if(_whereClause == null) { _whereClause = new WhereClause(this); } return _whereClause; } } private WhereClause _whereClause = null; #endregion #region Aggregate Clause public class AggregateClause { public AggregateClause(BusinessEntity entity) { this._entity = entity; } public TearOffAggregateParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffAggregateParameter(this); } return _tearOff; } } #region AggregateParameter TearOff's public class TearOffAggregateParameter { public TearOffAggregateParameter(AggregateClause clause) { this._clause = clause; } public AggregateParameter OrderID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.OrderID, Parameters.OrderID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter CustomerID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.CustomerID, Parameters.CustomerID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter EmployeeID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.EmployeeID, Parameters.EmployeeID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter OrderDate { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.OrderDate, Parameters.OrderDate); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter RequiredDate { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.RequiredDate, Parameters.RequiredDate); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShippedDate { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShippedDate, Parameters.ShippedDate); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipVia { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipVia, Parameters.ShipVia); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Freight { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Freight, Parameters.Freight); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipName { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipName, Parameters.ShipName); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipAddress { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipAddress, Parameters.ShipAddress); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipCity { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipCity, Parameters.ShipCity); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipRegion { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipRegion, Parameters.ShipRegion); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipPostalCode { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipPostalCode, Parameters.ShipPostalCode); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ShipCountry { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ShipCountry, Parameters.ShipCountry); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } private AggregateClause _clause; } #endregion public AggregateParameter OrderID { get { if(_OrderID_W == null) { _OrderID_W = TearOff.OrderID; } return _OrderID_W; } } public AggregateParameter CustomerID { get { if(_CustomerID_W == null) { _CustomerID_W = TearOff.CustomerID; } return _CustomerID_W; } } public AggregateParameter EmployeeID { get { if(_EmployeeID_W == null) { _EmployeeID_W = TearOff.EmployeeID; } return _EmployeeID_W; } } public AggregateParameter OrderDate { get { if(_OrderDate_W == null) { _OrderDate_W = TearOff.OrderDate; } return _OrderDate_W; } } public AggregateParameter RequiredDate { get { if(_RequiredDate_W == null) { _RequiredDate_W = TearOff.RequiredDate; } return _RequiredDate_W; } } public AggregateParameter ShippedDate { get { if(_ShippedDate_W == null) { _ShippedDate_W = TearOff.ShippedDate; } return _ShippedDate_W; } } public AggregateParameter ShipVia { get { if(_ShipVia_W == null) { _ShipVia_W = TearOff.ShipVia; } return _ShipVia_W; } } public AggregateParameter Freight { get { if(_Freight_W == null) { _Freight_W = TearOff.Freight; } return _Freight_W; } } public AggregateParameter ShipName { get { if(_ShipName_W == null) { _ShipName_W = TearOff.ShipName; } return _ShipName_W; } } public AggregateParameter ShipAddress { get { if(_ShipAddress_W == null) { _ShipAddress_W = TearOff.ShipAddress; } return _ShipAddress_W; } } public AggregateParameter ShipCity { get { if(_ShipCity_W == null) { _ShipCity_W = TearOff.ShipCity; } return _ShipCity_W; } } public AggregateParameter ShipRegion { get { if(_ShipRegion_W == null) { _ShipRegion_W = TearOff.ShipRegion; } return _ShipRegion_W; } } public AggregateParameter ShipPostalCode { get { if(_ShipPostalCode_W == null) { _ShipPostalCode_W = TearOff.ShipPostalCode; } return _ShipPostalCode_W; } } public AggregateParameter ShipCountry { get { if(_ShipCountry_W == null) { _ShipCountry_W = TearOff.ShipCountry; } return _ShipCountry_W; } } private AggregateParameter _OrderID_W = null; private AggregateParameter _CustomerID_W = null; private AggregateParameter _EmployeeID_W = null; private AggregateParameter _OrderDate_W = null; private AggregateParameter _RequiredDate_W = null; private AggregateParameter _ShippedDate_W = null; private AggregateParameter _ShipVia_W = null; private AggregateParameter _Freight_W = null; private AggregateParameter _ShipName_W = null; private AggregateParameter _ShipAddress_W = null; private AggregateParameter _ShipCity_W = null; private AggregateParameter _ShipRegion_W = null; private AggregateParameter _ShipPostalCode_W = null; private AggregateParameter _ShipCountry_W = null; public void AggregateClauseReset() { _OrderID_W = null; _CustomerID_W = null; _EmployeeID_W = null; _OrderDate_W = null; _RequiredDate_W = null; _ShippedDate_W = null; _ShipVia_W = null; _Freight_W = null; _ShipName_W = null; _ShipAddress_W = null; _ShipCity_W = null; _ShipRegion_W = null; _ShipPostalCode_W = null; _ShipCountry_W = null; this._entity.Query.FlushAggregateParameters(); } private BusinessEntity _entity; private TearOffAggregateParameter _tearOff; } public AggregateClause Aggregate { get { if(_aggregateClause == null) { _aggregateClause = new AggregateClause(this); } return _aggregateClause; } } private AggregateClause _aggregateClause = null; #endregion protected override IDbCommand GetInsertCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_OrdersInsert]"; CreateParameters(cmd); SqlParameter p; p = cmd.Parameters[Parameters.OrderID.ParameterName]; p.Direction = ParameterDirection.Output; return cmd; } protected override IDbCommand GetUpdateCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_OrdersUpdate]"; CreateParameters(cmd); return cmd; } protected override IDbCommand GetDeleteCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_OrdersDelete]"; SqlParameter p; p = cmd.Parameters.Add(Parameters.OrderID); p.SourceColumn = ColumnNames.OrderID; p.SourceVersion = DataRowVersion.Current; return cmd; } private IDbCommand CreateParameters(SqlCommand cmd) { SqlParameter p; p = cmd.Parameters.Add(Parameters.OrderID); p.SourceColumn = ColumnNames.OrderID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.CustomerID); p.SourceColumn = ColumnNames.CustomerID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.EmployeeID); p.SourceColumn = ColumnNames.EmployeeID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.OrderDate); p.SourceColumn = ColumnNames.OrderDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.RequiredDate); p.SourceColumn = ColumnNames.RequiredDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShippedDate); p.SourceColumn = ColumnNames.ShippedDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipVia); p.SourceColumn = ColumnNames.ShipVia; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Freight); p.SourceColumn = ColumnNames.Freight; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipName); p.SourceColumn = ColumnNames.ShipName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipAddress); p.SourceColumn = ColumnNames.ShipAddress; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipCity); p.SourceColumn = ColumnNames.ShipCity; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipRegion); p.SourceColumn = ColumnNames.ShipRegion; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipPostalCode); p.SourceColumn = ColumnNames.ShipPostalCode; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ShipCountry); p.SourceColumn = ColumnNames.ShipCountry; p.SourceVersion = DataRowVersion.Current; return cmd; } } }
using GuiLabs.Editor.Blocks; using System.Collections.Generic; namespace GuiLabs.Editor.CSharp { [BlockSerialization("parameters")] public class ParameterListBlock : HContainerBlock, ICSharpBlock, IEnumerable<Parameter>, IReparsable { #region ctor public ParameterListBlock() : this("") { } public ParameterListBlock(string initialText) : base() { List = new ExpressionBlock(initialText); Init(); } private void Init() { LeftBrace = new LabelBlock(OpeningBrace); RightBrace = new LabelBlock(ClosingBrace); LeftBrace.MyControl.Enabled = false; RightBrace.MyControl.Enabled = false; Children.Add(LeftBrace); Children.Add(List); Children.Add(RightBrace); List.CanBeDeletedByUser = false; List.MyTextBox.MinWidth = 2; List.MyControl.Box.MouseSensitivityArea.SetLeftAndRight(List.MyTextBox.StringSize(OpeningBrace).X); } #endregion #region Parentheses public LabelBlock LeftBrace { get; set; } public LabelBlock RightBrace { get; set; } private void UpdateBraces() { LeftBrace.Text = OpeningBrace; RightBrace.Text = ClosingBrace; } public string OpeningBrace { get { switch (TypeOfBraces) { case TypeOfParentheses.Parentheses: return "("; case TypeOfParentheses.SquareBrackets: return "["; case TypeOfParentheses.CurlyBraces: return "{"; default: return ""; } } } public string ClosingBrace { get { switch (TypeOfBraces) { case TypeOfParentheses.Parentheses: return ")"; case TypeOfParentheses.SquareBrackets: return "]"; case TypeOfParentheses.CurlyBraces: return "}"; default: return ""; } } } private TypeOfParentheses mTypeOfBraces = TypeOfParentheses.Parentheses; public TypeOfParentheses TypeOfBraces { get { return mTypeOfBraces; } set { mTypeOfBraces = value; UpdateBraces(); } } public enum TypeOfParentheses { Parentheses, SquareBrackets, CurlyBraces } #endregion #region List private ExpressionBlock mList = new ExpressionBlock(); public ExpressionBlock List { get { return mList; } set { if (mList != null) { mList.MyTextBox.PreviewKeyPress -= MyTextBox_PreviewKeyPress; mList.TextChanged -= MyTextBox_TextChanged; } mList = value; if (mList != null) { mList.MyTextBox.PreviewKeyPress += MyTextBox_PreviewKeyPress; mList.TextChanged += MyTextBox_TextChanged; mList.Context = CompletionContext.MethodParameters; } } } #endregion #region API public Parameter this[string paramName] { get { return Parameters[paramName]; } } #endregion private ParameterList mParameters = new ParameterList(); public ParameterList Parameters { get { return mParameters; } set { mParameters = value; } } #region OnEvents void MyTextBox_TextChanged(GuiLabs.Canvas.Controls.ITextProvider sender, string oldText, string newText) { Reparse(); } void MyTextBox_PreviewKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (List.MyTextBox.CaretIsAtBeginning && e.KeyChar == ')') { Block child = this.FindNextFocusableBlockInChain(); if (child != null) { child.SetFocus(); } e.Handled = true; } } #endregion public void Reparse() { Parameters = LanguageService.ParseParameters(this.List); } #region Text public string Text { get { return List.Text; } set { List.Text = value; } } #endregion #region IEnumerable public IEnumerator<Parameter> GetEnumerator() { if (Parameters != null) { return Parameters.GetEnumerator(); } else { return (new List<Parameter>()).GetEnumerator(); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region AcceptVisitor public void AcceptVisitor(IVisitor Visitor) { Visitor.Visit(this); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; using NPOI.HSSF.Record; /** * Title: Sup Book (EXTERNALBOOK) * Description: A External Workbook Description (Suplemental Book) * Its only a dummy record for making new ExternSheet Record * REFERENCE: 5.38 * @author Libin Roman (Vista Portal LDT. Developer) * @author Andrew C. Oliver (acoliver@apache.org) * */ internal class SupBookRecord : StandardRecord { public const short sid = 0x1AE; private const short SMALL_RECORD_SIZE = 4; private const short TAG_INTERNAL_REFERENCES = 0x0401; private const short TAG_ADD_IN_FUNCTIONS = 0x3A01; private short field_1_number_of_sheets; private String field_2_encoded_url; private String[] field_3_sheet_names; private bool _isAddInFunctions; public static SupBookRecord CreateInternalReferences(short numberOfSheets) { return new SupBookRecord(false, numberOfSheets); } public static SupBookRecord CreateAddInFunctions() { return new SupBookRecord(true, (short)1); } public static SupBookRecord CreateExternalReferences(String url, String[] sheetNames) { return new SupBookRecord(url, sheetNames); } private SupBookRecord(bool IsAddInFuncs, short numberOfSheets) { // else not 'External References' field_1_number_of_sheets = numberOfSheets; field_2_encoded_url = null; field_3_sheet_names = null; _isAddInFunctions = IsAddInFuncs; } public SupBookRecord(String url, String[] sheetNames) { field_1_number_of_sheets = (short)sheetNames.Length; field_2_encoded_url = url; field_3_sheet_names = sheetNames; _isAddInFunctions = false; } /** * Constructs a Extern Sheet record and Sets its fields appropriately. * * @param id id must be 0x16 or an exception will be throw upon validation * @param size the size of the data area of the record * @param data data of the record (should not contain sid/len) */ public SupBookRecord(RecordInputStream in1) { int recLen = in1.Remaining; field_1_number_of_sheets = in1.ReadShort(); if (recLen > SMALL_RECORD_SIZE) { // 5.38.1 External References _isAddInFunctions = false; field_2_encoded_url = in1.ReadString(); String[] sheetNames = new String[field_1_number_of_sheets]; for (int i = 0; i < sheetNames.Length; i++) { sheetNames[i] = in1.ReadString(); } field_3_sheet_names = sheetNames; return; } // else not 'External References' field_2_encoded_url = null; field_3_sheet_names = null; short nextShort = in1.ReadShort(); if (nextShort == TAG_INTERNAL_REFERENCES) { // 5.38.2 'Internal References' _isAddInFunctions = false; } else if (nextShort == TAG_ADD_IN_FUNCTIONS) { // 5.38.3 'Add-In Functions' _isAddInFunctions = true; if (field_1_number_of_sheets != 1) { throw new Exception("Expected 0x0001 for number of sheets field in 'Add-In Functions' but got (" + field_1_number_of_sheets + ")"); } } else { throw new Exception("invalid EXTERNALBOOK code (" + StringUtil.ToHexString(nextShort) + ")"); } } public bool IsExternalReferences { get { return field_3_sheet_names != null; } } public bool IsInternalReferences { get { return field_3_sheet_names == null && !_isAddInFunctions; } } public bool IsAddInFunctions { get { return field_3_sheet_names == null && _isAddInFunctions; } } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append(GetType().Name).Append(" [SUPBOOK "); if (IsExternalReferences) { sb.Append("External References"); sb.Append(" nSheets=").Append(field_1_number_of_sheets); sb.Append(" url=").Append(field_2_encoded_url); } else if (_isAddInFunctions) { sb.Append("Add-In Functions"); } else { sb.Append("Internal References "); sb.Append(" nSheets= ").Append(field_1_number_of_sheets); } return sb.ToString(); } protected override int DataSize { get { if (!IsExternalReferences) { return SMALL_RECORD_SIZE; } int sum = 2; // u16 number of sheets sum += StringUtil.GetEncodedSize(field_2_encoded_url); for (int i = 0; i < field_3_sheet_names.Length; i++) { sum += StringUtil.GetEncodedSize(field_3_sheet_names[i]); } return sum; } } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(field_1_number_of_sheets); if (IsExternalReferences) { StringUtil.WriteUnicodeString(out1, field_2_encoded_url); for (int i = 0; i < field_3_sheet_names.Length; i++) { StringUtil.WriteUnicodeString(out1, field_3_sheet_names[i]); } } else { int field2val = _isAddInFunctions ? TAG_ADD_IN_FUNCTIONS : TAG_INTERNAL_REFERENCES; out1.WriteShort(field2val); } } public short NumberOfSheets { get { return field_1_number_of_sheets; } set { field_1_number_of_sheets = value; } } public override short Sid { get { return sid; } } public String URL { get { String encodedUrl = field_2_encoded_url; switch ((int)encodedUrl[0]) { case 0: // Reference to an empty workbook name return encodedUrl.Substring(1); // will this just be empty string? case 1: // encoded file name return DecodeFileName(encodedUrl); case 2: // Self-referential external reference return encodedUrl.Substring(1); } return encodedUrl; } } private static String DecodeFileName(String encodedUrl) { return encodedUrl.Substring(1); // TODO the following special characters may appear in the rest of the string, and need to get interpreted /* see "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" chVolume 1 chSameVolume 2 chDownDir 3 chUpDir 4 chLongVolume 5 chStartupDir 6 chAltStartupDir 7 chLibDir 8 */ } public String[] SheetNames { get { return (String[])field_3_sheet_names.Clone(); } } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using XenAdmin.Dialogs; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Text.RegularExpressions; namespace XenAdmin.Dialogs { public partial class NameAndConnectionPrompt : XenDialogBase { public NameAndConnectionPrompt() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); foreach (IXenConnection connection in ConnectionsManager.XenConnections) { if (!connection.IsConnected) continue; Pool pool = Helpers.GetPool(connection); if (pool != null) { comboBox.Items.Add(pool); continue; } Host master = Helpers.GetMaster(connection); if (master != null) { comboBox.Items.Add(master); continue; } } comboBox.Sorted = true; if (comboBox.Items.Count > 0) { // check to see if the user is readonly on connections, try and choose a sensible default int nonReadOnlyIndex = -1; for (int i = 0; i < comboBox.Items.Count; i++) { IXenObject xo = comboBox.Items[i] as IXenObject; if (xo != null && (xo.Connection.Session.IsLocalSuperuser || !Helpers.MidnightRideOrGreater(xo.Connection) || !XenAdmin.Commands.CrossConnectionCommand.IsReadOnly(xo.Connection))) { nonReadOnlyIndex = i; break; } } if (nonReadOnlyIndex == -1) comboBox.SelectedIndex = 0; else comboBox.SelectedIndex = nonReadOnlyIndex; } UpdateOK(); } public String PromptedName { get { return textBox.Text; } set { textBox.Text = value; } } public string OKText { set { okButton.Text = value; } } private string helpID = null; internal string HelpID { set { helpID = value; } } internal override string HelpName { get { return helpID ?? base.HelpName; } } public IXenConnection Connection { get { IXenObject o = comboBox.SelectedItem as IXenObject; if (o == null) return null; return o.Connection; } } private void textBox1_TextChanged(object sender, EventArgs e) { UpdateOK(); } private Regex invalid_folder = new Regex("^[ /]+$"); private void UpdateOK() { okButton.Enabled = !String.IsNullOrEmpty(textBox.Text.Trim()) && !invalid_folder.IsMatch(textBox.Text); } private const int PADDING = 1; private void comboBox_DrawItem(object sender, DrawItemEventArgs e) { ComboBox comboBox = sender as ComboBox; if (comboBox == null) return; if (e.Index < 0 || e.Index >= comboBox.Items.Count) return; Graphics g = e.Graphics; e.DrawBackground(); IXenObject o = comboBox.Items[e.Index] as IXenObject; if (o == null) return; Image image = Images.GetImage16For(o); Rectangle bounds = e.Bounds; if (image != null) g.DrawImage(image, bounds.X + PADDING, bounds.Y + PADDING, bounds.Height - 2 * PADDING, bounds.Height - 2 * PADDING); String name = Helpers.GetName(o).Ellipsise(50); e.DrawFocusRectangle(); if (name != null) using (Brush brush = new SolidBrush(e.ForeColor)) g.DrawString(name, Program.DefaultFont, brush, new Rectangle(bounds.X + bounds.Height, bounds.Y, bounds.Width - bounds.Height, bounds.Height)); } private void okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Commanding.Modules.Order.Properties; using Prism.Commands; using Prism.Events; namespace Commanding.Modules.Order.PresentationModels { /// <summary> /// Presentation model that represents an Order entity. /// </summary> public partial class OrderViewModel : INotifyPropertyChanged, IDataErrorInfo { private readonly IDictionary<string, string> errors = new Dictionary<string, string>(); private readonly Services.Order _order; public OrderViewModel(Services.Order order) { _order = order; //TODO: 01 - Each Order defines a Save command. this.SaveOrderCommand = new DelegateCommand<object>( this.Save, this.CanSave ); // Track all property changes so we can validate. this.PropertyChanged += this.OnPropertyChanged; this.Validate(); } #region Order Properties - OrderName, DeliveryDate, Quantity, Price, Shipping, Total public string OrderName { get { return _order.Name; } set { _order.Name = value; NotifyPropertyChanged( "OrderName" ); } } public DateTime DeliveryDate { get { return _order.DeliveryDate; } set { if ( _order.DeliveryDate != value ) { _order.DeliveryDate = value; this.NotifyPropertyChanged( "DeliveryDate" ); } } } public int? Quantity { get { return _order.Quantity; } set { if ( _order.Quantity != value ) { _order.Quantity = value; this.NotifyPropertyChanged( "Quantity" ); } } } public decimal? Price { get { return _order.Price; } set { if ( _order.Price != value ) { _order.Price = value; this.NotifyPropertyChanged( "Price" ); } } } public decimal? Shipping { get { return _order.Shipping; } set { if ( _order.Shipping != value ) { _order.Shipping = value; this.NotifyPropertyChanged( "Shipping" ); } } } public decimal Total { get { if (this.Price != null && this.Quantity != null) { return (this.Price.Value * this.Quantity.Value) + (this.Shipping ?? 0); } return 0; } } #endregion private void OnPropertyChanged( object sender, PropertyChangedEventArgs e ) { // Total is a calculated property based on price, quantity and shipping cost. // If any of these properties change, then notify the view. string propertyName = e.PropertyName; if ( propertyName == "Price" || propertyName == "Quantity" || propertyName == "Shipping" ) { this.NotifyPropertyChanged( "Total" ); } // Validate and update the enabled status of the SaveOrder // command whenever any property changes. this.Validate(); this.SaveOrderCommand.RaiseCanExecuteChanged(); } #region SaveOrder Command public event EventHandler<DataEventArgs<OrderViewModel>> Saved; public DelegateCommand<object> SaveOrderCommand { get; private set; } private bool CanSave( object arg ) { //TODO: 02 - The Order Save command is enabled only when all order data is valid. // Can only save when there are no errors and // when the order quantity is greater than zero. return this.errors.Count == 0 && this.Quantity > 0; } private void Save( object obj ) { // Save the order here. Console.WriteLine( String.Format( CultureInfo.InvariantCulture, "{0} saved.", this.OrderName ) ); // Notify that the order was saved. this.OnSaved(new DataEventArgs<OrderViewModel>(this)); } private void OnSaved(DataEventArgs<OrderViewModel> e) { EventHandler<DataEventArgs<OrderViewModel>> savedHandler = this.Saved; if ( savedHandler != null ) { savedHandler( this, e ); } } #endregion #region IDataErrorInfo Interface public string this[ string columnName ] { get { if ( this.errors.ContainsKey( columnName ) ) { return this.errors[columnName]; } return null; } set { this.errors[columnName] = value; } } public string Error { get { // Not implemented because we are not consuming it in this quick start. // Instead, we are displaying error messages at the item level. throw new NotImplementedException(); } } #endregion private void Validate() { if ( this.Price == null || this.Price <= 0 ) { this["Price"] = Resources.InvalidPriceRange; } else { this.ClearError("Price"); } if ( this.Quantity == null || this.Quantity <= 0 ) { this["Quantity"] = Resources.InvalidQuantityRange; } else { this.ClearError("Quantity"); } } private void ClearError( string columnName ) { if ( this.errors.ContainsKey( columnName ) ) { this.errors.Remove( columnName ); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged( string propertyName ) { if ( this.PropertyChanged != null ) { this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) ); } } #endregion } }
namespace PokerTell.PokerHand.Tests.Services { using System; using Infrastructure.Enumerations.PokerHand; using Infrastructure.Interfaces.PokerHand; using Infrastructure.Services; using NUnit.Framework; using PokerTell.PokerHand.Analyzation; using PokerTell.PokerHand.Aquisition; using PokerTell.PokerHand.Services; using UnitTests; [TestFixture] public class PokerActionConverterTests : TestWithLog { #region Constants and Fields PokerActionConverter _converter; #endregion #region Public Methods [SetUp] public void _Init() { _converter = new PokerActionConverter(new Constructor<IConvertedPokerAction>(() => new ConvertedPokerAction())); } [Test] public void Convert_Bet_SetsToCallToRatio() { const ActionTypes actionType = ActionTypes.B; double toCall = 0; const double ratio = 1.0; const double expectedToCall = ratio; double somePot = 3.0; const double someTotalPot = 4.0; var aquiredAction = new AquiredPokerAction(actionType, ratio); _converter.Convert(aquiredAction, ref somePot, ref toCall, someTotalPot); Assert.That(toCall, Is.EqualTo(expectedToCall)); } [Test] [Sequential] public void Convert_CallBet_SetsConvertedRatioToAquiredRatioDividedByPot( [Values(ActionTypes.C, ActionTypes.B)] ActionTypes actionType) { const double aquiredRatio = 1.0; const double origPot = 2.0; const double expectedRatio = aquiredRatio / origPot; double pot = origPot; double someToCall = 0; const double someTotalPot = 3.0; var aquiredAction = new AquiredPokerAction(actionType, aquiredRatio); var convertedAction = _converter.Convert(aquiredAction, ref pot, ref someToCall, someTotalPot); Assert.That(convertedAction.Ratio, Is.EqualTo(expectedRatio)); } [Test] [Sequential] public void Convert_CallBetRaise_AddsRatioToPot( [Values(ActionTypes.C, ActionTypes.B, ActionTypes.R)] ActionTypes actionType) { double pot = 2.0; const double ratio = 1.0; double expectedPot = pot + ratio; double someToCall = 3.0; const double someTotalPot = 4.0; var aquiredAction = new AquiredPokerAction(actionType, ratio); _converter.Convert(aquiredAction, ref pot, ref someToCall, someTotalPot); Assert.That(pot, Is.EqualTo(expectedPot)); } [Test] [Sequential] public void Convert_FoldCheckAllin_SetsConvertedRatioToAquiredRatio( [Values(ActionTypes.F, ActionTypes.X, ActionTypes.A)] ActionTypes actionType) { // For these actions the ratio is irelevant, but still should not be changed const double aquiredRatio = 1.0; double somePot = 0; double someToCall = 1.2; const double someTotalPot = 2.0; var aquiredAction = new AquiredPokerAction(actionType, aquiredRatio); var convertedAction = _converter.Convert( aquiredAction, ref somePot, ref someToCall, someTotalPot); Assert.That(convertedAction.Ratio, Is.EqualTo(aquiredRatio)); } [Test] [Sequential] public void Convert_FoldCheckAllinWin_DoesntChangePot( [Values(ActionTypes.F, ActionTypes.X, ActionTypes.A, ActionTypes.W)] ActionTypes actionType) { const double originalValue = 3.0; double pot = originalValue; double someToCall = 1.0; const double someTotalPot = 4.0; const double someRatio = 1.5; var aquiredAction = new AquiredPokerAction(actionType, someRatio); _converter.Convert(aquiredAction, ref pot, ref someToCall, someTotalPot); Assert.That(pot, Is.EqualTo(originalValue)); } [Test] [Sequential] public void Convert_FoldCheckCallAllinWin_DoesntChangeToCall( [Values(ActionTypes.F, ActionTypes.X, ActionTypes.C, ActionTypes.A, ActionTypes.W)] ActionTypes actionType) { const double originalValue = 1.5; double toCall = originalValue; double somePot = 3.0; const double someTotalPot = 4.0; const double someRatio = 1.0; var aquiredAction = new AquiredPokerAction(actionType, someRatio); _converter.Convert(aquiredAction, ref somePot, ref toCall, someTotalPot); Assert.That(toCall, Is.EqualTo(originalValue)); } [Test] [Sequential] public void Convert_InValidActionType_ThrowsArgumentException( [Values(ActionTypes.E, ActionTypes.N, ActionTypes.P, ActionTypes.U)] ActionTypes actionType) { double somePot = 3.0; double someToCall = 1.5; const double someTotalPot = 4.0; const double someRatio = 1.0; var aquiredAction = new AquiredPokerAction(actionType, someRatio); TestDelegate invokeConvert = () => _converter.Convert(aquiredAction, ref somePot, ref someToCall, someTotalPot); Assert.Throws<ArgumentException>(invokeConvert); } [Test] [Sequential] public void Convert_Raise_SetsConvertedRatioToAquiredRatioDividedByToCall() { const ActionTypes actionType = ActionTypes.R; const double aquiredRatio = 2.0; double toCall = 1.5; double expectedRatio = aquiredRatio / toCall; double somePot = 1.0; const double someTotalPot = 2.0; var aquiredAction = new AquiredPokerAction(actionType, aquiredRatio); IConvertedPokerAction convertedAction = _converter.Convert( aquiredAction, ref somePot, ref toCall, someTotalPot); Assert.That(convertedAction.Ratio, Is.EqualTo(expectedRatio)); } [Test] public void Convert_RaiseToCallIsGreaterThanRatio_DoesntChangeToCall() { const ActionTypes actionType = ActionTypes.R; const double originalValue = 2.0; double toCall = originalValue; const double ratio = 1.0; double somePot = 3.0; const double someTotalPot = 4.0; var aquiredAction = new AquiredPokerAction(actionType, ratio); _converter.Convert(aquiredAction, ref somePot, ref toCall, someTotalPot); Assert.That(toCall, Is.EqualTo(originalValue)); } [Test] public void Convert_RaiseToCallIsSmallerThanRatio_SetsToCallToRatio() { const ActionTypes actionType = ActionTypes.R; double toCall = 0; const double ratio = 1.0; const double expectedToCall = ratio; double somePot = 3.0; const double someTotalPot = 4.0; var aquiredAction = new AquiredPokerAction(actionType, ratio); _converter.Convert(aquiredAction, ref somePot, ref toCall, someTotalPot); Assert.That(toCall, Is.EqualTo(expectedToCall)); } [Test] [Sequential] public void Convert_ValidActionType_ReturnsConvertedActionWithSameActionType( [Values(ActionTypes.A, ActionTypes.B, ActionTypes.C, ActionTypes.F, ActionTypes.R, ActionTypes.W, ActionTypes.X)] ActionTypes actionType) { double somePot = 3.0; double someToCall = 1.5; const double someTotalPot = 4.0; const double someRatio = 1.0; var aquiredAction = new AquiredPokerAction(actionType, someRatio); ActionTypes expectedActionType = actionType; IConvertedPokerAction convertedAction = _converter.Convert( aquiredAction, ref somePot, ref someToCall, someTotalPot); Assert.That(convertedAction.What, Is.EqualTo(expectedActionType)); } [Test] [Sequential] public void Convert_Win_SetsConvertedRatioToAquiredRatioDividedByTotalPot() { const ActionTypes actionType = ActionTypes.W; const double aquiredRatio = 2.0; const double totalPot = 4.0; const double expectedRatio = aquiredRatio / totalPot; double somePot = 1.0; double someToCall = 1.5; var aquiredAction = new AquiredPokerAction(actionType, aquiredRatio); IConvertedPokerAction convertedAction = _converter.Convert( aquiredAction, ref somePot, ref someToCall, totalPot); Assert.That(convertedAction.Ratio, Is.EqualTo(expectedRatio)); } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using System.Net; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Services; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Grid.UserServer.Modules { public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID, ulong regionhandle, float positionX, float positionY, float positionZ, string firstname, string lastname); public class RegionLoginFailure { private const int FAIL_LIMIT = 10; private const int FAIL_EXPIRY = 5 * 60; // in seconds (5 minutes) private uint _lastFail; private int _failures; public int Count { get { return _failures; } } // Allocating one of these implies the first failure. public RegionLoginFailure() { _lastFail = 0; _failures = 0; AddFailure(); } // Increment the failure count and update the timestamp. public void AddFailure() { _failures++; _lastFail = (uint)Environment.TickCount; } // Returns true if fail count exceeds threshold public bool IsFailed() { return (_failures >= FAIL_LIMIT); } // Returns true if more than N minutes has passed since the last failure. public bool IsExpired() { return (((uint)Environment.TickCount - _lastFail) > (FAIL_EXPIRY*1000)); } // Returns true if the count is exceeded and not expired. public bool IsActive() { return IsFailed() && !IsExpired(); } } /// <summary> /// Login service used in grid mode. /// </summary> public class UserLoginService : LoginService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event UserLoggedInAtLocation OnUserLoggedInAtLocation; private UserLoggedInAtLocation handlerUserLoggedInAtLocation; public UserConfig m_config; private readonly IRegionProfileRouter m_regionProfileService; protected BaseHttpServer m_httpServer; private Dictionary<string, RegionLoginFailure> _LastRegionFailure = new Dictionary<string, RegionLoginFailure>(); public UserLoginService( OpenSim.Framework.Communications.UserProfileManager userManager, LibraryRootFolder libraryRootFolder, string mapServerURI, string profileServerURI, UserConfig config, string welcomeMess, IRegionProfileRouter regionProfileService) : base(userManager, libraryRootFolder, welcomeMess, mapServerURI, profileServerURI) { m_config = config; m_defaultHomeX = m_config.DefaultX; m_defaultHomeY = m_config.DefaultY; m_regionProfileService = regionProfileService; } public void RegisterHandlers(BaseHttpServer httpServer, bool registerOpenIDHandlers) { m_currencySymbol = m_config.CurrencySymbol; m_httpServer = httpServer; m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin); m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod); m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams); m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession, false); // New Style m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), XmlRpcLoginMethod)); m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("set_login_params"), XmlRPCSetLoginParams)); m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("check_auth_session"), XmlRPCCheckAuthSession)); if (registerOpenIDHandlers) { // Handler for OpenID avatar identity pages m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this)); // Handlers for the OpenID endpoint server m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this)); m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this)); } } public void setloginlevel(int level) { m_minLoginLevel = level; m_log.InfoFormat("[GRID]: Login Level set to {0} ", level); } public void setwelcometext(string text) { m_welcomeMessage = text; m_log.InfoFormat("[GRID]: Login text set to {0} ", text); } public override void LogOffUser(UserProfileData theUser, string message) { RegionProfileData SimInfo; try { SimInfo = m_regionProfileService.RequestSimProfileData( theUser.CurrentAgent.Handle, m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); if (SimInfo == null) { m_log.Error("[GRID]: Region user was in isn't currently logged in"); return; } } catch (Exception) { m_log.Error("[GRID]: Unable to look up region to log user off"); return; } // Prepare notification Hashtable SimParams = new Hashtable(); SimParams["agent_id"] = theUser.ID.ToString(); SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); SimParams["region_secret2"] = SimInfo.regionSecret; //m_log.Info(SimInfo.regionSecret); SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); SimParams["message"] = message; ArrayList SendParams = new ArrayList(); SendParams.Add(SimParams); m_log.InfoFormat( "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, theUser.FirstName + " " + theUser.SurName); try { string methodName = "logoff_user"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000); if (GridResp.IsFault) { m_log.ErrorFormat( "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); } } catch (Exception) { m_log.Error("[LOGIN]: Error telling region to logout user!"); } // Prepare notification SimParams = new Hashtable(); SimParams["agent_id"] = theUser.ID.ToString(); SimParams["region_secret"] = SimInfo.regionSecret; //m_log.Info(SimInfo.regionSecret); SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); SimParams["message"] = message; SendParams = new ArrayList(); SendParams.Add(SimParams); m_log.InfoFormat( "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, theUser.FirstName + " " + theUser.SurName); try { string methodName = "logoff_user"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000); if (GridResp.IsFault) { m_log.ErrorFormat( "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); } } catch (Exception) { m_log.Error("[LOGIN]: Error telling region to logout user!"); } //base.LogOffUser(theUser); } protected override RegionInfo RequestClosestRegion(string region) { RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(region, m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); if (profileData != null) { return profileData.ToRegionInfo(); } else { return null; } } protected override RegionInfo GetRegionInfo(ulong homeRegionHandle) { RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionHandle, m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); if (profileData != null) { return profileData.ToRegionInfo(); } else { return null; } } protected override RegionInfo GetRegionInfo(UUID homeRegionId) { RegionProfileData profileData = m_regionProfileService.RequestSimProfileData(homeRegionId, m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); if (profileData != null) { return profileData.ToRegionInfo(); } else { return null; } } protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, string clientVersion) { return PrepareLoginToRegion(RegionProfileData.FromRegionInfo(regionInfo), user, response, clientVersion); } /// <summary> /// Prepare a login to the given region. This involves both telling the region to expect a connection /// and appropriately customising the response to the user. /// </summary> /// <param name="regionInfo"></param> /// <param name="user"></param> /// <param name="response"></param> /// <returns>true if the region was successfully contacted, false otherwise</returns> private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response, string clientVersion) { string regionName = regionInfo.regionName; bool regionSuccess = false; // region communication result bool userSuccess = true; // user login succeeded result, for now try { lock (_LastRegionFailure) { if (_LastRegionFailure.ContainsKey(regionName)) { // region failed previously RegionLoginFailure failure = _LastRegionFailure[regionName]; if (failure.IsExpired()) { // failure has expired, retry this region again _LastRegionFailure.Remove(regionName); // m_log.WarnFormat("[LOGIN]: Region '{0}' was previously down, retrying.", regionName); } else { if (failure.IsFailed()) { // m_log.WarnFormat("[LOGIN]: Region '{0}' was recently down, skipping.", regionName); return false; // within 5 minutes, don't repeat attempt } // m_log.WarnFormat("[LOGIN]: Region '{0}' was recently down but under threshold, retrying.", regionName); } } } response.SimAddress = regionInfo.OutsideIpOrResolvedHostname; response.SimPort = regionInfo.serverPort; response.RegionX = regionInfo.regionLocX; response.RegionY = regionInfo.regionLocY; string capsPath = CapsUtil.GetRandomCapsObjectPath(); response.SeedCapability = CapsUtil.GetFullCapsSeedURL(regionInfo.httpServerURI, capsPath); // Notify the target of an incoming user m_log.InfoFormat( "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection", regionInfo.regionName, response.RegionX, response.RegionY, response.SeedCapability); // Update agent with target sim user.CurrentAgent.Region = regionInfo.UUID; user.CurrentAgent.Handle = regionInfo.regionHandle; // Prepare notification Hashtable loginParams = new Hashtable(); loginParams["session_id"] = user.CurrentAgent.SessionID.ToString(); loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString(); loginParams["firstname"] = user.FirstName; loginParams["lastname"] = user.SurName; loginParams["agent_id"] = user.ID.ToString(); loginParams["circuit_code"] = (Int32)Convert.ToUInt32(response.CircuitCode); loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString(); loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString(); loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString(); loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString(); loginParams["caps_path"] = capsPath; loginParams["client_version"] = clientVersion; // Get appearance AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID); if (appearance != null) { loginParams["appearance"] = appearance.ToHashTable(); m_log.DebugFormat("[LOGIN]: Found appearance version {0} for {1} {2}", appearance.Serial, user.FirstName, user.SurName); } else { m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); appearance = new AvatarAppearance(user.ID); } // Tell the client the COF version so it can use cached appearance if it matches. response.CofVersion = appearance.Serial.ToString(); loginParams["cof_version"] = response.CofVersion; ArrayList SendParams = new ArrayList(); SendParams.Add(loginParams); SendParams.Add(m_config.GridSendKey); // Send const string METHOD_NAME = "expect_user"; XmlRpcRequest GridReq = new XmlRpcRequest(METHOD_NAME, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(regionInfo.httpServerURI, METHOD_NAME), 6000); if (!GridResp.IsFault) { // We've received a successful response from the region. // From the perspective of communicating with the region, we were able to get a response. // Do not mark the region down if it responds, even if it doesn't allow the user into the region. regionSuccess = true; if (GridResp.Value != null) { Hashtable resp = (Hashtable)GridResp.Value; if (resp.ContainsKey("success")) { if ((string)resp["success"] == "FALSE") { // Tell the user their login failed. userSuccess = false; } } if (!userSuccess) { if (resp.ContainsKey("reason")) { response.ErrorMessage = resp["reason"].ToString(); } } } if (userSuccess) { handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation; if (handlerUserLoggedInAtLocation != null) { handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID, user.CurrentAgent.Region, user.CurrentAgent.Handle, user.CurrentAgent.Position.X, user.CurrentAgent.Position.Y, user.CurrentAgent.Position.Z, user.FirstName, user.SurName); } } else { m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to accept a login from {0} at this time.", user.Name); } } else { m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode); } } catch (Exception e) { m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e); } lock (_LastRegionFailure) { if (_LastRegionFailure.ContainsKey(regionName)) { RegionLoginFailure failure = _LastRegionFailure[regionName]; if (regionSuccess) { // Success, so if we've been storing this as a failed region, remove that from the failed list. m_log.WarnFormat("[LOGIN]: Region '{0}' recently down, is available again.", regionName); _LastRegionFailure.Remove(regionName); } else { // Region not available, update cache with incremented count. failure.AddFailure(); // m_log.WarnFormat("[LOGIN]: Region '{0}' is still down ({1}).", regionName, failure.Count); } } else { if (!regionSuccess) { // Region not available, cache that temporarily. m_log.WarnFormat("[LOGIN]: Region '{0}' is down, marking.", regionName); _LastRegionFailure[regionName] = new RegionLoginFailure(); } } } return regionSuccess && userSuccess; } public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; Hashtable responseData = new Hashtable(); UUID uid; string pass = requestData["password"].ToString(); if (!UUID.TryParse((string)requestData["avatar_uuid"], out uid)) { responseData["error"] = "No authorization"; response.Value = responseData; return response; } userProfile = m_userManager.GetUserProfile(uid); if (userProfile == null || (!AuthenticateUser(userProfile, pass)) || userProfile.GodLevel < 200) { responseData["error"] = "No authorization"; response.Value = responseData; return response; } if (requestData.ContainsKey("login_level")) { m_minLoginLevel = Convert.ToInt32(requestData["login_level"]); } if (requestData.ContainsKey("login_motd")) { m_welcomeMessage = requestData["login_motd"].ToString(); } response.Value = responseData; return response; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; namespace OpenSim.Server.Handlers.Asset { public class AssetServiceConnector : ServiceConnector { private IAssetService m_AssetService; private string m_ConfigName = "AssetService"; public AssetServiceConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); string assetService = serverConfig.GetString("LocalServiceModule", String.Empty); if (assetService == String.Empty) throw new Exception("No LocalServiceModule in config file"); Object[] args = new Object[] { config, m_ConfigName }; m_AssetService = ServerUtils.LoadPlugin<IAssetService>(assetService, args); if (m_AssetService == null) throw new Exception(String.Format("Failed to load AssetService from {0}; config is {1}", assetService, m_ConfigName)); bool allowDelete = serverConfig.GetBoolean("AllowRemoteDelete", false); bool allowDeleteAllTypes = serverConfig.GetBoolean("AllowRemoteDeleteAllTypes", false); AllowedRemoteDeleteTypes allowedRemoteDeleteTypes; if (!allowDelete) { allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.None; } else { if (allowDeleteAllTypes) allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.All; else allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.MapTile; } server.AddStreamHandler(new AssetServerGetHandler(m_AssetService)); server.AddStreamHandler(new AssetServerPostHandler(m_AssetService)); server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowedRemoteDeleteTypes)); MainConsole.Instance.Commands.AddCommand("Assets", false, "show asset", "show asset <ID>", "Show asset information", HandleShowAsset); MainConsole.Instance.Commands.AddCommand("Assets", false, "delete asset", "delete asset <ID>", "Delete asset from database", HandleDeleteAsset); MainConsole.Instance.Commands.AddCommand("Assets", false, "dump asset", "dump asset <ID>", "Dump asset to a file", "The filename is the same as the ID given.", HandleDumpAsset); } void HandleDeleteAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: delete asset <ID>"); return; } AssetBase asset = m_AssetService.Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } m_AssetService.Delete(args[2]); //MainConsole.Instance.Output("Asset deleted"); // TODO: Implement this MainConsole.Instance.Output("Asset deletion not supported by database"); } void HandleDumpAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Usage is dump asset <ID>"); return; } UUID assetId; string rawAssetId = args[2]; if (!UUID.TryParse(rawAssetId, out assetId)) { MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId); return; } AssetBase asset = m_AssetService.Get(assetId.ToString()); if (asset == null) { MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId); return; } string fileName = rawAssetId; if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, fileName)) return; using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write(asset.Data); } } MainConsole.Instance.OutputFormat("Asset dumped to file {0}", fileName); } void HandleShowAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: show asset <ID>"); return; } AssetBase asset = m_AssetService.Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } int i; MainConsole.Instance.OutputFormat("Name: {0}", asset.Name); MainConsole.Instance.OutputFormat("Description: {0}", asset.Description); MainConsole.Instance.OutputFormat("Type: {0} (type number = {1})", (AssetType)asset.Type, asset.Type); MainConsole.Instance.OutputFormat("Content-type: {0}", asset.Metadata.ContentType); MainConsole.Instance.OutputFormat("Size: {0} bytes", asset.Data.Length); MainConsole.Instance.OutputFormat("Temporary: {0}", asset.Temporary ? "yes" : "no"); MainConsole.Instance.OutputFormat("Flags: {0}", asset.Metadata.Flags); for (i = 0 ; i < 5 ; i++) { int off = i * 16; if (asset.Data.Length <= off) break; int len = 16; if (asset.Data.Length < off + len) len = asset.Data.Length - off; byte[] line = new byte[len]; Array.Copy(asset.Data, off, line, 0, len); string text = BitConverter.ToString(line); MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text)); } } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.PostProcessing { public sealed class CurveEditor { #region Enums enum EditMode { None, Moving, TangentEdit } enum Tangent { In, Out } #endregion #region Structs public struct Settings { public Rect bounds; public RectOffset padding; public Color selectionColor; public float curvePickingDistance; public float keyTimeClampingDistance; public static Settings defaultSettings { get { return new Settings { bounds = new Rect(0f, 0f, 1f, 1f), padding = new RectOffset(10, 10, 10, 10), selectionColor = Color.yellow, curvePickingDistance = 6f, keyTimeClampingDistance = 1e-4f }; } } } public struct CurveState { public bool visible; public bool editable; public uint minPointCount; public float zeroKeyConstantValue; public Color color; public float width; public float handleWidth; public bool showNonEditableHandles; public bool onlyShowHandlesOnSelection; public bool loopInBounds; public static CurveState defaultState { get { return new CurveState { visible = true, editable = true, minPointCount = 2, zeroKeyConstantValue = 0f, color = Color.white, width = 2f, handleWidth = 2f, showNonEditableHandles = true, onlyShowHandlesOnSelection = false, loopInBounds = false }; } } } public struct Selection { public SerializedProperty curve; public int keyframeIndex; public Keyframe? keyframe; public Selection(SerializedProperty curve, int keyframeIndex, Keyframe? keyframe) { this.curve = curve; this.keyframeIndex = keyframeIndex; this.keyframe = keyframe; } } #endregion #region Fields & properties public Settings settings { get; private set; } Dictionary<SerializedProperty, CurveState> m_Curves; Rect m_CurveArea; SerializedProperty m_SelectedCurve; int m_SelectedKeyframeIndex = -1; EditMode m_EditMode = EditMode.None; Tangent m_TangentEditMode; bool m_Dirty; #endregion #region Constructors & destructors public CurveEditor() : this(Settings.defaultSettings) {} public CurveEditor(Settings settings) { this.settings = settings; m_Curves = new Dictionary<SerializedProperty, CurveState>(); } #endregion #region Public API public void Add(params SerializedProperty[] curves) { foreach (var curve in curves) Add(curve, CurveState.defaultState); } public void Add(SerializedProperty curve) { Add(curve, CurveState.defaultState); } public void Add(SerializedProperty curve, CurveState state) { // Make sure the property is in fact an AnimationCurve var animCurve = curve.animationCurveValue; if (animCurve == null) throw new ArgumentException("curve"); if (m_Curves.ContainsKey(curve)) Debug.LogWarning("Curve has already been added to the editor"); m_Curves.Add(curve, state); } public void Remove(SerializedProperty curve) { m_Curves.Remove(curve); } public void RemoveAll() { m_Curves.Clear(); } public CurveState GetCurveState(SerializedProperty curve) { CurveState state; if (!m_Curves.TryGetValue(curve, out state)) throw new KeyNotFoundException("curve"); return state; } public void SetCurveState(SerializedProperty curve, CurveState state) { if (!m_Curves.ContainsKey(curve)) throw new KeyNotFoundException("curve"); m_Curves[curve] = state; } public Selection GetSelection() { Keyframe? key = null; if (m_SelectedKeyframeIndex > -1) { var curve = m_SelectedCurve.animationCurveValue; if (m_SelectedKeyframeIndex >= curve.length) m_SelectedKeyframeIndex = -1; else key = curve[m_SelectedKeyframeIndex]; } return new Selection(m_SelectedCurve, m_SelectedKeyframeIndex, key); } public void SetKeyframe(SerializedProperty curve, int keyframeIndex, Keyframe keyframe) { var animCurve = curve.animationCurveValue; SetKeyframe(animCurve, keyframeIndex, keyframe); SaveCurve(curve, animCurve); } public bool OnGUI(Rect rect) { m_Dirty = false; GUI.BeginClip(rect); { var area = new Rect(Vector2.zero, rect.size); m_CurveArea = settings.padding.Remove(area); foreach (var curve in m_Curves) OnCurveGUI(area, curve.Key, curve.Value); OnGeneralUI(area); } GUI.EndClip(); return m_Dirty; } #endregion #region UI & events void OnCurveGUI(Rect rect, SerializedProperty curve, CurveState state) { // Discard invisible curves if (!state.visible) return; var animCurve = curve.animationCurveValue; var keys = animCurve.keys; var length = keys.Length; // Curve drawing // Slightly dim non-editable curves var color = state.color; if (!state.editable) color.a *= 0.5f; Handles.color = color; var bounds = settings.bounds; if (length == 0) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, state.zeroKeyConstantValue)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, state.zeroKeyConstantValue)); Handles.DrawAAPolyLine(state.width, p1, p2); } else if (length == 1) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[0].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } else { var prevKey = keys[0]; for (int k = 1; k < length; k++) { var key = keys[k]; var pts = BezierSegment(prevKey, key); if (float.IsInfinity(prevKey.outTangent) || float.IsInfinity(key.inTangent)) { var s = HardSegment(prevKey, key); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); prevKey = key; } // Curve extents & loops if (keys[0].time > bounds.xMin) { if (state.loopInBounds) { var p1 = keys[length - 1]; p1.time -= settings.bounds.width; var p2 = keys[0]; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } else { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(keys[0]); Handles.DrawAAPolyLine(state.width, p1, p2); } } if (keys[length - 1].time < bounds.xMax) { if (state.loopInBounds) { var p1 = keys[length - 1]; var p2 = keys[0]; p2.time += settings.bounds.width; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } else { var p1 = CurveToCanvas(keys[length - 1]); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[length - 1].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } } } // Make sure selection is correct (undo can break it) bool isCurrentlySelectedCurve = curve == m_SelectedCurve; if (isCurrentlySelectedCurve && m_SelectedKeyframeIndex >= length) m_SelectedKeyframeIndex = -1; // Handles & keys for (int k = 0; k < length; k++) { bool isCurrentlySelectedKeyframe = k == m_SelectedKeyframeIndex; var e = Event.current; var pos = CurveToCanvas(keys[k]); var hitRect = new Rect(pos.x - 8f, pos.y - 8f, 16f, 16f); var offset = isCurrentlySelectedCurve ? new RectOffset(5, 5, 5, 5) : new RectOffset(6, 6, 6, 6); var outTangent = pos + CurveTangentToCanvas(keys[k].outTangent).normalized * 40f; var inTangent = pos - CurveTangentToCanvas(keys[k].inTangent).normalized * 40f; var inTangentHitRect = new Rect(inTangent.x - 7f, inTangent.y - 7f, 14f, 14f); var outTangentHitrect = new Rect(outTangent.x - 7f, outTangent.y - 7f, 14f, 14f); // Draw if (state.showNonEditableHandles) { if (e.type == EventType.repaint) { var selectedColor = (isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) ? settings.selectionColor : state.color; // Keyframe EditorGUI.DrawRect(offset.Remove(hitRect), selectedColor); // Tangents if (isCurrentlySelectedCurve && (!state.onlyShowHandlesOnSelection || (state.onlyShowHandlesOnSelection && isCurrentlySelectedKeyframe))) { Handles.color = selectedColor; if (k > 0 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, inTangent); EditorGUI.DrawRect(offset.Remove(inTangentHitRect), selectedColor); } if (k < length - 1 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, outTangent); EditorGUI.DrawRect(offset.Remove(outTangentHitrect), selectedColor); } } } } // Events if (state.editable) { // Keyframe move if (m_EditMode == EditMode.Moving && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { EditMoveKeyframe(animCurve, keys, k); } // Tangent editing if (m_EditMode == EditMode.TangentEdit && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { bool alreadyBroken = !(Mathf.Approximately(keys[k].inTangent, keys[k].outTangent) || (float.IsInfinity(keys[k].inTangent) && float.IsInfinity(keys[k].outTangent))); EditMoveTangent(animCurve, keys, k, m_TangentEditMode, e.shift || !(alreadyBroken || e.control)); } // Keyframe selection if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition)) { if (hitRect.Contains(e.mousePosition)) { SelectKeyframe(curve, k); m_EditMode = EditMode.Moving; e.Use(); } } // Tangent selection & edit mode if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition)) { if (inTangentHitRect.Contains(e.mousePosition) && (k > 0 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.In; e.Use(); } else if (outTangentHitrect.Contains(e.mousePosition) && (k < length - 1 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.Out; e.Use(); } } // Mouse up - clean up states if (e.rawType == EventType.MouseUp && m_EditMode != EditMode.None) { m_EditMode = EditMode.None; } // Set cursors { EditorGUIUtility.AddCursorRect(hitRect, MouseCursor.MoveArrow); if (k > 0 || state.loopInBounds) EditorGUIUtility.AddCursorRect(inTangentHitRect, MouseCursor.RotateArrow); if (k < length - 1 || state.loopInBounds) EditorGUIUtility.AddCursorRect(outTangentHitrect, MouseCursor.RotateArrow); } } } Handles.color = Color.white; SaveCurve(curve, animCurve); } void OnGeneralUI(Rect rect) { var e = Event.current; // Selection if (e.type == EventType.mouseDown) { GUI.FocusControl(null); m_SelectedCurve = null; m_SelectedKeyframeIndex = -1; var hit = CanvasToCurve(e.mousePosition); float curvePickValue = CurveToCanvas(hit).y; // Try and select a curve foreach (var curve in m_Curves) { if (!curve.Value.editable || !curve.Value.visible) continue; var prop = curve.Key; var state = curve.Value; var animCurve = prop.animationCurveValue; float hitY = animCurve.length == 0 ? state.zeroKeyConstantValue : animCurve.Evaluate(hit.x); var curvePos = CurveToCanvas(new Vector3(hit.x, hitY)); if (Mathf.Abs(curvePos.y - curvePickValue) < settings.curvePickingDistance) { m_SelectedCurve = prop; // Create a keyframe on double-click on this curve if (e.clickCount == 2) { EditCreateKeyframe(animCurve, hit, true, state.zeroKeyConstantValue); SaveCurve(prop, animCurve); } } } // Create a keyframe on every curve on double-click if (e.clickCount == 2 && m_SelectedCurve == null) { foreach (var curve in m_Curves) { if (!curve.Value.editable || !curve.Value.visible) continue; var prop = curve.Key; var state = curve.Value; var animCurve = prop.animationCurveValue; EditCreateKeyframe(animCurve, hit, e.alt, state.zeroKeyConstantValue); SaveCurve(prop, animCurve); } } e.Use(); } // Delete selected key(s) if (e.type == EventType.keyDown && (e.keyCode == KeyCode.Delete || e.keyCode == KeyCode.Backspace)) { if (m_SelectedKeyframeIndex != -1 && m_SelectedCurve != null) { var animCurve = m_SelectedCurve.animationCurveValue; var length = animCurve.length; if (m_Curves[m_SelectedCurve].minPointCount < length && length >= 0) { EditDeleteKeyframe(animCurve, m_SelectedKeyframeIndex); m_SelectedKeyframeIndex = -1; SaveCurve(m_SelectedCurve, animCurve); } e.Use(); } } } void SaveCurve(SerializedProperty prop, AnimationCurve curve) { prop.animationCurveValue = curve; } void Invalidate() { m_Dirty = true; } #endregion #region Keyframe manipulations void SelectKeyframe(SerializedProperty curve, int keyframeIndex) { m_SelectedKeyframeIndex = keyframeIndex; m_SelectedCurve = curve; Invalidate(); } void EditCreateKeyframe(AnimationCurve curve, Vector3 position, bool createOnCurve, float zeroKeyConstantValue) { float tangent = EvaluateTangent(curve, position.x); if (createOnCurve) { position.y = curve.length == 0 ? zeroKeyConstantValue : curve.Evaluate(position.x); } AddKeyframe(curve, new Keyframe(position.x, position.y, tangent, tangent)); } void EditDeleteKeyframe(AnimationCurve curve, int keyframeIndex) { RemoveKeyframe(curve, keyframeIndex); } void AddKeyframe(AnimationCurve curve, Keyframe newValue) { curve.AddKey(newValue); Invalidate(); } void RemoveKeyframe(AnimationCurve curve, int keyframeIndex) { curve.RemoveKey(keyframeIndex); Invalidate(); } void SetKeyframe(AnimationCurve curve, int keyframeIndex, Keyframe newValue) { var keys = curve.keys; if (keyframeIndex > 0) newValue.time = Mathf.Max(keys[keyframeIndex - 1].time + settings.keyTimeClampingDistance, newValue.time); if (keyframeIndex < keys.Length - 1) newValue.time = Mathf.Min(keys[keyframeIndex + 1].time - settings.keyTimeClampingDistance, newValue.time); curve.MoveKey(keyframeIndex, newValue); Invalidate(); } void EditMoveKeyframe(AnimationCurve curve, Keyframe[] keys, int keyframeIndex) { var key = CanvasToCurve(Event.current.mousePosition); float inTgt = keys[keyframeIndex].inTangent; float outTgt = keys[keyframeIndex].outTangent; SetKeyframe(curve, keyframeIndex, new Keyframe(key.x, key.y, inTgt, outTgt)); } void EditMoveTangent(AnimationCurve curve, Keyframe[] keys, int keyframeIndex, Tangent targetTangent, bool linkTangents) { var pos = CanvasToCurve(Event.current.mousePosition); float time = keys[keyframeIndex].time; float value = keys[keyframeIndex].value; pos -= new Vector3(time, value); if (targetTangent == Tangent.In && pos.x > 0f) pos.x = 0f; if (targetTangent == Tangent.Out && pos.x < 0f) pos.x = 0f; float tangent; if (Mathf.Approximately(pos.x, 0f)) tangent = pos.y < 0f ? float.PositiveInfinity : float.NegativeInfinity; else tangent = pos.y / pos.x; float inTangent = keys[keyframeIndex].inTangent; float outTangent = keys[keyframeIndex].outTangent; if (targetTangent == Tangent.In || linkTangents) inTangent = tangent; if (targetTangent == Tangent.Out || linkTangents) outTangent = tangent; SetKeyframe(curve, keyframeIndex, new Keyframe(time, value, inTangent, outTangent)); } #endregion #region Maths utilities Vector3 CurveToCanvas(Keyframe keyframe) { return CurveToCanvas(new Vector3(keyframe.time, keyframe.value)); } Vector3 CurveToCanvas(Vector3 position) { var bounds = settings.bounds; var output = new Vector3((position.x - bounds.x) / (bounds.xMax - bounds.x), (position.y - bounds.y) / (bounds.yMax - bounds.y)); output.x = output.x * (m_CurveArea.xMax - m_CurveArea.xMin) + m_CurveArea.xMin; output.y = (1f - output.y) * (m_CurveArea.yMax - m_CurveArea.yMin) + m_CurveArea.yMin; return output; } Vector3 CanvasToCurve(Vector3 position) { var bounds = settings.bounds; var output = position; output.x = (output.x - m_CurveArea.xMin) / (m_CurveArea.xMax - m_CurveArea.xMin); output.y = (output.y - m_CurveArea.yMin) / (m_CurveArea.yMax - m_CurveArea.yMin); output.x = Mathf.Lerp(bounds.x, bounds.xMax, output.x); output.y = Mathf.Lerp(bounds.yMax, bounds.y, output.y); return output; } Vector3 CurveTangentToCanvas(float tangent) { if (!float.IsInfinity(tangent)) { var bounds = settings.bounds; float ratio = (m_CurveArea.width / m_CurveArea.height) / ((bounds.xMax - bounds.x) / (bounds.yMax - bounds.y)); return new Vector3(1f, -tangent / ratio).normalized; } return float.IsPositiveInfinity(tangent) ? Vector3.up : Vector3.down; } Vector3[] BezierSegment(Keyframe start, Keyframe end) { var segment = new Vector3[4]; segment[0] = CurveToCanvas(new Vector3(start.time, start.value)); segment[3] = CurveToCanvas(new Vector3(end.time, end.value)); float middle = start.time + ((end.time - start.time) * 0.333333f); float middle2 = start.time + ((end.time - start.time) * 0.666666f); segment[1] = CurveToCanvas(new Vector3(middle, ProjectTangent(start.time, start.value, start.outTangent, middle))); segment[2] = CurveToCanvas(new Vector3(middle2, ProjectTangent(end.time, end.value, end.inTangent, middle2))); return segment; } Vector3[] HardSegment(Keyframe start, Keyframe end) { var segment = new Vector3[3]; segment[0] = CurveToCanvas(start); segment[1] = CurveToCanvas(new Vector3(end.time, start.value)); segment[2] = CurveToCanvas(end); return segment; } float ProjectTangent(float inPosition, float inValue, float inTangent, float projPosition) { return inValue + ((projPosition - inPosition) * inTangent); } float EvaluateTangent(AnimationCurve curve, float time) { int prev = -1, next = 0; for (int i = 0; i < curve.keys.Length; i++) { if (time > curve.keys[i].time) { prev = i; next = i + 1; } else break; } if (next == 0) return 0f; if (prev == curve.keys.Length - 1) return 0f; const float kD = 1e-3f; float tp = Mathf.Max(time - kD, curve.keys[prev].time); float tn = Mathf.Min(time + kD, curve.keys[next].time); float vp = curve.Evaluate(tp); float vn = curve.Evaluate(tn); if (Mathf.Approximately(tn, tp)) return (vn - vp > 0f) ? float.PositiveInfinity : float.NegativeInfinity; return (vn - vp) / (tn - tp); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; namespace MongoDB.Messaging.Storage { /// <summary> /// The queue storage repository /// </summary> public class QueueRepository : IQueueRepository { private readonly IMongoCollection<Message> _collection; /// <summary> /// Initializes a new instance of the <see cref="QueueRepository"/> class. /// </summary> /// <param name="collection">The underlying storage collection.</param> public QueueRepository(IMongoCollection<Message> collection) { _collection = collection; } /// <summary> /// Gets the underlying storage collection. /// </summary> /// <value> /// The underlying storage collection. /// </value> public IMongoCollection<Message> Collection { get { return _collection; } } /// <summary> /// Start an <see cref="IQueryable" /> of all messages. /// </summary> /// <returns> /// An <see cref="IQueryable" /> of all messages. /// </returns> public IQueryable<Message> All() { return _collection.AsQueryable(); } /// <summary> /// Finds message with the specified <paramref name="id" /> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> Find(string id) { return _collection .Find(m => m.Id == id) .FirstOrDefaultAsync(); } /// <summary> /// Finds one message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> FindOne(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .FirstOrDefaultAsync(); } /// <summary> /// Finds all message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<List<Message>> FindAll(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .ToListAsync(); } /// <summary> /// Gets the number of message as an asynchronous operation. /// </summary> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> Count() { // empty document to get all var filter = new BsonDocument(); return _collection .CountAsync(filter); } /// <summary> /// Gets the number of message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria"></param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> Count(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .CountAsync(); } /// <summary> /// Save the specified <paramref name="message" /> as an asynchronous operation. /// </summary> /// <param name="message">The message to save.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> public Task<Message> Save(Message message) { if (message == null) throw new ArgumentNullException("message"); // generate id if null, upsert requires id if (string.IsNullOrEmpty(message.Id)) { message.Id = ObjectId.GenerateNewId().ToString(); message.Created = DateTime.UtcNow; } message.Updated = DateTime.UtcNow; var updateOptions = new UpdateOptions { IsUpsert = true }; return _collection .ReplaceOneAsync(m => m.Id == message.Id, message, updateOptions) .ContinueWith(t => message); } /// <summary> /// Delete the message with the specified <paramref name="id" /> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<long> Delete(string id) { if (id == null) throw new ArgumentNullException("id"); return _collection .DeleteOneAsync(m => m.Id == id) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Delete one message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> DeleteOne(Expression<Func<Message, bool>> criteria) { return _collection .DeleteOneAsync(criteria) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Delete all message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> DeleteAll(Expression<Func<Message, bool>> criteria) { return _collection .DeleteManyAsync(criteria) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Enqueue the specified <paramref name="message" /> for processing as an asynchronous operation. /// </summary> /// <param name="message">The message to queue.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> public Task<Message> Enqueue(Message message) { if (message == null) throw new ArgumentNullException("message"); // mark state as queued message.State = MessageState.Queued; return Save(message); } /// <summary> /// Dequeues the next queued message for processing as an asynchronous operation. /// </summary> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> Dequeue() { var filter = Builders<Message>.Filter .Eq(m => m.State, MessageState.Queued); var update = Builders<Message>.Update .Set(m => m.State, MessageState.Processing) .Set(p => p.Status, "Begin processing ...") .Set(p => p.StartTime, DateTime.UtcNow) .Set(p => p.Updated, DateTime.UtcNow); // sort by priority then by insert order var sort = Builders<Message>.Sort .Ascending(m => m.Priority) .Ascending(m => m.Id); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; options.Sort = sort; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Requeue the message with the specified <paramref name="id"/> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task"/> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> Requeue(string id) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Queued) .Set(p => p.Updated, DateTime.UtcNow); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Schedules the message with specified identifier for processing on the <paramref name="scheduled"/> date and time. /// </summary> /// <param name="id">The message identifier to schedule.</param> /// <param name="scheduled">The date and time of the scheduled processing.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> Schedule(string id, DateTime scheduled) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Scheduled) .Set(p => p.Scheduled, scheduled.ToUniversalTime()) .Set(p => p.Updated, DateTime.UtcNow) .Unset(p => p.Expire); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Schedules the specified <paramref name="message" /> for future processing as an asynchronous operation. /// </summary> /// <param name="message">The message to queue.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">The Scheduled property can't be null when scheduling a message.</exception> public Task<Message> Schedule(Message message) { if (message == null) throw new ArgumentNullException("message"); if (message.Scheduled == null) throw new ArgumentException("The Scheduled property can't be null when scheduling a message.", "message"); // mark state as queued message.State = MessageState.Scheduled; return Save(message); } /// <summary> /// Updates the status of the message with specified <paramref name="id" /> as an asynchronous operation.. /// </summary> /// <param name="id">The identifier of the message.</param> /// <param name="status">The status display mesage.</param> /// <param name="step">The current processing step.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> UpdateStatus(string id, string status, int? step = null) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.Updated, DateTime.UtcNow); if (!string.IsNullOrEmpty(status)) update.Set(p => p.Status, status); if (step.HasValue) update.Set(p => p.Step, step.Value); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Marks the processing complete for the message with specified <paramref name="id" /> as an asynchronous operation.. /// </summary> /// <param name="id">The identifier of the message.</param> /// <param name="messageResult">The result of the processing.</param> /// <param name="status">The status display mesage.</param> /// <param name="expireDate">The expire date.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> MarkComplete(string id, MessageResult messageResult, string status = null, DateTime? expireDate = null) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Complete) .Set(p => p.Result, messageResult) .Set(p => p.EndTime, DateTime.UtcNow) .Set(p => p.Updated, DateTime.UtcNow); update = expireDate.HasValue ? update.Set(p => p.Expire, expireDate.Value) : update.Unset(p => p.Expire); if (!string.IsNullOrEmpty(status)) update = update.Set(p => p.Status, status); if (messageResult == MessageResult.Error) update = update.Inc(p => p.ErrorCount, 1); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } } }
#region License /* Licensed to Blue Chilli Technology Pty Ltd and the contributors under the MIT License (the "License"). You may not use this file except in compliance with the License. See the LICENSE file in the project root for more information. */ #endregion // *********************************************************************** // Assembly : XLabs.Platform.Droid // Author : XLabs Team // Created : 12-27-2015 // // Last Modified By : XLabs Team // Last Modified On : 01-04-2016 // *********************************************************************** // <copyright file="Geolocator.cs" company="XLabs Team"> // Copyright (c) XLabs Team. All rights reserved. // </copyright> // <summary> // This project is licensed under the Apache 2.0 license // https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE // // XLabs is a open source project that aims to provide a powerfull and cross // platform set of controls tailored to work with Xamarin Forms. // </summary> // *********************************************************************** // using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Android.Content; using Android.Locations; using Android.OS; using ChilliSource.Mobile.Location; using Java.Lang; using Xamarin.Forms; using ChilliSource.Mobile.Core; [assembly: Dependency(typeof(LocationService))] namespace ChilliSource.Mobile.Location { public class LocationService : ILocationService { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private string _headingProvider; private Position _lastPosition; private GeolocationContinuousListener _listener; private LocationManager _manager; private readonly object _positionSync = new object(); private string[] _providers; double _desiredAccuracy; ILogger _logger; #region Properties public bool IsListening { get { return _listener != null; } } public bool SupportsHeading { get { if (string.IsNullOrEmpty(_headingProvider) || _manager.IsProviderEnabled(_headingProvider)) { Criteria c = new Criteria { BearingRequired = true }; string providerName = _manager.GetBestProvider(c, enabledOnly: false); LocationProvider provider = _manager.GetProvider(providerName); if (provider.SupportsBearing()) { _headingProvider = providerName; return true; } else { _headingProvider = null; return false; } } else { return true; } } } public bool IsGeolocationAvailable { get { return _providers.Length > 0; } } public bool IsGeolocationEnabled { get { return _providers.Any(_manager.IsProviderEnabled); } } #endregion #region Events public event EventHandler<PositionErrorEventArgs> ErrorOccured; public event EventHandler<PositionEventArgs> PositionChanged; #pragma warning disable CS0067 public event EventHandler<RegionEventArgs> RegionEntered; public event EventHandler<RegionEventArgs> RegionLeft; public event EventHandler<AuthorizationEventArgs> LocationAuthorizationChanged; #pragma warning restore CS0067 #endregion #region Lifecycle public void Initialize(LocationAuthorizationType authorizationType, bool allowBackgroundLocationUpdates, bool monitorRegions = false, ILogger logger = null) { _logger = logger; _manager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService); _providers = _manager.GetProviders(false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } public void Dispose() { _manager?.Dispose(); _manager = null; } #endregion #region Location Monitoring public void RequestAlwaysAuthorization() { throw new NotImplementedException(); } /// <summary> /// Start listening to location changes /// </summary> /// <param name="minTime">Minimum interval in milliseconds</param> /// <param name="minDistance">Minimum distance in meters</param> /// <param name="includeHeading">Include heading information</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// minTime /// or /// minDistance /// </exception> /// <exception cref="System.InvalidOperationException">This Geolocator is already listening</exception> public OperationResult StartListening(uint minTime, double minDistance, double desiredAccurancy = 0, bool includeHeading = false) { if (IsListening) { return OperationResult.AsFailure("Already listening"); } if (minTime < 0) { return OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minTime))); } if (minDistance < 0) { return OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minDistance))); } _desiredAccuracy = desiredAccurancy; _listener = new GeolocationContinuousListener(_manager, TimeSpan.FromMilliseconds(minTime), _providers); _listener.PositionChanged += OnListenerPositionChanged; _listener.PositionError += OnListenerPositionError; var looper = Looper.MyLooper() ?? Looper.MainLooper; for (var i = 0; i < _providers.Length; ++i) { _manager.RequestLocationUpdates(_providers[i], minTime, (float)minDistance, _listener, looper); } return OperationResult.AsSuccess(); } public OperationResult StopListening() { if (!IsListening) { return OperationResult.AsFailure("Location updates already stopped"); } _listener.PositionChanged -= OnListenerPositionChanged; _listener.PositionError -= OnListenerPositionError; for (var i = 0; i < _providers.Length; ++i) { _manager.RemoveUpdates(_listener); } _listener = null; return OperationResult.AsSuccess(); } public void StartListeningForSignificantLocationChanges() { throw new NotImplementedException(); } public void StopListeningForSignificantLocationChanges() { throw new NotImplementedException(); } public void StartMonitoringBeaconRegion(string uuid, ushort major, ushort minor, string identifier) { throw new NotImplementedException(); } public void StartMonitoringCircularRegion(Position centerPosition, double radius, string identifier) { throw new NotImplementedException(); } public void StopMonitoringRegion(string identifier) { throw new NotImplementedException(); } #endregion #region Position Management public Task<OperationResult<Position>> GetPositionAsync(CancellationToken cancelToken, bool includeHeading = false) { return GetPositionAsync(Timeout.Infinite, cancelToken); } public Task<OperationResult<Position>> GetPositionAsync(int timeout, bool includeHeading = false) { return GetPositionAsync(timeout, CancellationToken.None); } public Task<OperationResult<Position>> GetPositionAsync(int timeout, CancellationToken cancelToken, bool includeHeading = false) { var tcs = new TaskCompletionSource<OperationResult<Position>>(); if (timeout <= 0 && timeout != Timeout.Infinite) { var exception = new ArgumentOutOfRangeException(nameof(timeout), "timeout must be greater than or equal to 0"); tcs.SetResult(OperationResult<Position>.AsFailure(exception)); return tcs.Task; } if (!IsListening) { GeolocationSingleListener singleListener = null; singleListener = new GeolocationSingleListener( (float)_desiredAccuracy, timeout, _providers.Where(_manager.IsProviderEnabled), () => { for (var i = 0; i < _providers.Length; ++i) { _manager.RemoveUpdates(singleListener); } }); if (cancelToken != CancellationToken.None) { cancelToken.Register( () => { singleListener.Cancel(); for (var i = 0; i < _providers.Length; ++i) { _manager.RemoveUpdates(singleListener); } }, true); } try { var looper = Looper.MyLooper() ?? Looper.MainLooper; var enabled = 0; for (var i = 0; i < _providers.Length; ++i) { if (_manager.IsProviderEnabled(_providers[i])) { enabled++; } _manager.RequestLocationUpdates(_providers[i], 0, 0, singleListener, looper); } if (enabled == 0) { for (var i = 0; i < _providers.Length; ++i) { _manager.RemoveUpdates(singleListener); } tcs.SetResult(OperationResult<Position>.AsFailure(new LocationException(LocationErrorType.PositionUnavailable))); return tcs.Task; } } catch (SecurityException ex) { tcs.SetResult(OperationResult<Position>.AsFailure(new LocationException(LocationErrorType.Unauthorized, ex))); return tcs.Task; } return singleListener.Task; } // If we're already listening, just use the current listener lock (_positionSync) { if (_lastPosition == null) { if (cancelToken != CancellationToken.None) { cancelToken.Register(() => tcs.TrySetCanceled()); } EventHandler<PositionEventArgs> gotPosition = null; gotPosition = (s, e) => { tcs.TrySetResult(OperationResult<Position>.AsSuccess(e.Position)); PositionChanged -= gotPosition; }; PositionChanged += gotPosition; } else { tcs.SetResult(OperationResult<Position>.AsSuccess(_lastPosition)); } } return tcs.Task; } public OperationResult<double> GetDistanceFrom(Position referencePosition) { if (referencePosition == null) { return OperationResult<double>.AsFailure("Invalid reference position specified"); } if (_lastPosition == null) { return OperationResult<double>.AsFailure("Current position not available"); } float[] results = new float[1]; try { Android.Locations.Location.DistanceBetween(referencePosition.Latitude, referencePosition.Longitude, _lastPosition.Latitude, _lastPosition.Longitude, results); } catch (IllegalArgumentException e) { return OperationResult<double>.AsFailure(e); } if (results != null && results.Length > 0) { return OperationResult<double>.AsSuccess(results[0]); } else { return OperationResult<double>.AsFailure("Could not calculate distance"); } } public OperationResult<double> GetDistanceBetween(Position firstPosition, Position secondPosition) { if (firstPosition == null || secondPosition == null) { return OperationResult<double>.AsFailure("Invalid positions specified"); } float[] results = new float[1]; try { Android.Locations.Location.DistanceBetween(firstPosition.Latitude, firstPosition.Longitude, secondPosition.Latitude, secondPosition.Longitude, results); } catch (IllegalArgumentException e) { return OperationResult<double>.AsFailure(e); } if (results != null && results.Length > 0) { return OperationResult<double>.AsSuccess(results[0]); } else { return OperationResult<double>.AsFailure("Could not calculate distance"); } } #endregion #region Event Handlers private void OnListenerPositionChanged(object sender, PositionEventArgs e) { if (!IsListening) // ignore anything that might come in afterwards { return; } lock (_positionSync) { _lastPosition = e.Position; PositionChanged?.Invoke(this, e); } } private void OnListenerPositionError(object sender, PositionErrorEventArgs e) { StopListening(); ErrorOccured?.Invoke(this, e); } #endregion #region Helper methods internal static DateTimeOffset GetTimestamp(Android.Locations.Location location) { return new DateTimeOffset(Epoch.AddMilliseconds(location.Time)); } #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.Text; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class GZipStreamTests { static string gzTestFile(string fileName) { return Path.Combine("GZTestData", fileName); } [Fact] public void BaseStream1() { var writeStream = new MemoryStream(); var zip = new GZipStream(writeStream, CompressionMode.Compress); Assert.Same(zip.BaseStream, writeStream); writeStream.Dispose(); } [Fact] public void BaseStream2() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Decompress); Assert.Same(zip.BaseStream, ms); ms.Dispose(); } [Fact] public async Task ModifyBaseStream() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var zip = new GZipStream(ms, CompressionMode.Decompress); int size = 1024; byte[] bytes = new byte[size]; zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected } [Fact] public void DecompressCanRead() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Decompress); Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress"); zip.Dispose(); Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress"); } [Fact] public void CompressCanWrite() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Compress); Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress"); zip.Dispose(); Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose"); } [Fact] public void CanDisposeBaseStream() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Compress); ms.Dispose(); // This would throw if this was invalid } [Fact] public void CanDisposeGZipStream() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Compress); zip.Dispose(); Assert.Null(zip.BaseStream); zip.Dispose(); // Should be a no-op } [Fact] public async Task CanReadBaseStreamAfterDispose() { var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); var zip = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true); var baseStream = zip.BaseStream; zip.Dispose(); int size = 1024; byte[] bytes = new byte[size]; baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected } [Fact] public async Task DecompressWorks() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz")); await DecompressAsync(compareStream, gzStream); } [Fact] public async Task DecompressWorksWithDoc() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz")); await DecompressAsync(compareStream, gzStream); } [Fact] public async Task DecompressWorksWithDocx() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx.gz")); await DecompressAsync(compareStream, gzStream); } [Fact] public async Task DecompressWorksWithPdf() { var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf")); var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf.gz")); await DecompressAsync(compareStream, gzStream); } // Making this async since regular read/write are tested below private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream) { var ms = new MemoryStream(); var zip = new GZipStream(gzStream, CompressionMode.Decompress); var GZipStream = new MemoryStream(); await zip.CopyToAsync(GZipStream); GZipStream.Position = 0; compareStream.Position = 0; byte[] compareArray = compareStream.ToArray(); byte[] writtenArray = GZipStream.ToArray(); Assert.Equal(compareArray.Length, writtenArray.Length); for (int i = 0; i < compareArray.Length; i++) { Assert.Equal(compareArray[i], writtenArray[i]); } } [Fact] public void NullBaseStreamThrows() { Assert.Throws<ArgumentNullException>(() => { var deflate = new GZipStream(null, CompressionMode.Decompress); }); Assert.Throws<ArgumentNullException>(() => { var deflate = new GZipStream(null, CompressionMode.Compress); }); } [Fact] public void DisposedBaseStreamThrows() { var ms = new MemoryStream(); ms.Dispose(); Assert.Throws<ArgumentException>(() => { var deflate = new GZipStream(ms, CompressionMode.Decompress); }); Assert.Throws<ArgumentException>(() => { var deflate = new GZipStream(ms, CompressionMode.Compress); }); } [Fact] public void ReadOnlyStreamThrowsOnCompress() { var ms = new LocalMemoryStream(); ms.SetCanWrite(false); Assert.Throws<ArgumentException>(() => { var gzip = new GZipStream(ms, CompressionMode.Compress); }); } [Fact] public void WriteOnlyStreamThrowsOnDecompress() { var ms = new LocalMemoryStream(); ms.SetCanRead(false); Assert.Throws<ArgumentException>(() => { var gzip = new GZipStream(ms, CompressionMode.Decompress); }); } [Fact] public void CopyToAsyncArgumentValidation() { using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Decompress)) { Assert.Throws<ArgumentNullException>("destination", () => { gs.CopyToAsync(null); }); Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { gs.CopyToAsync(new MemoryStream(), 0); }); Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); }); gs.Dispose(); Assert.Throws<ObjectDisposedException>(() => { gs.CopyToAsync(new MemoryStream()); }); } using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Compress)) { Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream()); }); } } [Fact] public void TestCtors() { CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression }; foreach (CompressionLevel level in legalValues) { bool[] boolValues = new bool[] { true, false }; foreach (bool remainsOpen in boolValues) { TestCtor(level, remainsOpen); } } } [Fact] public void TestLevelOptimial() { TestCtor(CompressionLevel.Optimal); } [Fact] public void TestLevelNoCompression() { TestCtor(CompressionLevel.NoCompression); } [Fact] public void TestLevelFastest() { TestCtor(CompressionLevel.Fastest); } private static void TestCtor(CompressionLevel level, bool? leaveOpen = null) { //Create the GZipStream int _bufferSize = 1024; var bytes = new byte[_bufferSize]; var baseStream = new MemoryStream(bytes, writable: true); GZipStream ds; if (leaveOpen == null) { ds = new GZipStream(baseStream, level); } else { ds = new GZipStream(baseStream, level, leaveOpen ?? false); } //Write some data and Close the stream string strData = "Test Data"; var encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(strData); ds.Write(data, 0, data.Length); ds.Flush(); ds.Dispose(); if (leaveOpen != true) { //Check that Close has really closed the underlying stream Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); }); } //Read the data byte[] data2 = new byte[_bufferSize]; baseStream = new MemoryStream(bytes, writable: false); ds = new GZipStream(baseStream, CompressionMode.Decompress); int size = ds.Read(data2, 0, _bufferSize - 5); //Verify the data roundtripped for (int i = 0; i < size + 5; i++) { if (i < data.Length) { Assert.Equal(data[i], data2[i]); } else { Assert.Equal(data2[i], (byte)0); } } } [Fact] public async Task Flush() { var ms = new MemoryStream(); var ds = new GZipStream(ms, CompressionMode.Compress); ds.Flush(); await ds.FlushAsync(); // Just ensuring Flush doesn't throw } [Fact] public void FlushFailsAfterDispose() { var ms = new MemoryStream(); var ds = new GZipStream(ms, CompressionMode.Compress); ds.Dispose(); Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); }); } [Fact] public async Task FlushAsyncFailsAfterDispose() { var ms = new MemoryStream(); var ds = new GZipStream(ms, CompressionMode.Compress); ds.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(async () => { await ds.FlushAsync(); }); } [Fact] public void TestSeekMethodsDecompress() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Decompress); Assert.False(zip.CanSeek); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); zip.Dispose(); Assert.False(zip.CanSeek); } [Fact] public void TestSeekMethodsCompress() { var ms = new MemoryStream(); var zip = new GZipStream(ms, CompressionMode.Compress); Assert.False(zip.CanSeek); Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; }); Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; }); Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; }); Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); }); Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); }); zip.Dispose(); Assert.False(zip.CanSeek); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal.NetworkSenders; using NLog.Layouts; /// <summary> /// Sends log messages over the network. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will be very slow. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// <p> /// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a> /// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private Dictionary<string, LinkedListNode<NetworkSender>> currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>(); private LinkedList<NetworkSender> openNetworkSenders = new LinkedList<NetworkSender>(); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NetworkTarget() { this.SenderFactory = NetworkSenderFactory.Default; this.Encoding = Encoding.UTF8; this.OnOverflow = NetworkTargetOverflowAction.Split; this.KeepConnection = true; this.MaxMessageSize = 65000; this.ConnectionCacheSize = 5; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li> /// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li> /// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(true)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(false)] public bool NewLine { get; set; } /// <summary> /// Gets or sets the maximum message size in bytes. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(65000)] public int MaxMessageSize { get; set; } /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(5)] public int ConnectionCacheSize { get; set; } /// <summary> /// Gets or sets the maximum current connections. 0 = no maximum. /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(0)] public int MaxConnections { get; set; } /// <summary> /// Gets or sets the action that should be taken if the will be more connections than <see cref="MaxConnections"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; } /// <summary> /// Gets or sets the maximum queue size. /// </summary> [DefaultValue(0)] public int MaxQueueSize { get; set; } /// <summary> /// Gets or sets the action that should be taken if the message is larger than /// maxMessageSize. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue("utf-8")] public Encoding Encoding { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount = 0; AsyncContinuation continuation = ex => { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } }; lock (this.openNetworkSenders) { remainingCount = this.openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in this.openNetworkSenders) { openSender.FlushAsync(continuation); } } } } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { base.CloseTarget(); lock (this.openNetworkSenders) { foreach (var openSender in this.openNetworkSenders) { openSender.Close(ex => { }); } this.openNetworkSenders.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = this.Address.Render(logEvent.LogEvent); byte[] bytes = this.GetBytesToWrite(logEvent.LogEvent); if (this.KeepConnection) { var senderNode = this.GetCachedNetworkSender(address); this.ChunkedSend( senderNode.Value, bytes, ex => { if (ex != null) { InternalLogger.Error("Error when sending {0}", ex); this.ReleaseCachedConnection(senderNode); } logEvent.Continuation(ex); }); } else { lock (this.openNetworkSenders) { //handle to many connections var tooManyConnections = this.openNetworkSenders.Count >= MaxConnections; if (tooManyConnections && MaxConnections > 0) { switch (this.OnConnectionOverflow) { case NetworkTargetConnectionsOverflowAction.DiscardMessage: InternalLogger.Warn("Discarding message otherwise to many connections."); logEvent.Continuation(null); return; case NetworkTargetConnectionsOverflowAction.AllowNewConnnection: InternalLogger.Debug("Too may connections, but this is allowed"); break; case NetworkTargetConnectionsOverflowAction.Block: while (this.openNetworkSenders.Count >= this.MaxConnections) { InternalLogger.Debug("Blocking networktarget otherwhise too many connections."); System.Threading.Monitor.Wait(this.openNetworkSenders); InternalLogger.Trace("Entered critical section."); } InternalLogger.Trace("Limit ok."); break; } } var sender = this.SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); var linkedListNode = this.openNetworkSenders.AddLast(sender); this.ChunkedSend( sender, bytes, ex => { lock (this.openNetworkSenders) { TryRemove(this.openNetworkSenders, linkedListNode); if (this.OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block) { System.Threading.Monitor.PulseAll(this.openNetworkSenders); } } if (ex != null) { InternalLogger.Error("Error when sending {0}", ex); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } } } /// <summary> /// Try to remove. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="node"></param> /// <returns>removed something?</returns> private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node) { if (node == null || list != node.List) { return false; } list.Remove(node); return true; } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { string text; if (this.NewLine) { text = this.Layout.Render(logEvent) + "\r\n"; } else { text = this.Layout.Render(logEvent); } return this.Encoding.GetBytes(text); } private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address) { lock (this.currentSenderCache) { LinkedListNode<NetworkSender> senderNode; // already have address if (this.currentSenderCache.TryGetValue(address, out senderNode)) { senderNode.Value.CheckSocket(); return senderNode; } if (this.currentSenderCache.Count >= this.ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; LinkedListNode<NetworkSender> leastRecentlyUsed = null; foreach (var pair in this.currentSenderCache) { var networkSender = pair.Value.Value; if (networkSender.LastSendTime < minAccessTime) { minAccessTime = networkSender.LastSendTime; leastRecentlyUsed = pair.Value; } } if (leastRecentlyUsed != null) { this.ReleaseCachedConnection(leastRecentlyUsed); } } var sender = this.SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); lock (this.openNetworkSenders) { senderNode = this.openNetworkSenders.AddLast(sender); } this.currentSenderCache.Add(address, senderNode); return senderNode; } } private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode) { lock (this.currentSenderCache) { var networkSender = senderNode.Value; lock (this.openNetworkSenders) { if(TryRemove(this.openNetworkSenders,senderNode)) { // only remove it once networkSender.Close(ex => { }); } } LinkedListNode<NetworkSender> sender2; // make sure the current sender for this address is the one we want to remove if (this.currentSenderCache.TryGetValue(networkSender.Address, out sender2)) { if (ReferenceEquals(senderNode, sender2)) { this.currentSenderCache.Remove(networkSender.Address); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")] private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int tosend = buffer.Length; int pos = 0; AsyncContinuation sendNextChunk = null; sendNextChunk = ex => { if (ex != null) { continuation(ex); return; } if (tosend <= 0) { continuation(null); return; } int chunksize = tosend; if (chunksize > this.MaxMessageSize) { if (this.OnOverflow == NetworkTargetOverflowAction.Discard) { continuation(null); return; } if (this.OnOverflow == NetworkTargetOverflowAction.Error) { continuation(new OverflowException("Attempted to send a message larger than MaxMessageSize (" + this.MaxMessageSize + "). Actual size was: " + buffer.Length + ". Adjust OnOverflow and MaxMessageSize parameters accordingly.")); return; } chunksize = this.MaxMessageSize; } int pos0 = pos; tosend -= chunksize; pos += chunksize; sender.Send(buffer, pos0, chunksize, sendNextChunk); }; sendNextChunk(null); } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Vericred.Model { /// <summary> /// Provider /// </summary> [DataContract] public partial class Provider : IEquatable<Provider> { /// <summary> /// Initializes a new instance of the <see cref="Provider" /> class. /// </summary> /// <param name="City">City name (e.g. Springfield)..</param> /// <param name="Email">Primary email address to contact the provider..</param> /// <param name="Gender">Provider&#39;s gender (M or F).</param> /// <param name="FirstName">Given name for the provider..</param> /// <param name="Id">National Provider Index (NPI) number.</param> /// <param name="LastName">Family name for the provider..</param> /// <param name="Latitude">Latitude of provider.</param> /// <param name="Longitude">Longitude of provider.</param> /// <param name="MiddleName">Middle name for the provider..</param> /// <param name="NetworkIds">Array of network ids.</param> /// <param name="OrganizationName">name for the providers of type: organization..</param> /// <param name="PersonalPhone">Personal contact phone for the provider..</param> /// <param name="Phone">Office phone for the provider.</param> /// <param name="PresentationName">Preferred name for display (e.g. Dr. Francis White may prefer Dr. Frank White).</param> /// <param name="Specialty">Name of the primary Specialty.</param> /// <param name="State">State code for the provider&#39;s address (e.g. NY)..</param> /// <param name="StateId">Foreign key to States.</param> /// <param name="StreetLine1">First line of the provider&#39;s street address..</param> /// <param name="StreetLine2">Second line of the provider&#39;s street address..</param> /// <param name="Suffix">Suffix for the provider&#39;s name (e.g. Jr).</param> /// <param name="Title">Professional title for the provider (e.g. Dr)..</param> /// <param name="Type">Type of NPI number (individual provider vs organization)..</param> /// <param name="ZipCode">Postal code for the provider&#39;s address (e.g. 11215).</param> public Provider(string City = null, string Email = null, string Gender = null, string FirstName = null, int? Id = null, string LastName = null, decimal? Latitude = null, decimal? Longitude = null, string MiddleName = null, List<int?> NetworkIds = null, string OrganizationName = null, string PersonalPhone = null, string Phone = null, string PresentationName = null, string Specialty = null, string State = null, int? StateId = null, string StreetLine1 = null, string StreetLine2 = null, string Suffix = null, string Title = null, string Type = null, string ZipCode = null) { this.City = City; this.Email = Email; this.Gender = Gender; this.FirstName = FirstName; this.Id = Id; this.LastName = LastName; this.Latitude = Latitude; this.Longitude = Longitude; this.MiddleName = MiddleName; this.NetworkIds = NetworkIds; this.OrganizationName = OrganizationName; this.PersonalPhone = PersonalPhone; this.Phone = Phone; this.PresentationName = PresentationName; this.Specialty = Specialty; this.State = State; this.StateId = StateId; this.StreetLine1 = StreetLine1; this.StreetLine2 = StreetLine2; this.Suffix = Suffix; this.Title = Title; this.Type = Type; this.ZipCode = ZipCode; } /// <summary> /// City name (e.g. Springfield). /// </summary> /// <value>City name (e.g. Springfield).</value> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Primary email address to contact the provider. /// </summary> /// <value>Primary email address to contact the provider.</value> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// Provider&#39;s gender (M or F) /// </summary> /// <value>Provider&#39;s gender (M or F)</value> [DataMember(Name="gender", EmitDefaultValue=false)] public string Gender { get; set; } /// <summary> /// Given name for the provider. /// </summary> /// <value>Given name for the provider.</value> [DataMember(Name="first_name", EmitDefaultValue=false)] public string FirstName { get; set; } /// <summary> /// National Provider Index (NPI) number /// </summary> /// <value>National Provider Index (NPI) number</value> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; set; } /// <summary> /// Family name for the provider. /// </summary> /// <value>Family name for the provider.</value> [DataMember(Name="last_name", EmitDefaultValue=false)] public string LastName { get; set; } /// <summary> /// Latitude of provider /// </summary> /// <value>Latitude of provider</value> [DataMember(Name="latitude", EmitDefaultValue=false)] public decimal? Latitude { get; set; } /// <summary> /// Longitude of provider /// </summary> /// <value>Longitude of provider</value> [DataMember(Name="longitude", EmitDefaultValue=false)] public decimal? Longitude { get; set; } /// <summary> /// Middle name for the provider. /// </summary> /// <value>Middle name for the provider.</value> [DataMember(Name="middle_name", EmitDefaultValue=false)] public string MiddleName { get; set; } /// <summary> /// Array of network ids /// </summary> /// <value>Array of network ids</value> [DataMember(Name="network_ids", EmitDefaultValue=false)] public List<int?> NetworkIds { get; set; } /// <summary> /// name for the providers of type: organization. /// </summary> /// <value>name for the providers of type: organization.</value> [DataMember(Name="organization_name", EmitDefaultValue=false)] public string OrganizationName { get; set; } /// <summary> /// Personal contact phone for the provider. /// </summary> /// <value>Personal contact phone for the provider.</value> [DataMember(Name="personal_phone", EmitDefaultValue=false)] public string PersonalPhone { get; set; } /// <summary> /// Office phone for the provider /// </summary> /// <value>Office phone for the provider</value> [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } /// <summary> /// Preferred name for display (e.g. Dr. Francis White may prefer Dr. Frank White) /// </summary> /// <value>Preferred name for display (e.g. Dr. Francis White may prefer Dr. Frank White)</value> [DataMember(Name="presentation_name", EmitDefaultValue=false)] public string PresentationName { get; set; } /// <summary> /// Name of the primary Specialty /// </summary> /// <value>Name of the primary Specialty</value> [DataMember(Name="specialty", EmitDefaultValue=false)] public string Specialty { get; set; } /// <summary> /// State code for the provider&#39;s address (e.g. NY). /// </summary> /// <value>State code for the provider&#39;s address (e.g. NY).</value> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// Foreign key to States /// </summary> /// <value>Foreign key to States</value> [DataMember(Name="state_id", EmitDefaultValue=false)] public int? StateId { get; set; } /// <summary> /// First line of the provider&#39;s street address. /// </summary> /// <value>First line of the provider&#39;s street address.</value> [DataMember(Name="street_line_1", EmitDefaultValue=false)] public string StreetLine1 { get; set; } /// <summary> /// Second line of the provider&#39;s street address. /// </summary> /// <value>Second line of the provider&#39;s street address.</value> [DataMember(Name="street_line_2", EmitDefaultValue=false)] public string StreetLine2 { get; set; } /// <summary> /// Suffix for the provider&#39;s name (e.g. Jr) /// </summary> /// <value>Suffix for the provider&#39;s name (e.g. Jr)</value> [DataMember(Name="suffix", EmitDefaultValue=false)] public string Suffix { get; set; } /// <summary> /// Professional title for the provider (e.g. Dr). /// </summary> /// <value>Professional title for the provider (e.g. Dr).</value> [DataMember(Name="title", EmitDefaultValue=false)] public string Title { get; set; } /// <summary> /// Type of NPI number (individual provider vs organization). /// </summary> /// <value>Type of NPI number (individual provider vs organization).</value> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Postal code for the provider&#39;s address (e.g. 11215) /// </summary> /// <value>Postal code for the provider&#39;s address (e.g. 11215)</value> [DataMember(Name="zip_code", EmitDefaultValue=false)] public string ZipCode { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Provider {\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" Gender: ").Append(Gender).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" Latitude: ").Append(Latitude).Append("\n"); sb.Append(" Longitude: ").Append(Longitude).Append("\n"); sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); sb.Append(" NetworkIds: ").Append(NetworkIds).Append("\n"); sb.Append(" OrganizationName: ").Append(OrganizationName).Append("\n"); sb.Append(" PersonalPhone: ").Append(PersonalPhone).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" PresentationName: ").Append(PresentationName).Append("\n"); sb.Append(" Specialty: ").Append(Specialty).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" StateId: ").Append(StateId).Append("\n"); sb.Append(" StreetLine1: ").Append(StreetLine1).Append("\n"); sb.Append(" StreetLine2: ").Append(StreetLine2).Append("\n"); sb.Append(" Suffix: ").Append(Suffix).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ZipCode: ").Append(ZipCode).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Provider); } /// <summary> /// Returns true if Provider instances are equal /// </summary> /// <param name="other">Instance of Provider to be compared</param> /// <returns>Boolean</returns> public bool Equals(Provider other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.City == other.City || this.City != null && this.City.Equals(other.City) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.Gender == other.Gender || this.Gender != null && this.Gender.Equals(other.Gender) ) && ( this.FirstName == other.FirstName || this.FirstName != null && this.FirstName.Equals(other.FirstName) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.LastName == other.LastName || this.LastName != null && this.LastName.Equals(other.LastName) ) && ( this.Latitude == other.Latitude || this.Latitude != null && this.Latitude.Equals(other.Latitude) ) && ( this.Longitude == other.Longitude || this.Longitude != null && this.Longitude.Equals(other.Longitude) ) && ( this.MiddleName == other.MiddleName || this.MiddleName != null && this.MiddleName.Equals(other.MiddleName) ) && ( this.NetworkIds == other.NetworkIds || this.NetworkIds != null && this.NetworkIds.SequenceEqual(other.NetworkIds) ) && ( this.OrganizationName == other.OrganizationName || this.OrganizationName != null && this.OrganizationName.Equals(other.OrganizationName) ) && ( this.PersonalPhone == other.PersonalPhone || this.PersonalPhone != null && this.PersonalPhone.Equals(other.PersonalPhone) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.PresentationName == other.PresentationName || this.PresentationName != null && this.PresentationName.Equals(other.PresentationName) ) && ( this.Specialty == other.Specialty || this.Specialty != null && this.Specialty.Equals(other.Specialty) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.StateId == other.StateId || this.StateId != null && this.StateId.Equals(other.StateId) ) && ( this.StreetLine1 == other.StreetLine1 || this.StreetLine1 != null && this.StreetLine1.Equals(other.StreetLine1) ) && ( this.StreetLine2 == other.StreetLine2 || this.StreetLine2 != null && this.StreetLine2.Equals(other.StreetLine2) ) && ( this.Suffix == other.Suffix || this.Suffix != null && this.Suffix.Equals(other.Suffix) ) && ( this.Title == other.Title || this.Title != null && this.Title.Equals(other.Title) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.ZipCode == other.ZipCode || this.ZipCode != null && this.ZipCode.Equals(other.ZipCode) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.City != null) hash = hash * 59 + this.City.GetHashCode(); if (this.Email != null) hash = hash * 59 + this.Email.GetHashCode(); if (this.Gender != null) hash = hash * 59 + this.Gender.GetHashCode(); if (this.FirstName != null) hash = hash * 59 + this.FirstName.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.LastName != null) hash = hash * 59 + this.LastName.GetHashCode(); if (this.Latitude != null) hash = hash * 59 + this.Latitude.GetHashCode(); if (this.Longitude != null) hash = hash * 59 + this.Longitude.GetHashCode(); if (this.MiddleName != null) hash = hash * 59 + this.MiddleName.GetHashCode(); if (this.NetworkIds != null) hash = hash * 59 + this.NetworkIds.GetHashCode(); if (this.OrganizationName != null) hash = hash * 59 + this.OrganizationName.GetHashCode(); if (this.PersonalPhone != null) hash = hash * 59 + this.PersonalPhone.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.PresentationName != null) hash = hash * 59 + this.PresentationName.GetHashCode(); if (this.Specialty != null) hash = hash * 59 + this.Specialty.GetHashCode(); if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.StateId != null) hash = hash * 59 + this.StateId.GetHashCode(); if (this.StreetLine1 != null) hash = hash * 59 + this.StreetLine1.GetHashCode(); if (this.StreetLine2 != null) hash = hash * 59 + this.StreetLine2.GetHashCode(); if (this.Suffix != null) hash = hash * 59 + this.Suffix.GetHashCode(); if (this.Title != null) hash = hash * 59 + this.Title.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.ZipCode != null) hash = hash * 59 + this.ZipCode.GetHashCode(); return hash; } } } }
using UnityEngine; using System; using System.Linq; using System.Collections.Generic; namespace Voxelgon.Geometry { public static class GeoUtil { // PUBLIC STATIC METHODS // returns the intersection position for two lines, where p is a point on the line and d is its direction public static float SqrDistance(Vector3 p1, Vector3 p2) { var dx = (p1.x - p2.x); var dy = (p1.y - p2.y); var dz = (p1.z - p2.z); return (dx * dx + dy * dy + dz * dz); } // returns the winding order of a triangle in 3D space around `normal` public static int WindingOrder(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 normal) { var vectorA = new Vector3(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z); //unity's vector ops are slow??? var vectorB = new Vector3(p2.x - p0.x, p2.y - p0.y, p2.z - p0.z); return VectorWindingOrder(vectorA, vectorB, normal); } // returns the winding order of a triangle in 2D space // returns the winding order of two vectors in 3D space around `normal` public static int VectorWindingOrder(Vector3 vectorA, Vector3 vectorB, Vector3 normal) { var cross = Vector3.Cross(vectorA, normal); var dot = Vector3.Dot(cross, vectorB); if (Mathf.Approximately(0, dot)) return 0; return (dot > 0) ? 1 : -1; } // returns the winding order of two vectors in 2D space // returns the area of a triangle in 3D space public static float TriangleArea(Vector3 p0, Vector3 p1, Vector3 p2) { var vectorA = new Vector3(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z); //unity's vector ops are slow??? var vectorB = new Vector3(p2.x - p0.x, p2.y - p0.y, p2.z - p0.z); var crossed = Vector3.Cross(vectorA, vectorB); return crossed.magnitude / 2; } // returns the area of a triangle in 2D space // returns 2 times the area of a triangle in 2D space // returns if a triangle in 3D space contains a given point // the point is projected onto the plane of the triangle public static bool TriangleContains(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p, Vector3 normal) { bool contains = (WindingOrder(p0, p1, p, normal) != -1 && WindingOrder(p1, p2, p, normal) != -1 && WindingOrder(p2, p0, p, normal) != -1); return contains; } // returns if a triangle in 2D space contains a given point // using barycentric coordinates // returns the normal vector of a triangle public static Vector3 TriangleNormal(Vector3 p0, Vector3 p1, Vector3 p2) { var vectorA = new Vector3(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z); //unity's vector ops are slow??? var vectorB = new Vector3(p2.x - p0.x, p2.y - p0.y, p2.z - p0.z); var crossed = Vector3.Cross(vectorA, vectorB); return crossed.normalized; } // returns the angle of the first vertex of a triangle public static float TriangleAngle(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 normal) { var vectorA = new Vector3(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z); //unity's vector ops are slow??? var vectorB = new Vector3(p2.x - p0.x, p2.y - p0.y, p2.z - p0.z); return VectorAngle(vectorA, vectorB, normal); } // returns the angle between two vectors public static float VectorAngle(Vector3 vectorA, Vector3 vectorB, Vector3 normal) { Vector3 cross = Vector3.Cross(vectorA, vectorB); float cos = Vector3.Dot(vectorA, vectorB) / (vectorA.magnitude * vectorB.magnitude); float angle = Mathf.Acos(cos) * ((Vector3.Dot(cross, normal) >= 0) ? 1 : -1); return angle; } // returns the average of several points public static Vector3 VectorAvg(Vector3[] points) { if (points.Length == 0) throw new ArgumentException(); float sumX = 0; float sumY = 0; float sumZ = 0; foreach (Vector3 v in points) { sumX += v.x; sumY += v.y; sumZ += v.z; } float mult = 1.0f / points.Length; return new Vector3(sumX * mult, sumY * mult, sumZ * mult); } // returns the average of several points public static Vector3 VectorAvg(IEnumerable<Vector3> points) { float sumX = 0; float sumY = 0; float sumZ = 0; float n = 0; foreach (var v in points) { sumX += v.x; sumY += v.y; sumZ += v.z; n++; } float mult = 1 / n; return new Vector3(sumX * mult, sumY * mult, sumZ * mult); } // returns the average of several points // flattens `vertices` onto a plane through `center` with the normal `normal` public static Vector2[] FlattenPoints(Vector3 center, Vector3[] vertices, Vector3 normal) { Vector2[] flattened = new Vector2[vertices.Length]; Matrix4x4 matrix = Matrix4x4.TRS( center * -1, Quaternion.FromToRotation(normal, Vector3.forward), Vector3.one); for (var i = 0; i < vertices.Length; i++) { flattened[i] = matrix.MultiplyPoint3x4(vertices[i]); } return flattened; } // flattens `vertices` onto a plane through the origin with the normal `normal` public static Vector2[] FlattenPoints(Vector3[] vertices, Vector3 normal) { return FlattenPoints(Vector3.zero, vertices, normal); } // uses the shoelace algorithm on `vertices`, is 2*Area, and negative if clockwise // uses the shoelace algorithm on `vertices`, is 2*Area, and negative if clockwise // returns the first normal found for a set of vertices in 3D public static Vector3 PointsNormal(Vector3[] vertices) { if (vertices.Length < 3) { return Vector3.zero; } var p1 = vertices[vertices.Length - 2]; var p2 = vertices[vertices.Length - 1]; var p3 = vertices[0]; foreach (var v in vertices) { var normal = TriangleNormal(p1, p2, p3); p1 = p2; p2 = p3; p3 = v; if (normal.sqrMagnitude > 0.001f) return normal; } return Vector3.zero; } public static void TransformPoints(Vector3[] vertices, Matrix4x4 matrix) { for (var i = 0; i < vertices.Length; i++) { vertices[i] = matrix.MultiplyPoint3x4(vertices[i]); } } // length along the end of normalB perpendicular to it, // useful if you dont need the whole vector (e.g. normalB is vertical) // returns the point at the intersection to the surfaces at the ends of normalA and normalB // adds triangle indices for `vertices` to `tris`, and calls itself recursively to handle concave polygons // `index1` and `index2` should be 0 and 1 for the top level call // adds triangle indices for `vertices` to `tris`, and calls itself recursively to handle concave polygons // `index1` and `index2` should be 0 and 1 for the top level call // Creates a new AABB from two AABBs public static Bounds CalcBounds(Bounds box1, Bounds box2) { var bounds = new Bounds(); var min = new Vector3( Mathf.Min(box1.min.x, box2.min.x), Mathf.Min(box1.min.y, box2.min.y), Mathf.Min(box1.min.z, box2.min.z)); var max = new Vector3( Mathf.Max(box1.max.x, box2.max.x), Mathf.Max(box1.max.y, box2.max.y), Mathf.Max(box1.max.z, box2.max.z)); bounds.SetMinMax(min, max); return bounds; } // Creates a new AABB from a list of IBoundables public static Bounds CalcBounds(IEnumerable<Bounds> collection) { var min = new Vector3(); var max = new Vector3(); var array = collection as Bounds[] ?? collection.ToArray(); for (int i = 0; i < 3; i++) { min[i] = array.Min(o => o.min[i]); max[i] = array.Max(o => o.max[i]); } var bounds = new Bounds(); bounds.SetMinMax(min, max); return bounds; } // Creates a new AABB from a list of vectors public static Bounds CalcBounds(IEnumerable<Vector3> collection) { var min = new Vector3(); var max = new Vector3(); var array = collection as Vector3[] ?? collection.ToArray(); for (int i = 0; i < 3; i++) { min[i] = array.Min(o => o[i]); max[i] = array.Max(o => o[i]); } var bounds = new Bounds(); bounds.SetMinMax(min, max); return bounds; } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Web; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections; using gov.va.medora.mdo; using gov.va.medora.utils; using gov.va.medora.mdo.api; using gov.va.medora.mdo.dao; using gov.va.medora.mdws.dto; namespace gov.va.medora.mdws { public class LabsLib { MySession mySession; public LabsLib(MySession mySession) { this.mySession = mySession; } public TaggedPatientArrays getPatientsWithUpdatedChemHemReports(string username, string pwd, string fromDate) { TaggedPatientArrays result = new TaggedPatientArrays(); //if (String.IsNullOrEmpty(username) | String.IsNullOrEmpty(pwd) | String.IsNullOrEmpty(fromDate)) //{ // result.fault = new FaultTO("Must supply all arguments"); //} try { LabsApi api = new LabsApi(); DataSource ds = new DataSource { ConnectionString = mySession.MdwsConfiguration.CdwConnectionString }; AbstractConnection cxn = new gov.va.medora.mdo.dao.sql.cdw.CdwConnection(ds); Dictionary<string, HashSet<string>> dict = api.getUpdatedChemHemReports(cxn, DateTime.Parse(fromDate)); result.arrays = new TaggedPatientArray[dict.Keys.Count]; int arrayCount = 0; foreach (string key in dict.Keys) { TaggedPatientArray tpa = new TaggedPatientArray(key); tpa.patients = new PatientTO[dict[key].Count]; int patientCount = 0; foreach (string patientICN in dict[key]) { PatientTO p = new PatientTO { mpiPid = patientICN }; tpa.patients[patientCount] = p; patientCount++; } result.arrays[arrayCount] = tpa; arrayCount++; } } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedChemHemRptArrays getChemHemReports(string fromDate, string toDate) { TaggedChemHemRptArrays result = new TaggedChemHemRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { IndexedHashtable t = ChemHemReport.getChemHemReports(mySession.ConnectionSet, fromDate, toDate); result = new TaggedChemHemRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedChemHemRptArrays getChemHemReportsRdv(string fromDate, string toDate, int nrpts) { TaggedChemHemRptArrays result = new TaggedChemHemRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { IndexedHashtable t = ChemHemReport.getChemHemReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedChemHemRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedCytologyRptArrays getCytologyReports(string fromDate, string toDate, int nrpts) { TaggedCytologyRptArrays result = new TaggedCytologyRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getCytologyReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedCytologyRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedMicrobiologyRptArrays getMicrobiologyReports(string fromDate, string toDate, int nrpts) { TaggedMicrobiologyRptArrays result = new TaggedMicrobiologyRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getMicrobiologyReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedMicrobiologyRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedSurgicalPathologyRptArrays getSurgicalPathologyReports(string fromDate, string toDate, int nrpts) { TaggedSurgicalPathologyRptArrays result = new TaggedSurgicalPathologyRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getSurgicalPathologyReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedSurgicalPathologyRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getBloodAvailabilityReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getBloodAvailabilityReport(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getBloodTransfusionReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getBloodTransfusionReport(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getBloodBankReports() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getBloodBankReport(mySession.ConnectionSet); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getElectronMicroscopyReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getElectronMicroscopyReport(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getCytopathologyReports() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getCytopathologyReport(mySession.ConnectionSet); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getAutopsyReports() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); IndexedHashtable t = api.getAutopsyReport(mySession.ConnectionSet); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TextTO getLrDfn(string dfn) { return getLrDfn(null, dfn); } public TextTO getLrDfn(string sitecode, string dfn) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (dfn == "") { result.fault = new FaultTO("Missing dfn"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); LabsApi api = new LabsApi(); string lrdfn = api.getLrDfn(cxn, dfn); result = new TextTO(lrdfn); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedLabTestArrays getLabTests(string target) { TaggedLabTestArrays result = new TaggedLabTestArrays(); if (MdwsUtils.isAuthorizedConnection(mySession) != "OK") { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); return new TaggedLabTestArrays(api.getTests(mySession.ConnectionSet, target)); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedTextArray getTestDescription(string identifierString) { TaggedTextArray result = new TaggedTextArray(); if (MdwsUtils.isAuthorizedConnection(mySession) != "OK") { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { LabsApi api = new LabsApi(); return new TaggedTextArray(api.getTestDescription(mySession.ConnectionSet, identifierString)); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Collections.Generic; using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// Circuit data for an agent. Connection information shared between /// regions that accept UDP connections from a client /// </summary> public class AgentCircuitData { // DEBUG ON private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // DEBUG OFF /// <summary> /// Avatar Unique Agent Identifier /// </summary> public UUID AgentID; /// <summary> /// Avatar's Appearance /// </summary> public AvatarAppearance Appearance; /// <summary> /// Agent's root inventory folder /// </summary> public UUID BaseFolder; /// <summary> /// Base Caps path for user /// </summary> public string CapsPath = String.Empty; /// <summary> /// Seed caps for neighbor regions that the user can see into /// </summary> public Dictionary<ulong, string> ChildrenCapSeeds; /// <summary> /// Root agent, or Child agent /// </summary> public bool child; /// <summary> /// Number given to the client when they log-in that they provide /// as credentials to the UDP server /// </summary> public uint circuitcode; /// <summary> /// How this agent got here /// </summary> public uint teleportFlags; /// <summary> /// Agent's account first name /// </summary> public string firstname; public UUID InventoryFolder; /// <summary> /// Agent's account last name /// </summary> public string lastname; /// <summary> /// Random Unique GUID for this session. Client gets this at login and it's /// only supposed to be disclosed over secure channels /// </summary> public UUID SecureSessionID; /// <summary> /// Non secure Session ID /// </summary> public UUID SessionID; /// <summary> /// Hypergrid service token; generated by the user domain, consumed by the receiving grid. /// There is one such unique token for each grid visited. /// </summary> public string ServiceSessionID = string.Empty; /// <summary> /// The client's IP address, as captured by the login service /// </summary> public string IPAddress; /// <summary> /// Viewer's version string as reported by the viewer at login /// </summary> public string Viewer; /// <summary> /// The channel strinf sent by the viewer at login /// </summary> public string Channel; /// <summary> /// The Mac address as reported by the viewer at login /// </summary> public string Mac; /// <summary> /// The id0 as reported by the viewer at login /// </summary> public string Id0; /// <summary> /// Position the Agent's Avatar starts in the region /// </summary> public Vector3 startpos; public Dictionary<string, object> ServiceURLs; public AgentCircuitData() { } /// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) args["children_seeds"] = childrenSeeds; } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["client_ip"] = OSD.FromString(IPAddress); args["viewer"] = OSD.FromString(Viewer); args["channel"] = OSD.FromString(Channel); args["mac"] = OSD.FromString(Mac); args["id0"] = OSD.FromString(Id0); if (Appearance != null) { args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); OSDMap appmap = Appearance.Pack(); args["packed_appearance"] = appmap; } // Old, bad way. Keeping it fow now for backwards compatibility // OBSOLETE -- soon to be deleted if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } // again, this time the right way if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDMap urls = new OSDMap(); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()); } args["serviceurls"] = urls; } return args; } /// <summary> /// Unpack agent circuit data map into an AgentCiruitData object /// </summary> /// <param name="args"></param> public void UnpackAgentCircuitData(OSDMap args) { if (args["agent_id"] != null) AgentID = args["agent_id"].AsUUID(); if (args["base_folder"] != null) BaseFolder = args["base_folder"].AsUUID(); if (args["caps_path"] != null) CapsPath = args["caps_path"].AsString(); if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array)) { OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]); ChildrenCapSeeds = new Dictionary<ulong, string>(); foreach (OSD o in childrenSeeds) { if (o.Type == OSDType.Map) { ulong handle = 0; string seed = ""; OSDMap pair = (OSDMap)o; if (pair["handle"] != null) if (!UInt64.TryParse(pair["handle"].AsString(), out handle)) continue; if (pair["seed"] != null) seed = pair["seed"].AsString(); if (!ChildrenCapSeeds.ContainsKey(handle)) ChildrenCapSeeds.Add(handle, seed); } } } else ChildrenCapSeeds = new Dictionary<ulong, string>(); if (args["child"] != null) child = args["child"].AsBoolean(); if (args["circuit_code"] != null) UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode); if (args["first_name"] != null) firstname = args["first_name"].AsString(); if (args["last_name"] != null) lastname = args["last_name"].AsString(); if (args["inventory_folder"] != null) InventoryFolder = args["inventory_folder"].AsUUID(); if (args["secure_session_id"] != null) SecureSessionID = args["secure_session_id"].AsUUID(); if (args["session_id"] != null) SessionID = args["session_id"].AsUUID(); if (args["service_session_id"] != null) ServiceSessionID = args["service_session_id"].AsString(); if (args["client_ip"] != null) IPAddress = args["client_ip"].AsString(); if (args["viewer"] != null) Viewer = args["viewer"].AsString(); if (args["channel"] != null) Channel = args["channel"].AsString(); if (args["mac"] != null) Mac = args["mac"].AsString(); if (args["id0"] != null) Id0 = args["id0"].AsString(); if (args["start_pos"] != null) Vector3.TryParse(args["start_pos"].AsString(), out startpos); m_log.InfoFormat("[AGENTCIRCUITDATA] agentid={0}, child={1}, startpos={2}",AgentID,child,startpos.ToString()); try { // Unpack various appearance elements Appearance = new AvatarAppearance(AgentID); // Eventually this code should be deprecated, use full appearance // packing in packed_appearance if (args["appearance_serial"] != null) Appearance.Serial = args["appearance_serial"].AsInteger(); if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map)) { Appearance.Unpack((OSDMap)args["packed_appearance"]); m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance"); } else m_log.Warn("[AGENTCIRCUITDATA] failed to find a valid packed_appearance"); } catch (Exception e) { m_log.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}",e.Message); } ServiceURLs = new Dictionary<string, object>(); // Try parse the new way, OSDMap if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map) { OSDMap urls = (OSDMap)(args["serviceurls"]); foreach (KeyValuePair<String, OSD> kvp in urls) { ServiceURLs[kvp.Key] = kvp.Value.AsString(); //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); } } // else try the old way, OSDArray // OBSOLETE -- soon to be deleted else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) { ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString(); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Entities; using Signum.Utilities.DataStructures; using Signum.Utilities.Reflection; using Signum.Engine.Maps; using Signum.Entities.Reflection; using Signum.Entities.DynamicQuery; namespace Signum.Engine.Linq { /// <summary> /// QueryBinder is a visitor that converts method calls to LINQ operations into /// custom DbExpression nodes and references to class members into references to columns /// </summary> internal class MetadataVisitor : ExpressionVisitor { Dictionary<ParameterExpression, Expression> map = new Dictionary<ParameterExpression, Expression>(); private MetadataVisitor() { } static internal Dictionary<string, Meta?>? GatherMetadata(Expression expression) { if (expression == null) throw new ArgumentException("expression"); if (!typeof(IQueryable).IsAssignableFrom(expression.Type)) throw new InvalidOperationException("Expression type is not IQueryable"); Expression? simplified = MetaEvaluator.Clean(expression); var meta = (MetaProjectorExpression?)new MetadataVisitor().Visit(simplified!); if (meta == null) return null; var proj = meta.Projector; if (proj.NodeType != ExpressionType.New && //anonymous types proj.NodeType != ExpressionType.MemberInit && // not-anonymous type !(proj is MetaExpression && ((MetaExpression)proj).IsEntity)) // raw-entity! return null; PropertyInfo[] props = proj.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance); return props.ToDictionary(pi => pi.Name, pi => { Expression ex = BindMember(proj, pi, pi.PropertyType); return (ex as MetaExpression)?.Meta; }); } //internal static Expression JustVisit(LambdaExpression expression, PropertyRoute route) //{ // if (route.Type.IsLite()) // route = route.Add("Entity"); // return JustVisit(expression, )); //} internal static Expression JustVisit(LambdaExpression expression, MetaExpression metaExpression) { var cleaned = MetaEvaluator.Clean(expression); var replaced = ExpressionReplacer.Replace(Expression.Invoke(cleaned, metaExpression)); return new MetadataVisitor().Visit(replaced); } static MetaExpression MakeCleanMeta(Type type, Expression expression) { MetaExpression meta = (MetaExpression)expression; return new MetaExpression(type, meta.Meta); } static MetaExpression MakeDirtyMeta(Type type, Implementations? implementations, params Expression[] expression) { var metas = expression.OfType<MetaExpression>().Select(a => a.Meta).NotNull().ToArray(); return new MetaExpression(type, new DirtyMeta(implementations, metas)); } static internal Expression MakeVoidMeta(Type type) { return new MetaExpression(type, new DirtyMeta(null, new Meta[0])); } protected override Expression VisitMethodCall(MethodCallExpression m) { if (m.Method.DeclaringType == typeof(Queryable) || m.Method.DeclaringType == typeof(Enumerable) || m.Method.DeclaringType == typeof(EnumerableUniqueExtensions)) { switch (m.Method.Name) { case "Where": return this.BindWhere(m.Type, m.GetArgument("source"), m.GetArgument("predicate").StripQuotes()); case "Select": return this.BindSelect(m.Type, m.GetArgument("source"), m.GetArgument("selector").StripQuotes()); case "SelectMany": if (m.Arguments.Count == 2) return this.BindSelectMany(m.Type, m.GetArgument("source"), m.GetArgument("selector").StripQuotes(), null); else return this.BindSelectMany(m.Type, m.GetArgument("source"), m.GetArgument("collectionSelector").StripQuotes(), m.TryGetArgument("resultSelector")?.StripQuotes()); case "Join": return this.BindJoin( m.Type, m.GetArgument("outer"), m.GetArgument("inner"), m.GetArgument("outerKeySelector").StripQuotes(), m.GetArgument("innerKeySelector").StripQuotes(), m.GetArgument("resultSelector").StripQuotes()); case "OrderBy": return this.BindOrderBy(m.Type, m.GetArgument("source"), m.GetArgument("keySelector").StripQuotes(), OrderType.Ascending); case "OrderByDescending": return this.BindOrderBy(m.Type, m.GetArgument("source"), m.GetArgument("keySelector").StripQuotes(), OrderType.Descending); case "ThenBy": return this.BindThenBy(m.GetArgument("source"), m.GetArgument("keySelector").StripQuotes(), OrderType.Ascending); case "ThenByDescending": return this.BindThenBy(m.GetArgument("source"), m.GetArgument("keySelector").StripQuotes(), OrderType.Descending); case "GroupBy": return this.BindGroupBy(m.Type, m.GetArgument("source"), m.GetArgument("keySelector").StripQuotes(), m.GetArgument("elementSelector").StripQuotes()); case "Count": return this.BindCount(m.Type, m.GetArgument("source")); case "DefaultIfEmpty": return Visit(m.GetArgument("source")); case "Any": return this.BindAny(m.Type, m.GetArgument("source")); case "All": return this.BindAll(m.Type, m.GetArgument("source"), m.GetArgument("predicate").StripQuotes()); case "Contains": return this.BindContains(m.Type, m.GetArgument("source"), m.TryGetArgument("item") ?? m.GetArgument("value")); case "Sum": case "Min": case "Max": case "Average": return this.BindAggregate(m.Type, m.Method.Name.ToEnum<AggregateSqlFunction>(), m.GetArgument("source"), m.TryGetArgument("selector")?.StripQuotes()); case "First": case "FirstOrDefault": case "Single": case "SingleOrDefault": return BindUniqueRow(m.Type, m.Method.Name.ToEnum<UniqueFunction>(), m.GetArgument("source"), m.TryGetArgument("predicate")?.StripQuotes()); case "FirstEx": case "SingleEx": case "SingleOrDefaultEx": return BindUniqueRow(m.Type, m.Method.Name.RemoveEnd(2).ToEnum<UniqueFunction>(), m.GetArgument("collection"), m.TryGetArgument("predicate")?.StripQuotes()); case "Distinct": return BindDistinct(m.Type, m.GetArgument("source")); case "Take": return BindTake(m.Type, m.GetArgument("source"), m.GetArgument("count")); case "Skip": return BindSkip(m.Type, m.GetArgument("source"), m.GetArgument("count")); } } if (m.Method.Name == "Mixin" && m.Method.GetParameters().Length == 0) { var obj = Visit(m.Object); if (obj is MetaExpression me && me.Meta is CleanMeta) { CleanMeta cm = (CleanMeta)me.Meta; var mixinType = m.Method.GetGenericArguments().Single(); return new MetaExpression(mixinType, new CleanMeta(null, cm.PropertyRoutes.Select(a => a.Add(mixinType)).ToArray())); } } if (m.Method.DeclaringType == typeof(LinqHints) || m.Method.DeclaringType == typeof(LinqHintEntities)) return Visit(m.Arguments[0]); if (m.Method.DeclaringType == typeof(StringExtensions) && m.Method.Name == nameof(StringExtensions.Etc)) return Visit(m.Arguments[0]); if (m.Method.DeclaringType == typeof(Lite) && m.Method.Name == "ToLite") return MakeCleanMeta(m.Type, Visit(m.Arguments[0])); if (m.Method.DeclaringType == typeof(Math) && (m.Method.Name == "Abs" || m.Method.Name == "Ceiling" || m.Method.Name == "Floor" || m.Method.Name == "Round" || m.Method.Name == "Truncate")) return MakeCleanMeta(m.Type, Visit(m.Arguments[0])); if (m.Method.Name == "ToString" && m.Object != null && typeof(IEntity).IsAssignableFrom(m.Object.Type)) return Visit(Expression.Property(m.Object, piToStringProperty)); if (m.Object != null) { var a = this.Visit(m.Object); var list = this.Visit(m.Arguments); return MakeDirtyMeta(m.Type, null, list.PreAnd(a).ToArray()); } else { var list = this.Visit(m.Arguments); return MakeDirtyMeta(m.Type, null, list.ToArray()); } } static readonly PropertyInfo piToStringProperty = ReflectionTools.GetPropertyInfo((IEntity ii) => ii.ToStringProperty); private Expression MapAndVisit(LambdaExpression lambda, params MetaProjectorExpression[] projs) { map.SetRange(lambda.Parameters, projs.Select(a => a.Projector)); var result = Visit(lambda.Body); map.RemoveRange(lambda.Parameters); return result; } public static MetaProjectorExpression AsProjection(Expression expression) { if (expression is MetaProjectorExpression mpe) return mpe; if (expression.NodeType == ExpressionType.New) { NewExpression nex = (NewExpression)expression; if (nex.Type.IsInstantiationOf(typeof(Grouping<,>))) return (MetaProjectorExpression)nex.Arguments[1]; } Type? elementType = expression.Type.ElementType(); if (elementType != null) { if (expression is MetaExpression meta && meta.Meta is CleanMeta) { PropertyRoute route = ((CleanMeta)meta.Meta).PropertyRoutes.SingleEx(() => "PropertyRoutes for {0}. Metas don't work over polymorphic MLists".FormatWith(meta.Meta)).Add("Item"); return new MetaProjectorExpression(expression.Type, new MetaExpression(elementType, new CleanMeta(route.TryGetImplementations(), route))); } return new MetaProjectorExpression(expression.Type, MakeVoidMeta(elementType)); } throw new InvalidOperationException(); } private Expression BindTake(Type resultType, Expression source, Expression count) { return AsProjection(Visit(source)); } private Expression BindSkip(Type resultType, Expression source, Expression count) { return AsProjection(Visit(source)); } private Expression BindUniqueRow(Type resultType, UniqueFunction function, Expression source, LambdaExpression? predicate) { return AsProjection(Visit(source)).Projector; } private Expression BindDistinct(Type resultType, Expression source) { return AsProjection(Visit(source)); } private Expression BindCount(Type resultType, Expression source) { return MakeVoidMeta(resultType); } private Expression BindAll(Type resultType, Expression source, LambdaExpression predicate) { return MakeVoidMeta(resultType); } private Expression BindAny(Type resultType, Expression source) { return MakeVoidMeta(resultType); } private Expression BindContains(Type resultType, Expression source, Expression item) { return MakeVoidMeta(resultType); } private Expression BindAggregate(Type resultType, AggregateSqlFunction aggregateFunction, Expression source, LambdaExpression? selector) { MetaProjectorExpression mp = AsProjection(Visit(source)); if (selector == null) return mp.Projector; Expression projector = MapAndVisit(selector, mp); return projector; } private Expression BindWhere(Type resultType, Expression source, LambdaExpression predicate) { return AsProjection(Visit(source)); } private Expression BindSelect(Type resultType, Expression source, LambdaExpression selector) { MetaProjectorExpression mp = AsProjection(Visit(source)); Expression projector = MapAndVisit(selector, mp); return new MetaProjectorExpression(resultType, projector); } protected virtual Expression BindSelectMany(Type resultType, Expression source, LambdaExpression collectionSelector, LambdaExpression? resultSelector) { MetaProjectorExpression mp = AsProjection(Visit(source)); MetaProjectorExpression collectionProjector = AsProjection(MapAndVisit(collectionSelector, mp)); if (resultSelector == null) return collectionProjector; Expression resultProjection = MapAndVisit(resultSelector, mp, collectionProjector); return new MetaProjectorExpression(resultType, resultProjection); } protected virtual Expression BindJoin(Type resultType, Expression outerSource, Expression innerSource, LambdaExpression outerKey, LambdaExpression innerKey, LambdaExpression resultSelector) { MetaProjectorExpression mpOuter = AsProjection(Visit(outerSource)); MetaProjectorExpression mpInner = AsProjection(Visit(innerSource)); Expression projector = MapAndVisit(resultSelector, mpOuter, mpInner); return new MetaProjectorExpression(resultType, projector); } private Expression BindGroupBy(Type resultType, Expression source, LambdaExpression keySelector, LambdaExpression elementSelector) { MetaProjectorExpression mp = AsProjection(Visit(source)); Expression key = MapAndVisit(keySelector, mp); Expression element = MapAndVisit(elementSelector, mp); Type colType = typeof(IEnumerable<>).MakeGenericType(element.Type); Type groupType = typeof(Grouping<,>).MakeGenericType(key.Type, element.Type); return new MetaProjectorExpression(resultType, Expression.New(groupType.GetConstructor(new Type[] { key.Type, colType }), key, new MetaProjectorExpression(colType, element))); } protected virtual Expression BindOrderBy(Type resultType, Expression source, LambdaExpression orderSelector, OrderType orderType) { return AsProjection(Visit(source)); } protected virtual Expression BindThenBy(Expression source, LambdaExpression orderSelector, OrderType orderType) { return AsProjection(Visit(source)); } public Type? TableType(object value) { if (value == null) return null; Type t = value.GetType(); return typeof(IQueryable).IsAssignableFrom(t) ? t.GetGenericArguments()[0] : null; } public override Expression Visit(Expression exp) { if (exp is MetaExpression) return exp; return base.Visit(exp); } protected override Expression VisitConstant(ConstantExpression c) { Type? type = TableType(c.Value); if (type != null) { if (typeof(Entity).IsAssignableFrom(type)) return new MetaProjectorExpression(c.Type, new MetaExpression(type, new CleanMeta(Implementations.By(type), PropertyRoute.Root(type)))); if (type.IsInstantiationOf(typeof(MListElement<,>))) { var parentType = type.GetGenericArguments()[0]; ISignumTable st = (ISignumTable)c.Value; TableMList rt = (TableMList)st.Table; PropertyRoute element = rt.PropertyRoute.Add("Item"); return new MetaProjectorExpression(c.Type, new MetaMListExpression(type, new CleanMeta(Implementations.By(parentType), PropertyRoute.Root(rt.PropertyRoute.RootType)), new CleanMeta(element.TryGetImplementations(), element))); } } return MakeVoidMeta(c.Type); } protected override Expression VisitParameter(ParameterExpression p) { return map.TryGetC(p) ?? p; } protected override Expression VisitMember(MemberExpression m) { Expression source = Visit(m.Expression); return BindMember(source, m.Member, m.Type); } static Expression BindMember(Expression source, MemberInfo member, Type memberType) { switch (source.NodeType) { case ExpressionType.MemberInit: return ((MemberInitExpression)source).Bindings .OfType<MemberAssignment>() .SingleEx(a => ReflectionTools.MemeberEquals(a.Member, member)).Expression; case ExpressionType.New: NewExpression nex = (NewExpression)source; if (nex.Type.IsInstantiationOf(typeof(Grouping<,>)) && member.Name == "Key") { return nex.Arguments[0]; } if (nex.Members != null) { PropertyInfo pi = (PropertyInfo)member; return nex.Members.Zip(nex.Arguments).SingleEx(p => ReflectionTools.PropertyEquals((PropertyInfo)p.First, pi)).Second; } break; } if (source is MetaMListExpression mme) { var ga = mme.Type.GetGenericArguments(); if (member.Name == "Parent") return new MetaExpression(ga[0], mme.Parent); if (member.Name == "Element") return new MetaExpression(ga[1], mme.Element); throw new InvalidOperationException("Property {0} not found on {1}".FormatWith(member.Name, mme.Type.TypeName())); } if (typeof(ModifiableEntity).IsAssignableFrom(source.Type) || typeof(IEntity).IsAssignableFrom(source.Type)) { var pi = member as PropertyInfo ?? Reflector.TryFindPropertyInfo((FieldInfo)member); if (pi == null) return new MetaExpression(memberType, new DirtyMeta(null, new Meta[0])); MetaExpression meta = (MetaExpression)source; if(pi.DeclaringType == typeof(MixinEntity) && pi.Name == nameof(MixinEntity.MainEntity)) { var rootType = ((CleanMeta)meta.Meta).PropertyRoutes.Single().RootType; return new MetaExpression(rootType, new CleanMeta(Implementations.By(rootType), PropertyRoute.Root(rootType))); } if (meta.Meta.Implementations != null) { var routes = meta.Meta.Implementations.Value.Types.Select(t => PropertyRoute.Root(t).Add(pi)).ToArray(); return new MetaExpression(memberType, new CleanMeta(GetImplementations(routes, memberType), routes)); } if (meta.Meta is CleanMeta) { PropertyRoute[] routes = ((CleanMeta)meta.Meta).PropertyRoutes.Select(r => r.Add(pi.Name)).ToArray(); return new MetaExpression(memberType, new CleanMeta(GetImplementations(routes, memberType), routes)); } if (typeof(Entity).IsAssignableFrom(source.Type) && !source.Type.IsAbstract) //Works for simple entities and also for interface casting { var pr = PropertyRoute.Root(source.Type).Add(pi); return new MetaExpression(memberType, new CleanMeta(pr.TryGetImplementations(), pr)); } } if (source.Type.IsLite() && member.Name == "Entity") { MetaExpression meta = (MetaExpression)source; if (meta.Meta is CleanMeta) { PropertyRoute[] routes = ((CleanMeta)meta.Meta).PropertyRoutes.Select(pr => pr.Add("Entity")).ToArray(); return new MetaExpression(memberType, new CleanMeta(meta.Meta.Implementations, routes)); } } return MakeDirtyMeta(memberType, null, source); } internal static Entities.Implementations? GetImplementations(PropertyRoute[] propertyRoutes, Type cleanType) { if (!cleanType.IsIEntity() && !cleanType.IsLite()) return (Implementations?)null; var only = propertyRoutes.Only(); if (only != null && only.PropertyRouteType == PropertyRouteType.Root) return Signum.Entities.Implementations.By(cleanType); var aggregate = AggregateImplementations(propertyRoutes.Select(pr => pr.GetImplementations())); return aggregate; } public static Implementations AggregateImplementations(IEnumerable<Implementations> implementations) { if (implementations.IsEmpty()) throw new InvalidOperationException("implementations is Empty"); if (implementations.Count() == 1) return implementations.First(); if (implementations.Any(a => a.IsByAll)) return Signum.Entities.Implementations.ByAll; var types = implementations .SelectMany(ib => ib.Types) .Distinct() .ToArray(); return Signum.Entities.Implementations.By(types); } protected override Expression VisitTypeBinary(TypeBinaryExpression b) { return MakeDirtyMeta(b.Type, null, Visit(b.Expression)); } protected override Expression VisitUnary(UnaryExpression u) { var exp = (MetaExpression)Visit(u.Operand); if (u.NodeType == ExpressionType.Convert || u.NodeType == ExpressionType.TypeAs) { var imps = exp.Meta.Implementations?.Let(s => CastImplementations(s, u.Type.CleanType())); return new MetaExpression(u.Type, exp.Meta is DirtyMeta ? (Meta)new DirtyMeta(imps, ((DirtyMeta)exp.Meta).CleanMetas.Cast<Meta>().ToArray()) : (Meta)new CleanMeta(imps, ((CleanMeta)exp.Meta).PropertyRoutes)); } return new MetaExpression(u.Type, exp.Meta); } internal static Implementations CastImplementations(Implementations implementations, Type cleanType) { if (implementations.IsByAll) { if (!Schema.Current.Tables.ContainsKey(cleanType)) throw new InvalidOperationException("Tye type {0} is not registered in the schema as a concrete table".FormatWith(cleanType)); return Signum.Entities.Implementations.By(cleanType); } if (implementations.Types.All(cleanType.IsAssignableFrom)) return implementations; return Signum.Entities.Implementations.By(implementations.Types.Where(cleanType.IsAssignableFrom).ToArray()); } protected override Expression VisitBinary(BinaryExpression b) { var right = Visit(b.Right); var left = Visit(b.Left); Implementations? imps = right is MetaExpression mRight && mRight.Meta.Implementations != null && left is MetaExpression mLeft && mLeft.Meta.Implementations != null ? AggregateImplementations(new[] { mRight.Meta.Implementations.Value, mLeft.Meta.Implementations.Value }) : (Implementations?)null; return MakeDirtyMeta(b.Type, imps, left, right); } protected override Expression VisitConditional(ConditionalExpression c) { var ifTrue = Visit(c.IfTrue); var ifFalse = Visit(c.IfFalse); Implementations? imps = ifTrue is MetaExpression mIfTrue && mIfTrue.Meta.Implementations != null && ifFalse is MetaExpression mIfFalse && mIfFalse.Meta.Implementations != null ? AggregateImplementations(new[] { mIfTrue.Meta.Implementations.Value, mIfFalse.Meta.Implementations.Value }) : (Implementations?)null; return MakeDirtyMeta(c.Type, imps, Visit(c.Test), ifTrue, ifFalse); } } }
using System; using System.IO; namespace NAudio.Wave { /// <summary> /// Represents an MP3 Frame /// </summary> public class Mp3Frame { private const int MaxFrameLength = 16*1024; private static readonly int[,,] bitRates = { { // MPEG Version 1 {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448}, // Layer 1 {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384}, // Layer 2 {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320} // Layer 3 }, { // MPEG Version 2 & 2.5 {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, // Layer 1 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, // Layer 2 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160} // Layer 3 (same as layer 2) } }; private static readonly int[,] samplesPerFrame = { { // MPEG Version 1 384, // Layer1 1152, // Layer2 1152 // Layer3 }, { // MPEG Version 2 & 2.5 384, // Layer1 1152, // Layer2 576 // Layer3 } }; private static readonly int[] sampleRatesVersion1 = {44100, 48000, 32000}; private static readonly int[] sampleRatesVersion2 = {22050, 24000, 16000}; private static readonly int[] sampleRatesVersion25 = {11025, 12000, 8000}; //private short crc; /// <summary> /// Constructs an MP3 frame /// </summary> private Mp3Frame() { } /// <summary> /// Sample rate of this frame /// </summary> public int SampleRate { get; private set; } /// <summary> /// Frame length in bytes /// </summary> public int FrameLength { get; private set; } /// <summary> /// Bit Rate /// </summary> public int BitRate { get; private set; } /// <summary> /// Raw frame data (includes header bytes) /// </summary> public byte[] RawData { get; private set; } /// <summary> /// MPEG Version /// </summary> public MpegVersion MpegVersion { get; private set; } /// <summary> /// MPEG Layer /// </summary> public MpegLayer MpegLayer { get; private set; } /// <summary> /// Channel Mode /// </summary> public ChannelMode ChannelMode { get; private set; } /// <summary> /// The number of samples in this frame /// </summary> public int SampleCount { get; private set; } /// <summary> /// The channel extension bits /// </summary> public int ChannelExtension { get; private set; } /// <summary> /// The bitrate index (directly from the header) /// </summary> public int BitRateIndex { get; private set; } /// <summary> /// Whether the Copyright bit is set /// </summary> public bool Copyright { get; private set; } /// <summary> /// Whether a CRC is present /// </summary> public bool CrcPresent { get; private set; } /// <summary> /// Reads an MP3 frame from a stream /// </summary> /// <param name="input">input stream</param> /// <returns>A valid MP3 frame, or null if none found</returns> public static Mp3Frame LoadFromStream(Stream input) { return LoadFromStream(input, true); } /// <summary>Reads an MP3Frame from a stream</summary> /// <remarks> /// http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has some good info /// also see http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx /// </remarks> /// <returns>A valid MP3 frame, or null if none found</returns> public static Mp3Frame LoadFromStream(Stream input, bool readData) { var headerBytes = new byte[4]; int bytesRead = input.Read(headerBytes, 0, headerBytes.Length); if (bytesRead < headerBytes.Length) { // reached end of stream, no more MP3 frames return null; } var frame = new Mp3Frame(); while (!IsValidHeader(headerBytes, frame)) { // shift down by one and try again headerBytes[0] = headerBytes[1]; headerBytes[1] = headerBytes[2]; headerBytes[2] = headerBytes[3]; bytesRead = input.Read(headerBytes, 3, 1); if (bytesRead < 1) { return null; } } /* no longer read the CRC since we include this in framelengthbytes if (this.crcPresent) this.crc = reader.ReadInt16();*/ int bytesRequired = frame.FrameLength - 4; if (readData) { frame.RawData = new byte[frame.FrameLength]; Array.Copy(headerBytes, frame.RawData, 4); bytesRead = input.Read(frame.RawData, 4, bytesRequired); if (bytesRead < bytesRequired) { // TODO: could have an option to suppress this, although it does indicate a corrupt file // for now, caller should handle this exception throw new EndOfStreamException("Unexpected end of stream before frame complete"); } } else { // n.b. readData should not be false if input stream does not support seeking input.Position += bytesRequired; } return frame; } /// <summary> /// checks if the four bytes represent a valid header, /// if they are, will parse the values into Mp3Frame /// </summary> private static bool IsValidHeader(byte[] headerBytes, Mp3Frame frame) { if ((headerBytes[0] == 0xFF) && ((headerBytes[1] & 0xE0) == 0xE0)) { // TODO: could do with a bitstream class here frame.MpegVersion = (MpegVersion) ((headerBytes[1] & 0x18) >> 3); if (frame.MpegVersion == MpegVersion.Reserved) { //throw new FormatException("Unsupported MPEG Version"); return false; } frame.MpegLayer = (MpegLayer) ((headerBytes[1] & 0x06) >> 1); if (frame.MpegLayer == MpegLayer.Reserved) { return false; } int layerIndex = frame.MpegLayer == MpegLayer.Layer1 ? 0 : frame.MpegLayer == MpegLayer.Layer2 ? 1 : 2; frame.CrcPresent = (headerBytes[1] & 0x01) == 0x00; frame.BitRateIndex = (headerBytes[2] & 0xF0) >> 4; if (frame.BitRateIndex == 15) { // invalid index return false; } int versionIndex = frame.MpegVersion == MpegVersion.Version1 ? 0 : 1; frame.BitRate = bitRates[versionIndex, layerIndex, frame.BitRateIndex]*1000; if (frame.BitRate == 0) { return false; } int sampleFrequencyIndex = (headerBytes[2] & 0x0C) >> 2; if (sampleFrequencyIndex == 3) { return false; } if (frame.MpegVersion == MpegVersion.Version1) { frame.SampleRate = sampleRatesVersion1[sampleFrequencyIndex]; } else if (frame.MpegVersion == MpegVersion.Version2) { frame.SampleRate = sampleRatesVersion2[sampleFrequencyIndex]; } else { // mpegVersion == MpegVersion.Version25 frame.SampleRate = sampleRatesVersion25[sampleFrequencyIndex]; } bool padding = (headerBytes[2] & 0x02) == 0x02; bool privateBit = (headerBytes[2] & 0x01) == 0x01; frame.ChannelMode = (ChannelMode) ((headerBytes[3] & 0xC0) >> 6); frame.ChannelExtension = (headerBytes[3] & 0x30) >> 4; frame.Copyright = (headerBytes[3] & 0x08) == 0x08; bool original = (headerBytes[3] & 0x04) == 0x04; int emphasis = (headerBytes[3] & 0x03); int nPadding = padding ? 1 : 0; frame.SampleCount = samplesPerFrame[versionIndex, layerIndex]; int coefficient = frame.SampleCount/8; if (frame.MpegLayer == MpegLayer.Layer1) { frame.FrameLength = (coefficient*frame.BitRate/frame.SampleRate + nPadding)*4; } else { frame.FrameLength = (coefficient*frame.BitRate)/frame.SampleRate + nPadding; } if (frame.FrameLength > MaxFrameLength) { return false; } return true; } return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DriveWakeWeb.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using OpenMetaverse; namespace Aurora.Framework { public static class SLUtil { #region SL / file extension / content-type conversions public static string SLAssetTypeToContentType(int assetType) { switch ((AssetType) assetType) { case AssetType.Texture: return "image/x-j2c"; case AssetType.Sound: return "audio/ogg"; case AssetType.CallingCard: return "application/vnd.ll.callingcard"; case AssetType.Landmark: return "application/vnd.ll.landmark"; case AssetType.Clothing: return "application/vnd.ll.clothing"; case AssetType.Object: return "application/vnd.ll.primitive"; case AssetType.Notecard: return "application/vnd.ll.notecard"; case AssetType.Folder: return "application/vnd.ll.folder"; case AssetType.RootFolder: return "application/vnd.ll.rootfolder"; case AssetType.LSLText: return "application/vnd.ll.lsltext"; case AssetType.LSLBytecode: return "application/vnd.ll.lslbyte"; case AssetType.TextureTGA: case AssetType.ImageTGA: return "image/tga"; case AssetType.Bodypart: return "application/vnd.ll.bodypart"; case AssetType.TrashFolder: return "application/vnd.ll.trashfolder"; case AssetType.SnapshotFolder: return "application/vnd.ll.snapshotfolder"; case AssetType.LostAndFoundFolder: return "application/vnd.ll.lostandfoundfolder"; case AssetType.SoundWAV: return "audio/x-wav"; case AssetType.ImageJPEG: return "image/jpeg"; case AssetType.Animation: return "application/vnd.ll.animation"; case AssetType.Gesture: return "application/vnd.ll.gesture"; case AssetType.Simstate: return "application/x-metaverse-simstate"; case AssetType.FavoriteFolder: return "application/vnd.ll.favoritefolder"; case AssetType.Link: return "application/vnd.ll.link"; case AssetType.LinkFolder: return "application/vnd.ll.linkfolder"; case AssetType.CurrentOutfitFolder: return "application/vnd.ll.currentoutfitfolder"; case AssetType.OutfitFolder: return "application/vnd.ll.outfitfolder"; case AssetType.MyOutfitsFolder: return "application/vnd.ll.myoutfitsfolder"; case AssetType.Unknown: default: return "application/octet-stream"; } } public static string SLInvTypeToContentType(int invType) { switch ((InventoryType) invType) { case InventoryType.Animation: return "application/vnd.ll.animation"; case InventoryType.CallingCard: return "application/vnd.ll.callingcard"; case InventoryType.Folder: return "application/vnd.ll.folder"; case InventoryType.Gesture: return "application/vnd.ll.gesture"; case InventoryType.Landmark: return "application/vnd.ll.landmark"; case InventoryType.LSL: return "application/vnd.ll.lsltext"; case InventoryType.Notecard: return "application/vnd.ll.notecard"; case InventoryType.Attachment: case InventoryType.Object: return "application/vnd.ll.primitive"; case InventoryType.Sound: return "audio/ogg"; case InventoryType.Snapshot: case InventoryType.Texture: return "image/x-j2c"; case InventoryType.Wearable: return "application/vnd.ll.clothing"; default: return "application/octet-stream"; } } public static sbyte ContentTypeToSLAssetType(string contentType) { switch (contentType) { case "image/x-j2c": case "image/jp2": return (sbyte) AssetType.Texture; case "application/ogg": case "audio/ogg": return (sbyte) AssetType.Sound; case "application/vnd.ll.callingcard": case "application/x-metaverse-callingcard": return (sbyte) AssetType.CallingCard; case "application/vnd.ll.landmark": case "application/x-metaverse-landmark": return (sbyte) AssetType.Landmark; case "application/vnd.ll.clothing": case "application/x-metaverse-clothing": return (sbyte) AssetType.Clothing; case "application/vnd.ll.primitive": case "application/x-metaverse-primitive": return (sbyte) AssetType.Object; case "application/vnd.ll.notecard": case "application/x-metaverse-notecard": return (sbyte) AssetType.Notecard; case "application/vnd.ll.folder": return (sbyte) AssetType.Folder; case "application/vnd.ll.rootfolder": return (sbyte) AssetType.RootFolder; case "application/vnd.ll.lsltext": case "application/x-metaverse-lsl": return (sbyte) AssetType.LSLText; case "application/vnd.ll.lslbyte": case "application/x-metaverse-lso": return (sbyte) AssetType.LSLBytecode; case "image/tga": // Note that AssetType.TextureTGA will be converted to AssetType.ImageTGA return (sbyte) AssetType.ImageTGA; case "application/vnd.ll.bodypart": case "application/x-metaverse-bodypart": return (sbyte) AssetType.Bodypart; case "application/vnd.ll.trashfolder": return (sbyte) AssetType.TrashFolder; case "application/vnd.ll.snapshotfolder": return (sbyte) AssetType.SnapshotFolder; case "application/vnd.ll.lostandfoundfolder": return (sbyte) AssetType.LostAndFoundFolder; case "audio/x-wav": return (sbyte) AssetType.SoundWAV; case "image/jpeg": return (sbyte) AssetType.ImageJPEG; case "application/vnd.ll.animation": case "application/x-metaverse-animation": return (sbyte) AssetType.Animation; case "application/vnd.ll.gesture": case "application/x-metaverse-gesture": return (sbyte) AssetType.Gesture; case "application/x-metaverse-simstate": return (sbyte) AssetType.Simstate; case "application/vnd.ll.favoritefolder": return (sbyte) AssetType.FavoriteFolder; case "application/vnd.ll.link": return (sbyte) AssetType.Link; case "application/vnd.ll.linkfolder": return (sbyte) AssetType.LinkFolder; case "application/vnd.ll.currentoutfitfolder": return (sbyte) AssetType.CurrentOutfitFolder; case "application/vnd.ll.outfitfolder": return (sbyte) AssetType.OutfitFolder; case "application/vnd.ll.myoutfitsfolder": return (sbyte) AssetType.MyOutfitsFolder; case "application/octet-stream": default: return (sbyte) AssetType.Unknown; } } public static sbyte ContentTypeToSLInvType(string contentType) { switch (contentType) { case "image/x-j2c": case "image/jp2": case "image/tga": case "image/jpeg": return (sbyte) InventoryType.Texture; case "application/ogg": case "audio/ogg": case "audio/x-wav": return (sbyte) InventoryType.Sound; case "application/vnd.ll.callingcard": case "application/x-metaverse-callingcard": return (sbyte) InventoryType.CallingCard; case "application/vnd.ll.landmark": case "application/x-metaverse-landmark": return (sbyte) InventoryType.Landmark; case "application/vnd.ll.clothing": case "application/x-metaverse-clothing": case "application/vnd.ll.bodypart": case "application/x-metaverse-bodypart": return (sbyte) InventoryType.Wearable; case "application/vnd.ll.primitive": case "application/x-metaverse-primitive": return (sbyte) InventoryType.Object; case "application/vnd.ll.notecard": case "application/x-metaverse-notecard": return (sbyte) InventoryType.Notecard; case "application/vnd.ll.folder": return (sbyte) InventoryType.Folder; case "application/vnd.ll.rootfolder": return (sbyte) InventoryType.RootCategory; case "application/vnd.ll.lsltext": case "application/x-metaverse-lsl": case "application/vnd.ll.lslbyte": case "application/x-metaverse-lso": return (sbyte) InventoryType.LSL; case "application/vnd.ll.trashfolder": case "application/vnd.ll.snapshotfolder": case "application/vnd.ll.lostandfoundfolder": return (sbyte) InventoryType.Folder; case "application/vnd.ll.animation": case "application/x-metaverse-animation": return (sbyte) InventoryType.Animation; case "application/vnd.ll.gesture": case "application/x-metaverse-gesture": return (sbyte) InventoryType.Gesture; case "application/x-metaverse-simstate": return (sbyte) InventoryType.Snapshot; case "application/octet-stream": default: return (sbyte) InventoryType.Unknown; } } #endregion SL / file extension / content-type conversions // private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Parse a notecard in Linden format to a string of ordinary text. /// </summary> /// <param name = "rawInput"></param> /// <returns></returns> public static string ParseNotecardToString(string rawInput) { string[] output = ParseNotecardToList(rawInput).ToArray(); // foreach (string line in output) // MainConsole.Instance.DebugFormat("[PARSE NOTECARD]: ParseNotecardToString got line {0}", line); return string.Join("\n", output); } /// <summary> /// Parse a notecard in Linden format to a list of ordinary lines. /// </summary> /// <param name = "rawInput"></param> /// <returns></returns> public static List<string> ParseNotecardToList(string rawInput) { string[] input = rawInput.Replace("\r", "").Split('\n'); int idx = 0; int level = 0; List<string> output = new List<string>(); string[] words; while (idx < input.Length) { if (input[idx] == "{") { level++; idx++; continue; } if (input[idx] == "}") { level--; idx++; continue; } if (input[idx].EndsWith("}")) { input[idx] = input[idx].Remove(input[idx].Length - 1, 1); level--; } if (input[idx].StartsWith("{")) { input[idx] = input[idx].Remove(0, 1); level++; } switch (level) { case 0: words = input[idx].Split(' '); // Linden text ver // Notecards are created *really* empty. Treat that as "no text" (just like after saving an empty notecard) if (words.Length < 3) return output; int version = int.Parse(words[3]); if (version != 2) return output; break; case 1: words = input[idx].Split(' '); if (words[0] == "LLEmbeddedItems") break; if (words[0] == "Text") { int len = int.Parse(words[2]); idx++; int count = -1; while (count < len) { // int l = input[idx].Length; string ln = input[idx]; int stringLength = ln.Length; int need = len - count - 1; if (ln.Length > need) ln = ln.Substring(0, need); if (ln.EndsWith("}")) { ln = ln.Remove(ln.Length - 1, 1); level--; if(level == 0) break; } if (ln.StartsWith("{")) { ln = ln.Remove(0, 1); level++; } // MainConsole.Instance.DebugFormat("[PARSE NOTECARD]: Adding line {0}", ln); output.Add(ln); count += stringLength + 1; idx++; } return output; } break; case 2: words = input[idx].Split(' '); // count if (words[0] == "count") { int c = int.Parse(words[1]); if (c > 0) return output; break; } break; } idx++; } return output; } } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Web.UI.WebControls; using Rainbow.Framework; using Rainbow.Framework.Data; using Rainbow.Framework.Site.Configuration; using Rainbow.Framework.Site.Data; using Rainbow.Framework.Content.Data; using Rainbow.Framework.Users.Data; using Rainbow.Framework.Web.UI; using Label = System.Web.UI.WebControls.Label; using LinkButton = System.Web.UI.WebControls.LinkButton; using Page = System.Web.UI.Page; namespace Rainbow.Content.Web.Modules { /// <summary> /// Users Defined Table module - Manage page part /// Written by: Shaun Walker (IbuySpy Workshop) /// Moved into Rainbow by Jakob Hansen, hansen3000@hotmail.com /// </summary> [Rainbow.Framework.History("Ender", "2003/03/18", "Added file and Xsl functionality")] public partial class UserDefinedTableManage : EditItemPage { /// <summary> /// The Page_Load event on this Page is used to ... /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { if ( Page.IsPostBack == false ) { BindData(); // Store URL Referrer to return to portal //ViewState("UrlReferrer") = Replace(Request.UrlReferrer.ToString(), "insertrow=true&", string.Empty); ViewState["UrlReferrer"] = Request.UrlReferrer.ToString().Replace("insertrow=true&", string.Empty); } } /// <summary> /// Set the module guids with free access to this page /// </summary> /// <value>The allowed modules.</value> protected override ArrayList AllowedModules { get { ArrayList al = new ArrayList(); al.Add ("2502DB18-B580-4F90-8CB4-C15E6E531021"); return al; } } //private void cmdCancel_Click( object sender, EventArgs e) cmdCancel.Click, cmdCancel.Click /// <summary> /// Handles the Click event of the cmdCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void cmdCancel_Click(object sender, EventArgs e) { // Redirect back to the portal home page this.RedirectBackToReferringPage(); } /// <summary> /// Handles the CancelEdit event of the grdFields control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param> protected void grdFields_CancelEdit(object sender, DataGridCommandEventArgs e) { grdFields.EditItemIndex = -1; BindData(); } /// <summary> /// Handles the Edit event of the grdFields control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param> public void grdFields_Edit(object sender, DataGridCommandEventArgs e) { grdFields.EditItemIndex = e.Item.ItemIndex; grdFields.SelectedIndex = -1; BindData(); } /// <summary> /// Handles the Update event of the grdFields control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param> public void grdFields_Update(object sender, DataGridCommandEventArgs e) { CheckBox chkVisible = (CheckBox) e.Item.Cells[1].Controls[1]; TextBox txtFieldTitle = (TextBox) e.Item.Cells[2].Controls[1]; DropDownList cboFieldType = (DropDownList) e.Item.Cells[3].Controls[1]; if ( txtFieldTitle.Text.Length != 0 ) { UserDefinedTableDB objUserDefinedTable = new UserDefinedTableDB(); if ( int.Parse(grdFields.DataKeys[e.Item.ItemIndex].ToString()) == -1 ) objUserDefinedTable.AddUserDefinedField(ModuleID, txtFieldTitle.Text, chkVisible.Checked, cboFieldType.SelectedItem.Value); else objUserDefinedTable.UpdateUserDefinedField(int.Parse(grdFields.DataKeys[e.Item.ItemIndex].ToString()), txtFieldTitle.Text, chkVisible.Checked, cboFieldType.SelectedItem.Value); grdFields.EditItemIndex = -1; BindData(); } else { grdFields.EditItemIndex = -1; BindData(); } } /// <summary> /// Handles the Delete event of the grdFields control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param> public void grdFields_Delete(object sender, DataGridCommandEventArgs e) { UserDefinedTableDB objUserDefinedTable = new UserDefinedTableDB(); objUserDefinedTable.DeleteUserDefinedField(int.Parse(grdFields.DataKeys[e.Item.ItemIndex].ToString())); grdFields.EditItemIndex = -1; BindData(); } /// <summary> /// Handles the Move event of the grdFields control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"/> instance containing the event data.</param> public void grdFields_Move(object source, DataGridCommandEventArgs e) { UserDefinedTableDB objUserDefinedTable = new UserDefinedTableDB(); switch (e.CommandArgument.ToString()) { case "Up": objUserDefinedTable.UpdateUserDefinedFieldOrder(int.Parse(grdFields.DataKeys[e.Item.ItemIndex].ToString()), -1); BindData(); break; case "Down": objUserDefinedTable.UpdateUserDefinedFieldOrder(int.Parse(grdFields.DataKeys[e.Item.ItemIndex].ToString()), 1); BindData(); break; } } /// <summary> /// Handles the Click event of the cmdAddField control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void cmdAddField_Click(object sender, EventArgs e) { grdFields.EditItemIndex = 0; BindData(true); } /// <summary> /// Converts the data reader to data set. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> public DataSet ConvertDataReaderToDataSet( SqlDataReader reader) { DataSet dataSet = new DataSet(); DataTable schemaTable = reader.GetSchemaTable(); DataTable dataTable = new DataTable(); int intCounter; for ( intCounter = 0 ; intCounter <= schemaTable.Rows.Count - 1; intCounter++) { DataRow dataRow = schemaTable.Rows[intCounter]; string columnName = dataRow["ColumnName"].ToString(); DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]); dataTable.Columns.Add(column); } dataSet.Tables.Add(dataTable); try { while ( reader.Read()) { DataRow dataRow = dataTable.NewRow(); for (intCounter = 0; intCounter <= reader.FieldCount - 1; intCounter++) dataRow[intCounter] = reader.GetValue(intCounter); dataTable.Rows.Add(dataRow); } } finally { reader.Close(); //by Manu, fixed bug 807858 } return dataSet; } /// <summary> /// Binds the data. /// </summary> protected void BindData() { BindData(false); } /// <summary> /// Binds the data. /// </summary> /// <param name="blnInsertField">if set to <c>true</c> [BLN insert field].</param> protected void BindData(bool blnInsertField) { UserDefinedTableDB objUserDefinedTable = new UserDefinedTableDB(); SqlDataReader dr = objUserDefinedTable.GetUserDefinedFields(ModuleID); DataSet ds; ds = ConvertDataReaderToDataSet(dr); // inserting a new field if ( blnInsertField ) { DataRow row; row = ds.Tables[0].NewRow(); row["UserDefinedFieldID"] = "-1"; row["FieldTitle"] = string.Empty; row["Visible"] = true; row["FieldType"] = "String"; ds.Tables[0].Rows.InsertAt(row, 0); grdFields.EditItemIndex = 0; } grdFields.DataSource = ds; grdFields.DataBind(); } /// <summary> /// Handles the ItemCreated event of the grdFields control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridItemEventArgs"/> instance containing the event data.</param> protected void grdFields_ItemCreated(object sender, DataGridItemEventArgs e) { Control cmdDeleteUserDefinedField = e.Item.FindControl("cmdDeleteUserDefinedField"); if (cmdDeleteUserDefinedField != null ) { ImageButton imgBut = (ImageButton) cmdDeleteUserDefinedField; imgBut.Attributes.Add("onClick", "javascript: return confirm('Are you sure you wish to delete this field?')"); } } /// <summary> /// Gets the name of the field type. /// </summary> /// <param name="strFieldType">Type of the STR field.</param> /// <returns></returns> public string GetFieldTypeName(string strFieldType) { switch (strFieldType) { case "String" : return General.GetString("USERTABLE_TYPE_STRING", "Text",null); case "Int32" : return General.GetString("USERTABLE_TYPE_INT32", "Integer",null); case "Decimal" : return General.GetString("USERTABLE_TYPE_DECIMAL", "Decimal",null); case "DateTime" : return General.GetString("USERTABLE_TYPE_DATETIME", "Date",null); case "Boolean" : return General.GetString("USERTABLE_TYPE_BOOLEAN", "True/False",null); case "File" : return General.GetString("USERTABLE_TYPE_FILE", "File",null); case "Image" : return General.GetString("USERTABLE_TYPE_IMAGE", "Image",null); default : return General.GetString("USERTABLE_TYPE_STRING", "Text",null); } } /// <summary> /// Gets the index of the field type. /// </summary> /// <param name="strFieldType">Type of the STR field.</param> /// <returns></returns> public int GetFieldTypeIndex(string strFieldType) { switch (strFieldType) { case "String" : return 0; case "Int32" : return 1; case "Decimal" : return 2; case "DateTime" : return 3; case "Boolean" : return 4; case "File" : return 5; case "Image" : return 6; default: return 0; } } /// <summary> /// Ifs the visible. /// </summary> /// <param name="data">The data.</param> /// <param name="trueStr">The true STR.</param> /// <param name="falseStr">The false STR.</param> /// <returns></returns> public string IfVisible(object data, string trueStr, string falseStr) { bool check = bool.Parse(DataBinder.Eval(data, "Visible").ToString()); return (check ? this.CurrentTheme.GetImage(trueStr, trueStr + ".gif").ImageUrl : this.CurrentTheme.GetImage(falseStr, falseStr + ".gif").ImageUrl); } /// <summary> /// Gets the table types. /// </summary> /// <returns></returns> public UserDefinedTableType[] GetTableTypes() { UserDefinedTableType[] tableTypes = new UserDefinedTableType[7]; tableTypes[0] = new UserDefinedTableType(); tableTypes[0].TypeText =General.GetString("USERTABLE_TYPE_STRING", "Text",null); tableTypes[0].TypeValue = "String"; tableTypes[1] = new UserDefinedTableType(); tableTypes[1].TypeText =General.GetString("USERTABLE_TYPE_INT32", "Integer",null); tableTypes[1].TypeValue = "Int32"; tableTypes[2] = new UserDefinedTableType(); tableTypes[2].TypeText =General.GetString("USERTABLE_TYPE_DECIMAL", "Decimal",null); tableTypes[2].TypeValue = "Decimal"; tableTypes[3] = new UserDefinedTableType(); tableTypes[3].TypeText =General.GetString("USERTABLE_TYPE_DATETIME", "Date",null); tableTypes[3].TypeValue = "DateTime"; tableTypes[4] = new UserDefinedTableType(); tableTypes[4].TypeText =General.GetString("USERTABLE_TYPE_BOOLEAN", "True/False",null); tableTypes[4].TypeValue = "Boolean"; tableTypes[5] = new UserDefinedTableType(); tableTypes[5].TypeText =General.GetString("USERTABLE_TYPE_FILE", "File",null); tableTypes[5].TypeValue = "File"; tableTypes[6] = new UserDefinedTableType(); tableTypes[6].TypeText =General.GetString("USERTABLE_TYPE_IMAGE", "Image",null); tableTypes[6].TypeValue = "Image"; return tableTypes; } #region Web Form Designer generated code /// <summary> /// Raises OnInitEvent /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> override protected void OnInit(EventArgs e) { this.Load += new EventHandler(this.Page_Load); base.OnInit(e); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace SharpCompress.Compressors.Deflate64 { internal static class FastEncoderStatics { // static information for encoding, DO NOT MODIFY internal static ReadOnlySpan<byte> FAST_ENCODER_TREE_STRUCTURE_DATA => new byte[] { 0xec,0xbd,0x07,0x60,0x1c,0x49,0x96,0x25,0x26,0x2f,0x6d,0xca, 0x7b,0x7f,0x4a,0xf5,0x4a,0xd7,0xe0,0x74,0xa1,0x08,0x80,0x60, 0x13,0x24,0xd8,0x90,0x40,0x10,0xec,0xc1,0x88,0xcd,0xe6,0x92, 0xec,0x1d,0x69,0x47,0x23,0x29,0xab,0x2a,0x81,0xca,0x65,0x56, 0x65,0x5d,0x66,0x16,0x40,0xcc,0xed,0x9d,0xbc,0xf7,0xde,0x7b, 0xef,0xbd,0xf7,0xde,0x7b,0xef,0xbd,0xf7,0xba,0x3b,0x9d,0x4e, 0x27,0xf7,0xdf,0xff,0x3f,0x5c,0x66,0x64,0x01,0x6c,0xf6,0xce, 0x4a,0xda,0xc9,0x9e,0x21,0x80,0xaa,0xc8,0x1f,0x3f,0x7e,0x7c, 0x1f,0x3f }; internal static ReadOnlySpan<byte> B_FINAL_FAST_ENCODER_TREE_STRUCTURE_DATA => new byte[] { 0xed,0xbd,0x07,0x60,0x1c,0x49,0x96,0x25,0x26,0x2f,0x6d,0xca, 0x7b,0x7f,0x4a,0xf5,0x4a,0xd7,0xe0,0x74,0xa1,0x08,0x80,0x60, 0x13,0x24,0xd8,0x90,0x40,0x10,0xec,0xc1,0x88,0xcd,0xe6,0x92, 0xec,0x1d,0x69,0x47,0x23,0x29,0xab,0x2a,0x81,0xca,0x65,0x56, 0x65,0x5d,0x66,0x16,0x40,0xcc,0xed,0x9d,0xbc,0xf7,0xde,0x7b, 0xef,0xbd,0xf7,0xde,0x7b,0xef,0xbd,0xf7,0xba,0x3b,0x9d,0x4e, 0x27,0xf7,0xdf,0xff,0x3f,0x5c,0x66,0x64,0x01,0x6c,0xf6,0xce, 0x4a,0xda,0xc9,0x9e,0x21,0x80,0xaa,0xc8,0x1f,0x3f,0x7e,0x7c, 0x1f,0x3f }; // Output a currentMatch with length matchLen (>= MIN_MATCH) and displacement matchPos // // Optimisation: unlike the other encoders, here we have an array of codes for each currentMatch // length (not just each currentMatch length slot), complete with all the extra bits filled in, in // a single array element. // // There are many advantages to doing this: // // 1. A single array lookup on g_FastEncoderLiteralCodeInfo, instead of separate array lookups // on g_LengthLookup (to get the length slot), g_FastEncoderLiteralTreeLength, // g_FastEncoderLiteralTreeCode, g_ExtraLengthBits, and g_BitMask // // 2. The array is an array of ULONGs, so no access penalty, unlike for accessing those USHORT // code arrays in the other encoders (although they could be made into ULONGs with some // modifications to the source). // // Note, if we could guarantee that codeLen <= 16 always, then we could skip an if statement here. // // A completely different optimisation is used for the distance codes since, obviously, a table for // all 8192 distances combining their extra bits is not feasible. The distance codeinfo table is // made up of code[], len[] and # extraBits for this code. // // The advantages are similar to the above; a ULONG array instead of a USHORT and BYTE array, better // cache locality, fewer memory operations. // // Encoding information for literal and Length. // The least 5 significant bits are the length // and the rest is the code bits. internal static readonly uint[] FAST_ENCODER_LITERAL_CODE_INFO = { 0x0000d7ee,0x0004d7ee,0x0002d7ee,0x0006d7ee,0x0001d7ee,0x0005d7ee,0x0003d7ee, 0x0007d7ee,0x000037ee,0x0000c7ec,0x00000126,0x000437ee,0x000237ee,0x000637ee, 0x000137ee,0x000537ee,0x000337ee,0x000737ee,0x0000b7ee,0x0004b7ee,0x0002b7ee, 0x0006b7ee,0x0001b7ee,0x0005b7ee,0x0003b7ee,0x0007b7ee,0x000077ee,0x000477ee, 0x000277ee,0x000677ee,0x000017ed,0x000177ee,0x00000526,0x000577ee,0x000023ea, 0x0001c7ec,0x000377ee,0x000777ee,0x000217ed,0x000063ea,0x00000b68,0x00000ee9, 0x00005beb,0x000013ea,0x00000467,0x00001b68,0x00000c67,0x00002ee9,0x00000768, 0x00001768,0x00000f68,0x00001ee9,0x00001f68,0x00003ee9,0x000053ea,0x000001e9, 0x000000e8,0x000021e9,0x000011e9,0x000010e8,0x000031e9,0x000033ea,0x000008e8, 0x0000f7ee,0x0004f7ee,0x000018e8,0x000009e9,0x000004e8,0x000029e9,0x000014e8, 0x000019e9,0x000073ea,0x0000dbeb,0x00000ce8,0x00003beb,0x0002f7ee,0x000039e9, 0x00000bea,0x000005e9,0x00004bea,0x000025e9,0x000027ec,0x000015e9,0x000035e9, 0x00000de9,0x00002bea,0x000127ec,0x0000bbeb,0x0006f7ee,0x0001f7ee,0x0000a7ec, 0x00007beb,0x0005f7ee,0x0000fbeb,0x0003f7ee,0x0007f7ee,0x00000fee,0x00000326, 0x00000267,0x00000a67,0x00000667,0x00000726,0x00001ce8,0x000002e8,0x00000e67, 0x000000a6,0x0001a7ec,0x00002de9,0x000004a6,0x00000167,0x00000967,0x000002a6, 0x00000567,0x000117ed,0x000006a6,0x000001a6,0x000005a6,0x00000d67,0x000012e8, 0x00000ae8,0x00001de9,0x00001ae8,0x000007eb,0x000317ed,0x000067ec,0x000097ed, 0x000297ed,0x00040fee,0x00020fee,0x00060fee,0x00010fee,0x00050fee,0x00030fee, 0x00070fee,0x00008fee,0x00048fee,0x00028fee,0x00068fee,0x00018fee,0x00058fee, 0x00038fee,0x00078fee,0x00004fee,0x00044fee,0x00024fee,0x00064fee,0x00014fee, 0x00054fee,0x00034fee,0x00074fee,0x0000cfee,0x0004cfee,0x0002cfee,0x0006cfee, 0x0001cfee,0x0005cfee,0x0003cfee,0x0007cfee,0x00002fee,0x00042fee,0x00022fee, 0x00062fee,0x00012fee,0x00052fee,0x00032fee,0x00072fee,0x0000afee,0x0004afee, 0x0002afee,0x0006afee,0x0001afee,0x0005afee,0x0003afee,0x0007afee,0x00006fee, 0x00046fee,0x00026fee,0x00066fee,0x00016fee,0x00056fee,0x00036fee,0x00076fee, 0x0000efee,0x0004efee,0x0002efee,0x0006efee,0x0001efee,0x0005efee,0x0003efee, 0x0007efee,0x00001fee,0x00041fee,0x00021fee,0x00061fee,0x00011fee,0x00051fee, 0x00031fee,0x00071fee,0x00009fee,0x00049fee,0x00029fee,0x00069fee,0x00019fee, 0x00059fee,0x00039fee,0x00079fee,0x00005fee,0x00045fee,0x00025fee,0x00065fee, 0x00015fee,0x00055fee,0x00035fee,0x00075fee,0x0000dfee,0x0004dfee,0x0002dfee, 0x0006dfee,0x0001dfee,0x0005dfee,0x0003dfee,0x0007dfee,0x00003fee,0x00043fee, 0x00023fee,0x00063fee,0x00013fee,0x00053fee,0x00033fee,0x00073fee,0x0000bfee, 0x0004bfee,0x0002bfee,0x0006bfee,0x0001bfee,0x0005bfee,0x0003bfee,0x0007bfee, 0x00007fee,0x00047fee,0x00027fee,0x00067fee,0x00017fee,0x000197ed,0x000397ed, 0x000057ed,0x00057fee,0x000257ed,0x00037fee,0x000157ed,0x00077fee,0x000357ed, 0x0000ffee,0x0004ffee,0x0002ffee,0x0006ffee,0x0001ffee,0x00000084,0x00000003, 0x00000184,0x00000044,0x00000144,0x000000c5,0x000002c5,0x000001c5,0x000003c6, 0x000007c6,0x00000026,0x00000426,0x000003a7,0x00000ba7,0x000007a7,0x00000fa7, 0x00000227,0x00000627,0x00000a27,0x00000e27,0x00000068,0x00000868,0x00001068, 0x00001868,0x00000369,0x00001369,0x00002369,0x00003369,0x000006ea,0x000026ea, 0x000046ea,0x000066ea,0x000016eb,0x000036eb,0x000056eb,0x000076eb,0x000096eb, 0x0000b6eb,0x0000d6eb,0x0000f6eb,0x00003dec,0x00007dec,0x0000bdec,0x0000fdec, 0x00013dec,0x00017dec,0x0001bdec,0x0001fdec,0x00006bed,0x0000ebed,0x00016bed, 0x0001ebed,0x00026bed,0x0002ebed,0x00036bed,0x0003ebed,0x000003ec,0x000043ec, 0x000083ec,0x0000c3ec,0x000103ec,0x000143ec,0x000183ec,0x0001c3ec,0x00001bee, 0x00009bee,0x00011bee,0x00019bee,0x00021bee,0x00029bee,0x00031bee,0x00039bee, 0x00041bee,0x00049bee,0x00051bee,0x00059bee,0x00061bee,0x00069bee,0x00071bee, 0x00079bee,0x000167f0,0x000367f0,0x000567f0,0x000767f0,0x000967f0,0x000b67f0, 0x000d67f0,0x000f67f0,0x001167f0,0x001367f0,0x001567f0,0x001767f0,0x001967f0, 0x001b67f0,0x001d67f0,0x001f67f0,0x000087ef,0x000187ef,0x000287ef,0x000387ef, 0x000487ef,0x000587ef,0x000687ef,0x000787ef,0x000887ef,0x000987ef,0x000a87ef, 0x000b87ef,0x000c87ef,0x000d87ef,0x000e87ef,0x000f87ef,0x0000e7f0,0x0002e7f0, 0x0004e7f0,0x0006e7f0,0x0008e7f0,0x000ae7f0,0x000ce7f0,0x000ee7f0,0x0010e7f0, 0x0012e7f0,0x0014e7f0,0x0016e7f0,0x0018e7f0,0x001ae7f0,0x001ce7f0,0x001ee7f0, 0x0005fff3,0x000dfff3,0x0015fff3,0x001dfff3,0x0025fff3,0x002dfff3,0x0035fff3, 0x003dfff3,0x0045fff3,0x004dfff3,0x0055fff3,0x005dfff3,0x0065fff3,0x006dfff3, 0x0075fff3,0x007dfff3,0x0085fff3,0x008dfff3,0x0095fff3,0x009dfff3,0x00a5fff3, 0x00adfff3,0x00b5fff3,0x00bdfff3,0x00c5fff3,0x00cdfff3,0x00d5fff3,0x00ddfff3, 0x00e5fff3,0x00edfff3,0x00f5fff3,0x00fdfff3,0x0003fff3,0x000bfff3,0x0013fff3, 0x001bfff3,0x0023fff3,0x002bfff3,0x0033fff3,0x003bfff3,0x0043fff3,0x004bfff3, 0x0053fff3,0x005bfff3,0x0063fff3,0x006bfff3,0x0073fff3,0x007bfff3,0x0083fff3, 0x008bfff3,0x0093fff3,0x009bfff3,0x00a3fff3,0x00abfff3,0x00b3fff3,0x00bbfff3, 0x00c3fff3,0x00cbfff3,0x00d3fff3,0x00dbfff3,0x00e3fff3,0x00ebfff3,0x00f3fff3, 0x00fbfff3,0x0007fff3,0x000ffff3,0x0017fff3,0x001ffff3,0x0027fff3,0x002ffff3, 0x0037fff3,0x003ffff3,0x0047fff3,0x004ffff3,0x0057fff3,0x005ffff3,0x0067fff3, 0x006ffff3,0x0077fff3,0x007ffff3,0x0087fff3,0x008ffff3,0x0097fff3,0x009ffff3, 0x00a7fff3,0x00affff3,0x00b7fff3,0x00bffff3,0x00c7fff3,0x00cffff3,0x00d7fff3, 0x00dffff3,0x00e7fff3,0x00effff3,0x00f7fff3,0x00fffff3,0x0001e7f1,0x0003e7f1, 0x0005e7f1,0x0007e7f1,0x0009e7f1,0x000be7f1,0x000de7f1,0x000fe7f1,0x0011e7f1, 0x0013e7f1,0x0015e7f1,0x0017e7f1,0x0019e7f1,0x001be7f1,0x001de7f1,0x001fe7f1, 0x0021e7f1,0x0023e7f1,0x0025e7f1,0x0027e7f1,0x0029e7f1,0x002be7f1,0x002de7f1, 0x002fe7f1,0x0031e7f1,0x0033e7f1,0x0035e7f1,0x0037e7f1,0x0039e7f1,0x003be7f1, 0x003de7f1,0x000047eb }; internal static readonly uint[] FAST_ENCODER_DISTANCE_CODE_INFO = { 0x00000f06,0x0001ff0a,0x0003ff0b,0x0007ff0b,0x0000ff19,0x00003f18,0x0000bf28, 0x00007f28,0x00001f37,0x00005f37,0x00000d45,0x00002f46,0x00000054,0x00001d55, 0x00000864,0x00000365,0x00000474,0x00001375,0x00000c84,0x00000284,0x00000a94, 0x00000694,0x00000ea4,0x000001a4,0x000009b4,0x00000bb5,0x000005c4,0x00001bc5, 0x000007d5,0x000017d5,0x00000000,0x00000100 }; internal static readonly uint[] BIT_MASK = { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 }; internal static readonly byte[] EXTRA_LENGTH_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; internal static readonly byte[] EXTRA_DISTANCE_BITS = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0 }; internal const int NUM_CHARS = 256; internal const int NUM_LENGTH_BASE_CODES = 29; internal const int NUM_DIST_BASE_CODES = 30; internal const uint FAST_ENCODER_POST_TREE_BIT_BUF = 0x0022; internal const int FAST_ENCODER_POST_TREE_BIT_COUNT = 9; internal const uint NO_COMPRESSION_HEADER = 0x0; internal const int NO_COMPRESSION_HEADER_BIT_COUNT = 3; internal const uint B_FINAL_NO_COMPRESSION_HEADER = 0x1; internal const int B_FINAL_NO_COMPRESSION_HEADER_BIT_COUNT = 3; internal const int MAX_CODE_LEN = 16; private static readonly byte[] S_DIST_LOOKUP = CreateDistanceLookup(); private static byte[] CreateDistanceLookup() { byte[] result = new byte[512]; // Generate the global slot tables which allow us to convert a distance // (0..32K) to a distance slot (0..29) // // Distance table // Extra Extra Extra // Code Bits Dist Code Bits Dist Code Bits Distance // ---- ---- ---- ---- ---- ------ ---- ---- -------- // 0 0 1 10 4 33-48 20 9 1025-1536 // 1 0 2 11 4 49-64 21 9 1537-2048 // 2 0 3 12 5 65-96 22 10 2049-3072 // 3 0 4 13 5 97-128 23 10 3073-4096 // 4 1 5,6 14 6 129-192 24 11 4097-6144 // 5 1 7,8 15 6 193-256 25 11 6145-8192 // 6 2 9-12 16 7 257-384 26 12 8193-12288 // 7 2 13-16 17 7 385-512 27 12 12289-16384 // 8 3 17-24 18 8 513-768 28 13 16385-24576 // 9 3 25-32 19 8 769-1024 29 13 24577-32768 // Initialize the mapping length (0..255) -> length code (0..28) //int length = 0; //for (code = 0; code < FastEncoderStatics.NumLengthBaseCodes-1; code++) { // for (int n = 0; n < (1 << FastEncoderStatics.ExtraLengthBits[code]); n++) // lengthLookup[length++] = (byte) code; //} //lengthLookup[length-1] = (byte) code; // Initialize the mapping dist (0..32K) -> dist code (0..29) int dist = 0; int code; for (code = 0; code < 16; code++) { for (int n = 0; n < (1 << EXTRA_DISTANCE_BITS[code]); n++) { result[dist++] = (byte)code; } } dist >>= 7; // from now on, all distances are divided by 128 for (; code < NUM_DIST_BASE_CODES; code++) { for (int n = 0; n < (1 << (EXTRA_DISTANCE_BITS[code] - 7)); n++) { result[256 + dist++] = (byte)code; } } return result; } // Return the position slot (0...29) of a match offset (0...32767) internal static int GetSlot(int pos) => S_DIST_LOOKUP[((pos) < 256) ? (pos) : (256 + ((pos) >> 7))]; // Reverse 'length' of the bits in code public static uint BitReverse(uint code, int length) { uint newCode = 0; Debug.Assert(length > 0 && length <= 16, "Invalid len"); do { newCode |= (code & 1); newCode <<= 1; code >>= 1; } while (--length > 0); return newCode >> 1; } } }
using System; using System.Xml; using System.Collections; using System.Collections.Generic; namespace Zeus { /// <summary> /// Summary description for InputItemCollection. /// </summary> public class SavedTemplateInputCollection : ICollection, IDictionary { private SortedList _hash = new SortedList(); private List<string> _filesChanged; private ApplyOverrideDataDelegate _applyOverrideDataDelegate; public SavedTemplateInputCollection() { } public ApplyOverrideDataDelegate ApplyOverrideDataDelegate { set { if (_applyOverrideDataDelegate != value) { _applyOverrideDataDelegate = value; foreach (SavedTemplateInput item in this._hash.Values) { item.ApplyOverrideDataDelegate = _applyOverrideDataDelegate; } } } } public SavedTemplateInput this[string objectName] { get { if (_hash.ContainsKey(objectName)) { SavedTemplateInput item = _hash[objectName] as SavedTemplateInput; item.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; return item; } else return null; } set { value.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; _hash[objectName] = value; } } public List<string> SavedFiles { get { if (_filesChanged == null) _filesChanged = new List<string>(); return this._filesChanged; } } public void Add(SavedTemplateInput item) { item.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; this._hash[item.SavedObjectName] = item; } public void Remove(SavedTemplateInput item) { Remove(item.SavedObjectName); } public void Remove(string key) { if (_hash.ContainsKey(key)) _hash.Remove(key); } public bool Contains(string objectName) { return _hash.ContainsKey(objectName); } public void Execute(int timeout, ILog log) { foreach (SavedTemplateInput item in this) { item.Execute(timeout, log); foreach (string file in item.SavedFiles) { if (!SavedFiles.Contains(file)) SavedFiles.Add(file); } } } public void BuildXML(XmlTextWriter xml) { if (this.Count > 0) { xml.WriteStartElement("objects"); foreach (SavedTemplateInput item in this.Values) { item.BuildXML(xml); } xml.WriteEndElement(); } } #region ICollection Members public bool IsSynchronized { get { return _hash.IsSynchronized; } } public int Count { get { return _hash.Count; } } public void CopyTo(Array array, int index) { _hash.CopyTo(array, index); } public object SyncRoot { get { return _hash.SyncRoot; } } #endregion #region IDictionary Members public bool IsReadOnly { get { return _hash.IsReadOnly; } } IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return _hash.GetEnumerator(); } object System.Collections.IDictionary.this[object key] { get { SavedTemplateInput item = _hash[key] as SavedTemplateInput; item.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; return item; } set { SavedTemplateInput item = value as SavedTemplateInput; item.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; _hash[key] = item; } } public void Remove(object key) { _hash.Remove(key); } bool System.Collections.IDictionary.Contains(object key) { return _hash.Contains(key); } public void Clear() { _hash.Clear(); } public ICollection Values { get { return _hash.Values; } } void System.Collections.IDictionary.Add(object key, object value) { SavedTemplateInput item = value as SavedTemplateInput; item.ApplyOverrideDataDelegate = this._applyOverrideDataDelegate; _hash.Add(key, item); } public ICollection Keys { get { return _hash.Keys; } } public bool IsFixedSize { get { return _hash.IsFixedSize; } } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return _hash.Values.GetEnumerator(); } #endregion } }
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Signum.React.Facades; using System.Collections; namespace Signum.React.JsonModelValidators; //don't make it public! use services.AddSignumValidation(); instead internal class SignumObjectModelValidator : IObjectModelValidator { private readonly IModelMetadataProvider _modelMetadataProvider; private readonly ValidatorCache _validatorCache; private readonly CompositeModelValidatorProvider _validatorProvider; /// <summary> /// Initializes a new instance of <see cref="ObjectModelValidator"/>. /// </summary> /// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param> /// <param name="validatorProviders">The list of <see cref="IModelValidatorProvider"/>.</param> public SignumObjectModelValidator( IModelMetadataProvider modelMetadataProvider, IList<IModelValidatorProvider> validatorProviders) { if (modelMetadataProvider == null) { throw new ArgumentNullException(nameof(modelMetadataProvider)); } if (validatorProviders == null) { throw new ArgumentNullException(nameof(validatorProviders)); } _modelMetadataProvider = modelMetadataProvider; _validatorCache = new ValidatorCache(); _validatorProvider = new CompositeModelValidatorProvider(validatorProviders); } /// <inheritdoc /> public virtual void Validate( ActionContext actionContext, ValidationStateDictionary? validationState, string prefix, object? model) { var visitor = GetValidationVisitor( actionContext, _validatorProvider, _validatorCache, _modelMetadataProvider, validationState!); var metadata = model == null ? null : _modelMetadataProvider.GetMetadataForType(model.GetType()); visitor.Validate(metadata, prefix, model, alwaysValidateAtTopLevel: false); } /// <summary> /// Validates the provided object model. /// If <paramref name="model"/> is <see langword="null"/> and the <paramref name="metadata"/>'s /// <see cref="ModelMetadata.IsRequired"/> is <see langword="true"/>, will add one or more /// model state errors that <see cref="Validate(ActionContext, ValidationStateDictionary, string, object)"/> /// would not. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/>.</param> /// <param name="validationState">The <see cref="ValidationStateDictionary"/>.</param> /// <param name="prefix">The model prefix key.</param> /// <param name="model">The model object.</param> /// <param name="metadata">The <see cref="ModelMetadata"/>.</param> public virtual void Validate( ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model, ModelMetadata metadata) { var visitor = GetValidationVisitor( actionContext, _validatorProvider, _validatorCache, _modelMetadataProvider, validationState); visitor.Validate(metadata, prefix, model, alwaysValidateAtTopLevel: metadata.IsRequired); } /// <summary> /// Gets a <see cref="ValidationVisitor"/> that traverses the object model graph and performs validation. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/>.</param> /// <param name="validatorProvider">The <see cref="IModelValidatorProvider"/>.</param> /// <param name="validatorCache">The <see cref="ValidatorCache"/>.</param> /// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param> /// <param name="validationState">The <see cref="ValidationStateDictionary"/>.</param> /// <returns>A <see cref="ValidationVisitor"/> which traverses the object model graph.</returns> public ValidationVisitor GetValidationVisitor( ActionContext actionContext, IModelValidatorProvider validatorProvider, ValidatorCache validatorCache, IModelMetadataProvider metadataProvider, ValidationStateDictionary validationState) { return new SignumValidationVisitor( actionContext, validatorProvider, validatorCache, metadataProvider, validationState); } } internal class SignumValidationVisitor : ValidationVisitor { public SignumValidationVisitor( ActionContext actionContext, IModelValidatorProvider validatorProvider, ValidatorCache validatorCache, IModelMetadataProvider metadataProvider, ValidationStateDictionary validationState) : base( actionContext, validatorProvider, validatorCache, metadataProvider, validationState) { } protected override bool VisitComplexType(IValidationStrategy defaultStrategy) { bool? customValidate = SignumValidate(); if (customValidate.HasValue) return customValidate.Value; return base.VisitComplexType(defaultStrategy); } private bool? SignumValidate() { if (this.Model is Lite<Entity> lite) return ValidateLite(lite); if (this.Model is ModifiableEntity mod) return ValidateModifiableEntity(mod); if (this.Model is IMListPrivate mlist) return ValidateMList(mlist); return null; } private bool ValidateLite(Lite<Entity> lite) { if (lite.EntityOrNull == null) return true; if (this.CurrentPath.Push(lite.EntityOrNull)) { using (StateManager.Recurse(this, this.Key + ".entity", null, lite.EntityOrNull, null)) { return this.ValidateModifiableEntity(lite.EntityOrNull); } } return true; } private bool ValidateMList(IMListPrivate mlist) { bool isValid = true; Type elementType = mlist.GetType().ElementType()!; int i = 0; foreach (object? element in (IEnumerable)mlist) { if (element != null && this.CurrentPath.Push(element)) { using (StateManager.Recurse(this, this.Key + "[" + (i++) + "].element", null, element, null)) { if (element is ModifiableEntity me) isValid &= ValidateModifiableEntity(me); else if (element is Lite<Entity> lite) isValid &= ValidateLite(lite); else isValid &= true; } } } return isValid; } private bool ValidateModifiableEntity(ModifiableEntity mod) { using (Entities.Validator.ModelBinderScope()) { bool isValid = true; var entity = mod as Entity; using (entity == null ? null : entity.Mixins.OfType<CorruptMixin>().Any(c => c.Corrupt) ? Corruption.AllowScope() : Corruption.DenyScope()) { foreach (var kvp in SignumServer.WebEntityJsonConverterFactory.GetPropertyConverters(mod.GetType())) { if (kvp.Value.AvoidValidate) continue; string? error = kvp.Value.PropertyValidator!.PropertyCheck(mod); if (error != null) { isValid = false; ModelState.AddModelError(this.Key + "." + kvp.Key, error); } var val = kvp.Value.GetValue!(mod); if (val != null && this.CurrentPath.Push(val)) { using (StateManager.Recurse(this, this.Key + "." + kvp.Key, null, val, null)) { if (this.SignumValidate() == false) { isValid = false; } } } } if (entity != null && entity.Mixins.Any()) { foreach (var mixin in entity.Mixins) { if (this.CurrentPath.Push(mixin)) { using (StateManager.Recurse(this, this.Key + ".mixins[" + mixin.GetType().Name + "]", null, mixin, null)) { isValid &= ValidateModifiableEntity(mixin); } } } } } return isValid; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G08Level1111 (editable child object).<br/> /// This is a generated base class of <see cref="G08Level1111"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G09Level11111Objects"/> of type <see cref="G09Level11111Coll"/> (1:M relation to <see cref="G10Level11111"/>)<br/> /// This class is an item of <see cref="G07Level1111Coll"/> collection. /// </remarks> [Serializable] public partial class G08Level1111 : BusinessBase<G08Level1111> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Level_1_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_1_ID, "Level_1_1_1_1 ID"); /// <summary> /// Gets the Level_1_1_1_1 ID. /// </summary> /// <value>The Level_1_1_1_1 ID.</value> public int Level_1_1_1_1_ID { get { return GetProperty(Level_1_1_1_1_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Name, "Level_1_1_1_1 Name"); /// <summary> /// Gets or sets the Level_1_1_1_1 Name. /// </summary> /// <value>The Level_1_1_1_1 Name.</value> public string Level_1_1_1_1_Name { get { return GetProperty(Level_1_1_1_1_NameProperty); } set { SetProperty(Level_1_1_1_1_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09Level11111SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G09Level11111Child> G09Level11111SingleObjectProperty = RegisterProperty<G09Level11111Child>(p => p.G09Level11111SingleObject, "G09 Level11111 Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G09 Level11111 Single Object ("self load" child property). /// </summary> /// <value>The G09 Level11111 Single Object.</value> public G09Level11111Child G09Level11111SingleObject { get { return GetProperty(G09Level11111SingleObjectProperty); } private set { LoadProperty(G09Level11111SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09Level11111ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G09Level11111ReChild> G09Level11111ASingleObjectProperty = RegisterProperty<G09Level11111ReChild>(p => p.G09Level11111ASingleObject, "G09 Level11111 ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the G09 Level11111 ASingle Object ("self load" child property). /// </summary> /// <value>The G09 Level11111 ASingle Object.</value> public G09Level11111ReChild G09Level11111ASingleObject { get { return GetProperty(G09Level11111ASingleObjectProperty); } private set { LoadProperty(G09Level11111ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G09Level11111Objects"/> property. /// </summary> public static readonly PropertyInfo<G09Level11111Coll> G09Level11111ObjectsProperty = RegisterProperty<G09Level11111Coll>(p => p.G09Level11111Objects, "G09 Level11111 Objects", RelationshipTypes.Child); /// <summary> /// Gets the G09 Level11111 Objects ("self load" child property). /// </summary> /// <value>The G09 Level11111 Objects.</value> public G09Level11111Coll G09Level11111Objects { get { return GetProperty(G09Level11111ObjectsProperty); } private set { LoadProperty(G09Level11111ObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G08Level1111"/> object. /// </summary> /// <returns>A reference to the created <see cref="G08Level1111"/> object.</returns> internal static G08Level1111 NewG08Level1111() { return DataPortal.CreateChild<G08Level1111>(); } /// <summary> /// Factory method. Loads a <see cref="G08Level1111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="G08Level1111"/> object.</returns> internal static G08Level1111 GetG08Level1111(SafeDataReader dr) { G08Level1111 obj = new G08Level1111(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G08Level1111"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private G08Level1111() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G08Level1111"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Level_1_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G09Level11111SingleObjectProperty, DataPortal.CreateChild<G09Level11111Child>()); LoadProperty(G09Level11111ASingleObjectProperty, DataPortal.CreateChild<G09Level11111ReChild>()); LoadProperty(G09Level11111ObjectsProperty, DataPortal.CreateChild<G09Level11111Coll>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G08Level1111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_1_ID")); LoadProperty(Level_1_1_1_1_NameProperty, dr.GetString("Level_1_1_1_1_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(G09Level11111SingleObjectProperty, G09Level11111Child.GetG09Level11111Child(Level_1_1_1_1_ID)); LoadProperty(G09Level11111ASingleObjectProperty, G09Level11111ReChild.GetG09Level11111ReChild(Level_1_1_1_1_ID)); LoadProperty(G09Level11111ObjectsProperty, G09Level11111Coll.GetG09Level11111Coll(Level_1_1_1_1_ID)); } /// <summary> /// Inserts a new <see cref="G08Level1111"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG08Level1111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Level_1_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_1_ID"].Value); } FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G08Level1111"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG08Level1111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Name", ReadProperty(Level_1_1_1_1_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G08Level1111"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteG08Level1111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", ReadProperty(Level_1_1_1_1_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(G09Level11111SingleObjectProperty, DataPortal.CreateChild<G09Level11111Child>()); LoadProperty(G09Level11111ASingleObjectProperty, DataPortal.CreateChild<G09Level11111ReChild>()); LoadProperty(G09Level11111ObjectsProperty, DataPortal.CreateChild<G09Level11111Coll>()); } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml.Linq; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable IntroduceOptionalParameters.Global #if BUILD_PEANUTBUTTER_INTERNAL namespace Imported.PeanutButter.Utils #else namespace PeanutButter.Utils #endif { /// <summary> /// Provides convenience functions to get reasonable string representations of objects and collections /// </summary> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif static class Stringifier { /// <summary> /// Provides a reasonable human-readable string representation of a collection /// </summary> /// <param name="objs"></param> /// <returns>Human-readable representation of collection</returns> public static string Stringify<T>( this IEnumerable<T> objs) { if (typeof(T) == typeof(char)) { return objs == null ? "(null)" : $"\"{objs as string}\""; } return StringifyCollectionInternal(objs, "null", 0); } private static string StringifyCollectionInternal<T>( IEnumerable<T> objs, string nullRepresentation, int level ) { return objs == null ? "(null collection)" : $"[ {string.Join(", ", objs.Select(o => Stringify(o, nullRepresentation, level)))} ]"; } /// <summary> /// Provides a reasonable human-readable string representation of an object /// </summary> /// <param name="obj"></param> /// <returns>Human-readable representation of object</returns> public static string Stringify( this object obj) { return Stringify(obj, "null"); } /// <summary> /// Provides a reasonable human-readable string representation of an object /// </summary> /// <param name="obj"></param> /// <param name="nullRepresentation">How to represent null values - defaults to the string "null"</param> /// <returns>Human-readable representation of object</returns> public static string Stringify( object obj, string nullRepresentation) { return Stringify(obj, nullRepresentation, 0); } private static string Stringify( object obj, string nullRepresentation, int level) { return SafeStringifier(obj, level, nullRepresentation ?? "null"); } private const int MAX_STRINGIFY_DEPTH = 10; private const int INDENT_SIZE = 2; private static readonly Dictionary<Type, Func<object, string>> _primitiveStringifiers = new Dictionary<Type, Func<object, string>>() { [typeof(string)] = o => $"\"{o}\"", [typeof(bool)] = o => o.ToString().ToLower() }; private static readonly string[] _ignoreAssembliesByName = { "mscorlib" }; private static readonly Tuple<Func<object, int, bool>, Func<object, int, string, string>>[] _strategies = { MakeStrategy(IsNull, PrintNull), MakeStrategy(IsDateTime, StringifyDateTime), MakeStrategy(IsPrimitive, StringifyPrimitive), MakeStrategy(IsEnum, StringifyEnum), MakeStrategy(IsType, StringifyType), MakeStrategy(IsEnumerable, StringifyCollection), MakeStrategy(IsXDocument, StringifyXDocument), MakeStrategy(IsXElement, StringifyXElement), MakeStrategy(Default, StringifyJsonLike), MakeStrategy(LastPass, JustToStringIt) }; private static string StringifyXElement( object arg1, int arg2, string arg3) { return ((XElement) arg1).ToString(); } private static bool IsXElement( object arg1, int arg2) { return arg1 is XElement; } private static string StringifyXDocument( object arg1, int arg2, string arg3) { return ((XDocument) arg1).ToString(); } private static bool IsXDocument( object obj, int level) { return obj is XDocument; } private static string StringifyType( object obj, int level, string nullRep) { return (obj as Type).PrettyName(); } private static bool IsType( object obj, int level) { return obj is Type; } private static string StringifyDateTime( object obj, int level, string nullRep) { var dt = (DateTime) obj; return $"{dt.ToString(CultureInfo.InvariantCulture)} ({dt.Kind})"; } private static bool IsDateTime( object obj, int level) { return obj is DateTime; } private static string StringifyCollection( object obj, int level, string nullRep) { var itemType = obj.GetType().TryGetEnumerableItemType() ?? throw new Exception($"{obj.GetType()} is not IEnumerable<T>"); var method = typeof(Stringifier) .GetMethod(nameof(StringifyCollectionInternal), BindingFlags.NonPublic | BindingFlags.Static); if (method == null) throw new InvalidOperationException( $"No non-public, static '{nameof(StringifyCollectionInternal)}' method found on {typeof(Stringifier).PrettyName()}" ); var specific = method.MakeGenericMethod(itemType); return (string) (specific.Invoke(null, new[] { obj, nullRep, level })); } private static bool IsEnumerable( object obj, int level) { return obj.GetType().ImplementsEnumerableGenericType(); } private static string StringifyEnum( object obj, int level, string nullRepresentation) { return obj.ToString(); } private static bool IsEnum( object obj, int level) { #if NETSTANDARD return obj.GetType().GetTypeInfo().IsEnum; #else return obj.GetType().IsEnum; #endif } private static string JustToStringIt( object obj, int level, string nullRepresentation) { try { return obj.ToString(); } catch { return $"{{{obj.GetType()}}}"; } } private static bool LastPass( object arg1, int arg2) { return true; } private static string PrintNull( object obj, int level, string nullRepresentation) { return nullRepresentation; } private static bool IsNull( object obj, int level) { return obj == null; } private static Tuple<Func<object, int, bool>, Func<object, int, string, string>> MakeStrategy( Func<object, int, bool> matcher, Func<object, int, string, string> writer ) { return Tuple.Create(matcher, writer); } private static bool IsPrimitive( object obj, int level) { return level >= MAX_STRINGIFY_DEPTH || Types.PrimitivesAndImmutables.Contains(obj.GetType()); } private static bool Default( object obj, int level) { return true; } private static string SafeStringifier( object obj, int level, string nullRepresentation) { if (level >= MAX_STRINGIFY_DEPTH) { return StringifyPrimitive(obj, level, nullRepresentation); } return _strategies.Aggregate( null as string, ( acc, cur) => acc ?? ApplyStrategy( cur.Item1, cur.Item2, obj, level, nullRepresentation ) ); } private static string ApplyStrategy( Func<object, int, bool> matcher, Func<object, int, string, string> strategy, object obj, int level, string nullRepresentation) { try { var isMatched = matcher(obj, level); return isMatched ? strategy(obj, level, nullRepresentation) : null; } catch { return null; } } private static string StringifyJsonLike( object obj, int level, string nullRepresentation) { var props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); var indentMinus1 = new string(' ', level * INDENT_SIZE); var indent = indentMinus1 + new string(' ', INDENT_SIZE); var joinWith = props.Aggregate( new List<string>(), ( acc, cur) => { var propValue = cur.GetValue(obj); if (_ignoreAssembliesByName.Contains( #if NETSTANDARD cur.DeclaringType?.AssemblyQualifiedName?.Split( new[] { "," }, StringSplitOptions.RemoveEmptyEntries ).Skip(1).FirstOrDefault() #else cur.DeclaringType?.Assembly.GetName().Name #endif )) { acc.Add(string.Join("", cur.Name, ": ", SafeStringifier(propValue, level + 1, nullRepresentation) ) ); } else { acc.Add( string.Join( "", cur.Name, ": ", SafeStringifier(propValue, level + 1, nullRepresentation))); } return acc; }) .JoinWith($"\n{indent}"); return ("{\n" + string.Join( "\n{indent}", $"{indent}{joinWith}" ) + $"\n{indentMinus1}}}").Compact(); } private static string StringifyPrimitive( object obj, int level, string nullRep) { if (obj == null) return nullRep; return _primitiveStringifiers.TryGetValue(obj.GetType(), out var strategy) ? strategy(obj) : obj.ToString(); } } internal static class StringifierStringExtensions { internal static string Compact( this string str) { return new[] { "\r\n", "\n" }.Aggregate( str, ( acc, cur) => { var twice = $"{cur}{cur}"; while (acc.Contains(twice)) acc = acc.Replace(twice, ""); return acc; }) .SquashEmptyObjects(); } private static string SquashEmptyObjects( this string str) { return str.RegexReplace("{\\s*}", "{}"); } } }
#region using declarations using System; using System.Drawing; using System.Windows.Forms; #endregion namespace DigitallyImported.Controls { /// <summary> /// </summary> public partial class ColorPaletteDialog : Form { private readonly Panel[] _panel = new Panel[40]; private readonly Button cancelButton = new Button(); private readonly Color[] color = new Color[40] { //row 1 Color.FromArgb(0, 0, 0), Color.FromArgb(153, 51, 0), Color.FromArgb(51, 51, 0), Color.FromArgb(0, 51, 0), Color.FromArgb(0, 51, 102), Color.FromArgb(0, 0, 128), Color.FromArgb(51, 51, 153), Color.FromArgb(51, 51, 51), //row 2 Color.FromArgb(128, 0, 0), Color.FromArgb(255, 102, 0), Color.FromArgb(128, 128, 0), Color.FromArgb(0, 128, 0), Color.FromArgb(0, 128, 128), Color.FromArgb(0, 0, 255), Color.FromArgb(102, 102, 153), Color.FromArgb(128, 128, 128), //row 3 Color.FromArgb(255, 0, 0), Color.FromArgb(255, 153, 0), Color.FromArgb(153, 204, 0), Color.FromArgb(51, 153, 102), Color.FromArgb(51, 204, 204), Color.FromArgb(51, 102, 255), Color.FromArgb(128, 0, 128), Color.FromArgb(153, 153, 153), //row 4 Color.FromArgb(255, 0, 255), Color.FromArgb(255, 204, 0), Color.FromArgb(255, 255, 0), Color.FromArgb(0, 255, 0), Color.FromArgb(0, 255, 255), Color.FromArgb(0, 204, 255), Color.FromArgb(153, 51, 102), Color.FromArgb(192, 192, 192), //row 5 Color.FromArgb(255, 153, 204), Color.FromArgb(255, 204, 153), Color.FromArgb(255, 255, 153), Color.FromArgb(204, 255, 204), Color.FromArgb(204, 255, 255), Color.FromArgb(153, 204, 255), Color.FromArgb(204, 153, 255), Color.FromArgb(255, 255, 255) }; private readonly string[] colorName = new string[40] { "Black", "Brown", "Olive Green", "Dark Green", "Dark Teal", "Dark Blue", "Indigo", "Gray-80%", "Dark Red", "Orange", "Dark Yellow", "Green", "Teal", "Blue", "Blue-Gray", "Gray-50%", "Red", "Light Orange", "Lime", "Sea Green", "Aqua", "Light Blue", "Violet", "Gray-40%", "Pink", "Gold", "Yellow", "Bright Green", "Turquoise", "Sky Blue", "Plum", "Gray-25%", "Rose", "Tan", "Light Yellow", "Light Green", "Light Turquoise", "Pale Blue", "Lavender", "White" }; private readonly Button moreColorsButton = new Button(); private byte max = 40; private Color selectedColor; /// <summary> /// </summary> /// <param name="x"> </param> /// <param name="y"> </param> public ColorPaletteDialog(int x, int y) { Size = new Size(158, 132); FormBorderStyle = FormBorderStyle.FixedDialog; MinimizeBox = MaximizeBox = ControlBox = false; ShowInTaskbar = false; CenterToScreen(); Location = new Point(x, y); BuildPalette(); moreColorsButton.Text = "More colors ..."; moreColorsButton.Size = new Size(142, 22); moreColorsButton.Location = new Point(5, 99); moreColorsButton.Click += moreColorsButton_Click; moreColorsButton.FlatStyle = FlatStyle.Popup; Controls.Add(moreColorsButton); //"invisible" button to cancel at Escape cancelButton.Size = new Size(5, 5); cancelButton.Location = new Point(-10, -10); cancelButton.Click += cancelButton_Click; Controls.Add(cancelButton); cancelButton.TabIndex = 0; CancelButton = cancelButton; } /// <summary> /// </summary> public Color Color { get { return selectedColor; } } private void BuildPalette() { byte pwidth = 16; byte pheight = 16; byte pdistance = 2; byte border = 5; int x = border, y = border; var toolTip = new ToolTip(); for (var i = 0; i < max; i++) { _panel[i] = new Panel {Height = pwidth, Width = pheight, Location = new Point(x, y)}; toolTip.SetToolTip(_panel[i], colorName[i]); Controls.Add(_panel[i]); if (x < (7*(pwidth + pdistance))) x += pwidth + pdistance; else { x = border; y += pheight + pdistance; } _panel[i].BackColor = color[i]; _panel[i].MouseEnter += OnMouseEnterPanel; _panel[i].MouseLeave += OnMouseLeavePanel; _panel[i].MouseDown += OnMouseDownPanel; _panel[i].MouseUp += OnMouseUpPanel; _panel[i].Paint += OnPanelPaint; } } private void moreColorsButton_Click(object sender, EventArgs e) { var colDialog = new ColorDialog {FullOpen = true}; colDialog.ShowDialog(); selectedColor = colDialog.Color; colDialog.Dispose(); Close(); } private void cancelButton_Click(object sender, EventArgs e) { Close(); } private void OnMouseEnterPanel(object sender, EventArgs e) { DrawPanel(sender, 1); } private void OnMouseLeavePanel(object sender, EventArgs e) { DrawPanel(sender, 0); } private void OnMouseDownPanel(object sender, MouseEventArgs e) { DrawPanel(sender, 2); } private void OnMouseUpPanel(object sender, MouseEventArgs e) { using (var panel = (Panel) sender) { selectedColor = panel.BackColor; } Close(); } private void DrawPanel(object sender, byte state) { var panel = (Panel) sender; var g = panel.CreateGraphics(); Pen pen1, pen2; switch (state) { case 1: pen1 = new Pen(SystemColors.ControlLightLight); pen2 = new Pen(SystemColors.ControlDarkDark); break; case 2: pen1 = new Pen(SystemColors.ControlDarkDark); pen2 = new Pen(SystemColors.ControlLightLight); break; default: pen1 = new Pen(SystemColors.ControlDark); pen2 = new Pen(SystemColors.ControlDark); break; } var r = panel.ClientRectangle; var p1 = new Point(r.Left, r.Top); //top left var p2 = new Point(r.Right - 1, r.Top); //top right var p3 = new Point(r.Left, r.Bottom - 1); //bottom left var p4 = new Point(r.Right - 1, r.Bottom - 1); //bottom right g.DrawLine(pen1, p1, p2); g.DrawLine(pen1, p1, p3); g.DrawLine(pen2, p2, p4); g.DrawLine(pen2, p3, p4); } private void OnPanelPaint(Object sender, PaintEventArgs e) { DrawPanel(sender, 0); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using PieceColor = ChinaChess.PieceColor; using PieceCode = ChinaChess.PieceCode; using System; using BoardUtils; namespace DarkChinaChess { static public class BoardExtension { /* 0,1,2,3,4,5,6,7, 8,9,10,11,12,13,14,15, 16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63, 64,65,66,67,68,69,70,71 */ static public int EatedPieceIndex(this Board2D<Piece> b, PieceColor color) { int[] redIndexs = {40,48,56,64,41,49,57,65,42,50,58,66,43,51,59,67}; int[] blackIndexs = {47,55,63,71,46,54,62,70,45,53,61,69,44,52,60,68}; int[] useIndexs = color == PieceColor.Red ? redIndexs : blackIndexs; return useIndexs.SkipWhile (i => b.HasPiece(i)).First (); } } public class Game : IInitable, IMovable, IOpenable { public static IEnumerable<Piece> StandardBegin { get { int[] pieceNos = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; return pieceNos.Select (x => x != 0 ? new Piece (x + 100) : null); } } public static IEnumerable<Piece> GetRandomBegin () { int[] pieceNos = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 7, 7, 7, 11, 11, 12, 12, 13, 13, 14, 14, 15, 16, 16, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; Utils.Shuffle (pieceNos, 32); return pieceNos.Select (x => x != 0 ? new Piece (x + 100) : null); } Board2D<Piece> board; public Board2D<Piece> Board { get { // TODO return a readable one? return board; } } PieceColor playerColorNow; public PieceColor PlayerColorNow { get { return playerColorNow; } } bool initPlayerColorByOpen; public bool InitPlayerColorByOpen { get { return this.initPlayerColorByOpen; } } public Game () { board = new Board2D<Piece> (9, 8); Init (); } public void Init () { Init (StandardBegin); } public void Init (IEnumerable<Piece> pieces) { board.SetPieces (pieces); playerColorNow = PieceColor.Red; initPlayerColorByOpen = false; } public void InitPlayerColor(int openIndex) { Open (openIndex); playerColorNow = Board.GetPiece (openIndex).Color.Opposite (); initPlayerColorByOpen = true; } public bool GameOver { get { var pieces = Board.Pieces; return pieces.All (x => x.Color == PieceColor.Red) || pieces.All (x => x.Color == PieceColor.Black); } } public PieceColor WinnerColor { get { if (!GameOver) { throw new System.Exception (); } return playerColorNow; } } public bool IsValidOpen (int index) { var p = Board.GetPiece (index); return p != null && !p.Opened; } public void Open (int index) { if (!IsValidOpen (index)) { throw new System.ArgumentException (); } Board.SetPiece (index, Board.GetPiece (index).Open); if (!GameOver) { playerColorNow = playerColorNow.Opposite (); } } public IEnumerable<int> ValidOpens () { return Board.Indexs.Where (IsValidOpen); } public void Move (int indexFrom, int indexTo) { if (!IsValidMove (indexFrom, indexTo)) { throw new System.Exception (); } var pEated = Board.GetPiece (indexTo); Board.MovePiece (indexFrom, indexTo); if (pEated != null) { Board.SetPiece (Board.EatedPieceIndex (pEated.Color), pEated); } if (!GameOver) { playerColorNow = playerColorNow.Opposite (); } } public bool IsValidMove (int indexFrom, int indexTo) { return ValidMoves (indexFrom).Contains (indexTo); } public IEnumerable<int> ValidMoves (int indexFrom) { IEnumerable<int> indexTos = new List<int> (); // 1. indexFrom requirements var p = Board.GetPiece (indexFrom); if (GameOver || indexFrom > 32 || p == null || p.Color != playerColorNow || !p.Opened) { return indexTos; } // 2. common indexTos indexTos = Board.FourNeighbourIndexs (indexFrom); int[,] eatTableByCode = { // public enum PieceCode {Rook=1,Knight,Elephant,Mandarin,King,Connon,Pawn}; { 1, 1, 0, 0, 0, 1, 1 }, { 0, 1, 0, 0, 0, 1, 1 }, { 1, 1, 1, 0, 0, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 1, 1 }, { 0, 0, 0, 0, 1, 0, 1 }, }; Func<Piece,Piece,bool> eatable = (p1, p2) => eatTableByCode [(int)p1.Code-1, (int)p2.Code-1] > 0; indexTos = indexTos.Where (indexTo => Board.GetPiece (indexTo) == null || eatable (p, Board.GetPiece (indexTo))); // 3. special indexTos if (p.Code == PieceCode.Connon) { var extraIndexs = Board.FourDirectionIndexs (indexFrom).Where (x => x.HasSecondPiece).Select (x => x.IndexOfSecondPiece); indexTos = indexTos.Union (extraIndexs); } // 4. indexTos requirement indexTos = indexTos.Where (x => x < 32 && (Board.GetPiece (x) == null || (Board.GetPiece (x).Color != p.Color && Board.GetPiece (x).Opened) )); return indexTos; } } public class RandomInitCommand : IInitCommand { Game g; IEnumerable<Piece> begin; public RandomInitCommand (Game g) { this.g = g; begin = Game.GetRandomBegin (); } #region ICommand implementation public void Execute () { g.Init (begin); } #endregion } public class InitPlayerColorCommand : ICommand { Game g; int index; public InitPlayerColorCommand (Game g, int index) { this.g = g; this.index = index; } #region ICommand implementation public void Execute () { g.InitPlayerColor (index); } #endregion } }
namespace AngleSharp.Css.Tests.Values { using AngleSharp.Css.Converters; using AngleSharp.Css.Values; using NUnit.Framework; using System.Linq; using static CssConstructionFunctions; using static ValueConverters; [TestFixture] public class GradientTests { [Test] public void InLinearGradient() { var source = "linear-gradient(135deg, red, blue)"; var value = GradientConverter.Convert(source); Assert.IsNotNull(value); } [Test] public void InRadialGradient() { var source = "radial-gradient(ellipse farthest-corner at 45px 45px , #00FFFF, rgba(0, 0, 255, 0) 50%, #0000FF 95%)"; var value = GradientConverter.Convert(source); Assert.IsNotNull(value); } [Test] public void BackgroundImageLinearGradientWithAngle() { var red = Color.Red; var blue = Color.Blue; var source = $"background-image: linear-gradient(135deg, {red.CssText}, {blue.CssText})"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsNotNull(gradient); Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Angle.TripleHalfQuarter, gradient.Angle); Assert.AreEqual(2, gradient.Stops.Length); Assert.AreEqual(red, gradient.Stops.First().Color); Assert.AreEqual(blue, gradient.Stops.Last().Color); Assert.AreEqual(source, property.CssText); } [Test] public void BackgroundImageLinearGradientWithSide() { var source = "background-image: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Angle.Quarter, gradient.Angle); var stops = gradient.Stops.ToArray(); Assert.AreEqual(7, stops.Length); Assert.AreEqual(CssColors.GetColor("red").Value, stops[0].Color); Assert.AreEqual(CssColors.GetColor("orange").Value, stops[1].Color); Assert.AreEqual(CssColors.GetColor("yellow").Value, stops[2].Color); Assert.AreEqual(CssColors.GetColor("green").Value, stops[3].Color); Assert.AreEqual(CssColors.GetColor("blue").Value, stops[4].Color); Assert.AreEqual(CssColors.GetColor("indigo").Value, stops[5].Color); Assert.AreEqual(CssColors.GetColor("violet").Value, stops[6].Color); } [Test] public void BackgroundImageLinearGradientWithCornerAndRgba() { var source = "background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0))"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Angle.TripleHalfQuarter, gradient.Angle); Assert.AreEqual(2, gradient.Stops.Count()); Assert.AreEqual(Color.Red, gradient.Stops.First().Color); Assert.AreEqual(Color.FromRgba(255, 0, 0, 0), gradient.Stops.Last().Color); } [Test] public void BackgroundImageLinearGradientWithSideAndHsl() { var source = "background-image: linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Angle.Half, gradient.Angle); Assert.AreEqual(2, gradient.Stops.Count()); Assert.AreEqual(Color.FromHsl(0f, 0.8f, 0.7f), gradient.Stops.First().Color); Assert.AreEqual(Color.FromHex("bada55"), gradient.Stops.Last().Color); } [Test] public void BackgroundImageLinearGradientNoAngle() { var source = "background-image: linear-gradient(yellow, blue 20%, #0f0)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Angle.Half, gradient.Angle); Assert.AreEqual(3, gradient.Stops.Count()); Assert.AreEqual(CssColors.GetColor("yellow").Value, gradient.Stops.First().Color); Assert.AreEqual(CssColors.GetColor("blue").Value, gradient.Stops.Skip(1).First().Color); Assert.AreEqual(Color.FromRgb(0, 255, 0), gradient.Stops.Skip(2).First().Color); } [Test] public void BackgroundImageRadialGradientCircleFarthestCorner() { var source = "background-image: radial-gradient(circle farthest-corner at 45px 45px , #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(45, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(45, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(true, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.FarthestCorner, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromRgb(0, 255, 255), stops[0].Color); Assert.AreEqual(Color.FromRgba(0, 0, 255, 0), stops[1].Color); Assert.AreEqual(Color.FromRgb(0, 0, 255), stops[2].Color); } [Test] public void BackgroundImageRadialGradientEllipseFarthestCorner() { var source = "background-image: radial-gradient(ellipse farthest-corner at 470px 47px , #FFFF80 20%, rgba(204, 153, 153, 0.4) 30%, #E6E6FF 60%)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(470, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(47, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.FarthestCorner, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromRgb(0xFF, 0xFF, 0x80), stops[0].Color); Assert.AreEqual(Color.FromRgba(204, 153, 153, 0.4f), stops[1].Color); Assert.AreEqual(Color.FromRgb(0xE6, 0xE6, 0xFF), stops[2].Color); } [Test] public void BackgroundImageRadialGradientFarthestCornerWithPoint() { var source = "background-image: radial-gradient(farthest-corner at 45px 45px , #FF0000 0%, #0000FF 100%)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(45, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(45, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.FarthestCorner, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(2, stops.Length); Assert.AreEqual(Color.FromRgb(255, 0, 0), stops[0].Color); Assert.AreEqual(Color.FromRgb(0, 0, 255), stops[1].Color); } [Test] public void BackgroundImageRadialGradientSingleSize() { var source = "background-image: radial-gradient(16px at 60px 50% , #000000 0%, #000000 14px, rgba(0, 0, 0, 0.3) 18px, rgba(0, 0, 0, 0) 19px)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(60f, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(true, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); Assert.AreEqual(new Length(16f, Length.Unit.Px), gradient.MajorRadius); Assert.AreEqual(Length.Full, gradient.MinorRadius); var stops = gradient.Stops.ToArray(); Assert.AreEqual(4, stops.Length); Assert.AreEqual(Color.FromRgb(0, 0, 0), stops[0].Color); Assert.AreEqual(Color.FromRgb(0, 0, 0), stops[1].Color); Assert.AreEqual(Color.FromRgba(0, 0, 0, 0.3), stops[2].Color); Assert.AreEqual(Color.Transparent, stops[3].Color); } [Test] public void BackgroundImageRadialGradientCircle() { var source = "background-image: radial-gradient(circle, yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Length.Half, gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(true, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(2, stops.Length); Assert.AreEqual(Color.FromName("yellow").Value, stops[0].Color); Assert.AreEqual(Color.FromName("green").Value, stops[1].Color); } [Test] public void BackgroundImageRadialGradientOnlyGradientStops() { var source = "background-image: radial-gradient(yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Length.Half, gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(2, stops.Length); Assert.AreEqual(Color.FromName("yellow").Value, stops[0].Color); Assert.AreEqual(Color.FromName("green").Value, stops[1].Color); } [Test] public void BackgroundImageRadialGradientEllipseAtCenter() { var source = "background-image: radial-gradient(ellipse at center, yellow 0%, green 100%)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Length.Half, gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(2, stops.Length); Assert.AreEqual(Color.FromName("yellow").Value, stops[0].Color); Assert.AreEqual(Color.FromName("green").Value, stops[1].Color); } [Test] public void BackgroundImageRadialGradientFarthestCornerWithoutPoint() { var source = "background-image: radial-gradient(farthest-corner, yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Length.Half, gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.FarthestCorner, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(2, stops.Length); Assert.AreEqual(Color.FromName("yellow").Value, stops[0].Color); Assert.AreEqual(Color.FromName("green").Value, stops[1].Color); } [Test] public void BackgroundImageRadialGradientClosestSideWithPoint() { var source = "background-image: radial-gradient(closest-side at 20px 30px, red, yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(20f, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(30f, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.ClosestSide, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[1].Color); Assert.AreEqual(Color.FromName("green").Value, stops[2].Color); } [Test] public void BackgroundImageRadialGradientSizeAndPoint() { var source = "background-image: radial-gradient(20px 30px at 20px 30px, red, yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(20f, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(30f, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); Assert.AreEqual(new Length(20f, Length.Unit.Px), gradient.MajorRadius); Assert.AreEqual(new Length(30f, Length.Unit.Px), gradient.MinorRadius); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[1].Color); Assert.AreEqual(Color.FromName("green").Value, stops[2].Color); } [Test] public void BackgroundImageRadialGradientClosestSideCircleShuffledWithPoint() { var source = "background-image: radial-gradient(closest-side circle at 20px 30px, red, yellow, green)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(new Length(20f, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(30f, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(true, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.ClosestSide, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[1].Color); Assert.AreEqual(Color.FromName("green").Value, stops[2].Color); } [Test] public void BackgroundImageRadialGradientFarthestSideLeftBottom() { var source = "background-image: radial-gradient(farthest-side at left bottom, red, yellow 50px, green);"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsFalse(gradient.IsRepeating); Assert.AreEqual(Length.Zero, gradient.Position.X); Assert.AreEqual(Length.Full, gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.FarthestSide, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[1].Color); Assert.AreEqual(Color.FromName("green").Value, stops[2].Color); } [Test] public void BackgroundImageRepeatingLinearGradientRedBlue() { var source = "background-image: repeating-linear-gradient(red, blue 20px, red 40px)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssLinearGradientValue; Assert.IsTrue(gradient.IsRepeating); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("blue").Value, stops[1].Color); Assert.AreEqual(Color.FromName("red").Value, stops[2].Color); } [Test] public void BackgroundImageRepeatingRadialGradientRedBlue() { var source = "background-image: repeating-radial-gradient(red, blue 20px, red 40px)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsTrue(gradient.IsRepeating); Assert.AreEqual(Length.Half, gradient.Position.X); Assert.AreEqual(Length.Half, gradient.Position.Y); Assert.AreEqual(false, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.None, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(3, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("blue").Value, stops[1].Color); Assert.AreEqual(Color.FromName("red").Value, stops[2].Color); } [Test] public void BackgroundImageRepeatingRadialGradientFunky() { var source = "background-image: repeating-radial-gradient(circle closest-side at 20px 30px, red, yellow, green 100%, yellow 150%, red 200%)"; var property = ParseDeclaration(source); Assert.IsTrue(property.HasValue); Assert.IsFalse(property.IsInitial); var value = property.RawValue as CssListValue; Assert.IsNotNull(value); Assert.AreEqual(1, value.Items.Length); var gradient = value.Items[0] as CssRadialGradientValue; Assert.IsTrue(gradient.IsRepeating); Assert.AreEqual(new Length(20f, Length.Unit.Px), gradient.Position.X); Assert.AreEqual(new Length(30f, Length.Unit.Px), gradient.Position.Y); Assert.AreEqual(true, gradient.IsCircle); Assert.AreEqual(CssRadialGradientValue.SizeMode.ClosestSide, gradient.Mode); var stops = gradient.Stops.ToArray(); Assert.AreEqual(5, stops.Length); Assert.AreEqual(Color.FromName("red").Value, stops[0].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[1].Color); Assert.AreEqual(Color.FromName("green").Value, stops[2].Color); Assert.AreEqual(Color.FromName("yellow").Value, stops[3].Color); Assert.AreEqual(Color.FromName("red").Value, stops[4].Color); } } }
#region License /* * TcpListenerWebSocketContext.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Contributors /* * Contributors: * - Liryna <liryna.stark@gmail.com> */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; namespace WebSocketSharp.Net.WebSockets { /// <summary> /// Provides the properties used to access the information in a WebSocket connection request /// received by the <see cref="TcpListener"/>. /// </summary> internal class TcpListenerWebSocketContext : WebSocketContext { #region Private Fields private CookieCollection _cookies; private Logger _logger; private NameValueCollection _queryString; private HttpRequest _request; private bool _secure; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private IPrincipal _user; private WebSocket _websocket; #endregion #region Internal Constructors internal TcpListenerWebSocketContext ( TcpClient tcpClient, string protocol, bool secure, ServerSslConfiguration sslConfig, Logger logger) { _tcpClient = tcpClient; _secure = secure; _logger = logger; var netStream = tcpClient.GetStream (); if (secure) { var sslStream = new SslStream ( netStream, false, sslConfig.ClientCertificateValidationCallback); sslStream.AuthenticateAsServer ( sslConfig.ServerCertificate, sslConfig.ClientCertificateRequired, sslConfig.EnabledSslProtocols, sslConfig.CheckCertificateRevocation); _stream = sslStream; } else { _stream = netStream; } _request = HttpRequest.Read (_stream, 90000); _uri = HttpUtility.CreateRequestUrl ( _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure); _websocket = new WebSocket (this, protocol); } #endregion #region Internal Properties internal string HttpMethod { get { return _request.HttpMethod; } } internal Logger Log { get { return _logger; } } internal Stream Stream { get { return _stream; } } #endregion #region Public Properties /// <summary> /// Gets the HTTP cookies included in the request. /// </summary> /// <value> /// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains the cookies. /// </value> public override CookieCollection CookieCollection { get { return _cookies ?? (_cookies = _request.Cookies); } } /// <summary> /// Gets the HTTP headers included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public override NameValueCollection Headers { get { return _request.Headers; } } /// <summary> /// Gets the value of the Host header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Host header. /// </value> public override string Host { get { return _request.Headers["Host"]; } } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public override bool IsAuthenticated { get { return _user != null; } } /// <summary> /// Gets a value indicating whether the client connected from the local computer. /// </summary> /// <value> /// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>. /// </value> public override bool IsLocal { get { return UserEndPoint.Address.IsLocal (); } } /// <summary> /// Gets a value indicating whether the WebSocket connection is secured. /// </summary> /// <value> /// <c>true</c> if the connection is secured; otherwise, <c>false</c>. /// </value> public override bool IsSecureConnection { get { return _secure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket connection request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>. /// </value> public override bool IsWebSocketRequest { get { return _request.IsWebSocketRequest; } } /// <summary> /// Gets the value of the Origin header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Origin header. /// </value> public override string Origin { get { return _request.Headers["Origin"]; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the query string parameters. /// </value> public override NameValueCollection QueryString { get { return _queryString ?? (_queryString = HttpUtility.InternalParseQueryString ( _uri != null ? _uri.Query : null, Encoding.UTF8)); } } /// <summary> /// Gets the URI requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the requested URI. /// </value> public override Uri RequestUri { get { return _uri; } } /// <summary> /// Gets the value of the Sec-WebSocket-Key header included in the request. /// </summary> /// <remarks> /// This property provides a part of the information used by the server to prove that it /// received a valid WebSocket connection request. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key header. /// </value> public override string SecWebSocketKey { get { return _request.Headers["Sec-WebSocket-Key"]; } } /// <summary> /// Gets the values of the Sec-WebSocket-Protocol header included in the request. /// </summary> /// <remarks> /// This property represents the subprotocols requested by the client. /// </remarks> /// <value> /// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> instance that provides /// an enumerator which supports the iteration over the values of the Sec-WebSocket-Protocol /// header. /// </value> public override IEnumerable<string> SecWebSocketProtocols { get { var protocols = _request.Headers["Sec-WebSocket-Protocol"]; if (protocols != null) foreach (var protocol in protocols.Split (',')) yield return protocol.Trim (); } } /// <summary> /// Gets the value of the Sec-WebSocket-Version header included in the request. /// </summary> /// <remarks> /// This property represents the WebSocket protocol version. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Version header. /// </value> public override string SecWebSocketVersion { get { return _request.Headers["Sec-WebSocket-Version"]; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint. /// </value> public override System.Net.IPEndPoint ServerEndPoint { get { return (System.Net.IPEndPoint) _tcpClient.Client.LocalEndPoint; } } /// <summary> /// Gets the client information (identity, authentication, and security roles). /// </summary> /// <value> /// A <see cref="IPrincipal"/> instance that represents the client information. /// </value> public override IPrincipal User { get { return _user; } } /// <summary> /// Gets the client endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint. /// </value> public override System.Net.IPEndPoint UserEndPoint { get { return (System.Net.IPEndPoint) _tcpClient.Client.RemoteEndPoint; } } /// <summary> /// Gets the <see cref="WebSocketSharp.WebSocket"/> instance used for two-way communication /// between client and server. /// </summary> /// <value> /// A <see cref="WebSocketSharp.WebSocket"/>. /// </value> public override WebSocket WebSocket { get { return _websocket; } } #endregion #region Internal Methods internal void Close () { _stream.Close (); _tcpClient.Close (); } internal void Close (HttpStatusCode code) { _websocket.Close (HttpResponse.CreateCloseResponse (code)); } internal void SendAuthenticationChallenge (string challenge) { var buff = HttpResponse.CreateUnauthorizedResponse (challenge).ToByteArray (); _stream.Write (buff, 0, buff.Length); _request = HttpRequest.Read (_stream, 15000); } internal void SetUser (IPrincipal value) { _user = value; } #endregion #region Public Methods /// <summary> /// Returns a <see cref="string"/> that represents the current /// <see cref="TcpListenerWebSocketContext"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the current /// <see cref="TcpListenerWebSocketContext"/>. /// </returns> public override string ToString () { return _request.ToString (); } #endregion } }
using System; using System.Collections.Concurrent; using System.Net; using System.Reflection; using System.Text; using System.Threading; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.Serialization { using System.Runtime.CompilerServices; internal static class TypeUtilities { internal static bool IsOrleansPrimitive(this Type t) { return t.IsPrimitive || t.IsEnum || t == typeof(string) || t == typeof(DateTime) || t == typeof(Decimal) || t == typeof(Guid) || (t.IsArray && t.GetElementType().IsOrleansPrimitive()); } static readonly ConcurrentDictionary<Type, string> typeNameCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, string> typeKeyStringCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, byte[]> typeKeyCache = new ConcurrentDictionary<Type, byte[]>(); static readonly ConcurrentDictionary<Type, bool> shallowCopyableTypes = new ConcurrentDictionary<Type, bool> { [typeof(Decimal)] = true, [typeof(DateTime)] = true, [typeof(TimeSpan)] = true, [typeof(IPAddress)] = true, [typeof(IPEndPoint)] = true, [typeof(SiloAddress)] = true, [typeof(GrainId)] = true, [typeof(ActivationId)] = true, [typeof(ActivationAddress)] = true, [typeof(CorrelationId)] = true, [typeof(string)] = true, [typeof(CancellationToken)] = true, [typeof(Guid)] = true, }; internal static bool IsOrleansShallowCopyable(this Type t) { if (shallowCopyableTypes.TryGetValue(t, out var result)) { return result; } return shallowCopyableTypes.GetOrAdd(t, IsShallowCopyableInternal(t)); } private static bool IsShallowCopyableInternal(Type t) { if (t.IsPrimitive || t.IsEnum) return true; if (t.IsDefined(typeof(ImmutableAttribute), false)) return true; if (t.IsConstructedGenericType) { var def = t.GetGenericTypeDefinition(); if (def == typeof(Immutable<>)) return true; if (def == typeof(Nullable<>) || def == typeof(Tuple<>) || def == typeof(Tuple<,>) || def == typeof(Tuple<,,>) || def == typeof(Tuple<,,,>) || def == typeof(Tuple<,,,,>) || def == typeof(Tuple<,,,,,>) || def == typeof(Tuple<,,,,,,>) || def == typeof(Tuple<,,,,,,,>)) return Array.TrueForAll(t.GenericTypeArguments, a => IsOrleansShallowCopyable(a)); } if (t.IsValueType && !t.IsGenericTypeDefinition) return Array.TrueForAll(t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic), f => IsOrleansShallowCopyable(f.FieldType)); if (typeof(Exception).IsAssignableFrom(t)) return true; return false; } internal static string OrleansTypeName(this Type t) { string name; if (typeNameCache.TryGetValue(t, out name)) return name; name = TypeUtils.GetTemplatedName(t, _ => !_.IsGenericParameter); typeNameCache[t] = name; return name; } public static byte[] OrleansTypeKey(this Type t) { byte[] key; if (typeKeyCache.TryGetValue(t, out key)) return key; key = Encoding.UTF8.GetBytes(t.OrleansTypeKeyString()); typeKeyCache[t] = key; return key; } public static string OrleansTypeKeyString(this Type t) { string key; if (typeKeyStringCache.TryGetValue(t, out key)) return key; var sb = new StringBuilder(); if (t.IsGenericTypeDefinition) { sb.Append(GetBaseTypeKey(t)); sb.Append('\''); sb.Append(t.GetGenericArguments().Length); } else if (t.IsGenericType) { sb.Append(GetBaseTypeKey(t)); sb.Append('<'); var first = true; foreach (var genericArgument in t.GetGenericArguments()) { if (!first) { sb.Append(','); } first = false; sb.Append(OrleansTypeKeyString(genericArgument)); } sb.Append('>'); } else if (t.IsArray) { sb.Append(OrleansTypeKeyString(t.GetElementType())); sb.Append('['); if (t.GetArrayRank() > 1) { sb.Append(',', t.GetArrayRank() - 1); } sb.Append(']'); } else { sb.Append(GetBaseTypeKey(t)); } key = sb.ToString(); typeKeyStringCache[t] = key; return key; } private static string GetBaseTypeKey(Type t) { string namespacePrefix = ""; if ((t.Namespace != null) && !t.Namespace.StartsWith("System.", StringComparison.Ordinal) && !t.Namespace.Equals("System")) { namespacePrefix = t.Namespace + '.'; } if (t.IsNestedPublic) { return namespacePrefix + OrleansTypeKeyString(t.DeclaringType) + "." + t.Name; } return namespacePrefix + t.Name; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static string GetLocationSafe(this Assembly a) { if (a.IsDynamic) { return "dynamic"; } try { return a.Location; } catch (Exception) { return "unknown"; } } /// <summary> /// Returns <see langword="true"/> if a type is accessible from C# code from the specified assembly, and <see langword="false"/> otherwise. /// </summary> /// <param name="type"></param> /// <param name="assembly"></param> /// <returns></returns> public static bool IsAccessibleFromAssembly(Type type, Assembly assembly) { if (type.IsSpecialName) return false; if (type.GetCustomAttribute<CompilerGeneratedAttribute>() != null) return false; // Obsolete types can be accessed, however obsolete types which have IsError set cannot. var obsoleteAttr = type.GetCustomAttribute<ObsoleteAttribute>(); if (obsoleteAttr != null && obsoleteAttr.IsError) return false; // Arrays are accessible if their element type is accessible. if (type.IsArray) return IsAccessibleFromAssembly(type.GetElementType(), assembly); // Pointer and ref types are not accessible. if (type.IsPointer || type.IsByRef) return false; // Generic types are only accessible if their generic arguments are accessible. if (type.IsConstructedGenericType) { foreach (var parameter in type.GetGenericArguments()) { if (!IsAccessibleFromAssembly(parameter, assembly)) return false; } } else if (type.IsGenericTypeDefinition) { // Guard against unrepresentable type constraints, which appear when generating code for some languages, such as F#. foreach (var parameter in type.GetTypeInfo().GenericTypeParameters) { foreach (var constraint in parameter.GetGenericParameterConstraints()) { if (constraint == typeof(Array) || constraint == typeof(Delegate) || constraint == typeof(Enum)) return false; } } } // Internal types are accessible only if the declaring assembly exposes its internals to the target assembly. if (type.IsNotPublic || type.IsNestedAssembly || type.IsNestedFamORAssem) { if (!AreInternalsVisibleTo(type.Assembly, assembly)) return false; } // Nested types which are private or protected are not accessible. if (type.IsNestedPrivate || type.IsNestedFamily || type.IsNestedFamANDAssem) return false; // Nested types are otherwise accessible if their declaring type is accessible. if (type.IsNested) { return IsAccessibleFromAssembly(type.DeclaringType, assembly); } return true; } /// <summary> /// Returns true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise. /// </summary> /// <param name="fromAssembly">The assembly containing internal types.</param> /// <param name="toAssembly">The assembly requiring access to internal types.</param> /// <returns> /// true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise /// </returns> private static bool AreInternalsVisibleTo(Assembly fromAssembly, Assembly toAssembly) { // If the to-assembly is null, it cannot have internals visible to it. if (toAssembly == null) { return false; } if (Equals(fromAssembly, toAssembly)) return true; // Check InternalsVisibleTo attributes on the from-assembly, pointing to the to-assembly. var fullName = toAssembly.GetName().FullName; var shortName = toAssembly.GetName().Name; var internalsVisibleTo = fromAssembly.GetCustomAttributes<InternalsVisibleToAttribute>(); foreach (var attr in internalsVisibleTo) { if (string.Equals(attr.AssemblyName, fullName, StringComparison.Ordinal)) return true; if (string.Equals(attr.AssemblyName, shortName, StringComparison.Ordinal)) return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; namespace System { #if CORERT public sealed #else internal #endif partial class DefaultBinder : Binder { // This method is passed a set of methods and must choose the best // fit. The methods all have the same number of arguments and the object // array args. On exit, this method will choice the best fit method // and coerce the args to match that method. By match, we mean all primitive // arguments are exact matchs and all object arguments are exact or subclasses // of the target. If the target OR is an interface, the object must implement // that interface. There are a couple of exceptions // thrown when a method cannot be returned. If no method matchs the args and // ArgumentException is thrown. If multiple methods match the args then // an AmbiguousMatchException is thrown. // // The most specific match will be selected. // public sealed override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, ParameterModifier[]? modifiers, CultureInfo? cultureInfo, string[]? names, out object? state) { if (match == null || match.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); MethodBase?[] candidates = (MethodBase[])match.Clone(); int i; int j; state = null; #region Map named parameters to candidate parameter positions // We are creating an paramOrder array to act as a mapping // between the order of the args and the actual order of the // parameters in the method. This order may differ because // named parameters (names) may change the order. If names // is not provided, then we assume the default mapping (0,1,...) int[][] paramOrder = new int[candidates.Length][]; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; if (names == null) { // Default mapping for (j = 0; j < args.Length; j++) paramOrder[i][j] = j; } else { // Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method // doesn't have a name that matchs one of the named parameters so we don't consider it any further. if (!CreateParamOrder(paramOrder[i], par, names)) candidates[i] = null; } } #endregion Type[] paramArrayTypes = new Type[candidates.Length]; Type[] argTypes = new Type[args.Length]; #region Cache the type of the provided arguments // object that contain a null are treated as if they were typeless (but match either object // references or value classes). We mark this condition by placing a null in the argTypes array. for (i = 0; i < args.Length; i++) { if (args[i] != null) { argTypes[i] = args[i]!.GetType(); } } #endregion // Find the method that matches... int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); Type? paramArrayType; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) { paramArrayType = null; // If we have named parameters then we may have a hole in the candidates array. if (candidates[i] == null) continue; // Validate the parameters. ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) #region Match method by parameter count if (par.Length == 0) { #region No formal parameters if (args.Length != 0) { if ((candidates[i]!.CallingConvention & CallingConventions.VarArgs) == 0) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) continue; } // This is a valid routine so we move it up the candidates list. paramOrder[CurIdx] = paramOrder[i]; candidates[CurIdx++] = candidates[i]; continue; #endregion } else if (par.Length > args.Length) { #region Shortage of provided parameters // If the number of parameters is greater than the number of args then // we are in the situation were we may be using default values. for (j = args.Length; j < par.Length - 1; j++) { if (par[j].DefaultValue == System.DBNull.Value) break; } if (j != par.Length - 1) continue; if (par[j].DefaultValue == System.DBNull.Value) { if (!par[j].ParameterType.IsArray) continue; if (!par[j].IsDefined(typeof(ParamArrayAttribute), true)) continue; paramArrayType = par[j].ParameterType.GetElementType(); } #endregion } else if (par.Length < args.Length) { #region Excess provided parameters // test for the ParamArray case int lastArgPos = par.Length - 1; if (!par[lastArgPos].ParameterType.IsArray) continue; if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)) continue; if (paramOrder[i][lastArgPos] != lastArgPos) continue; paramArrayType = par[lastArgPos].ParameterType.GetElementType(); #endregion } else { #region Test for paramArray, save paramArray type int lastArgPos = par.Length - 1; if (par[lastArgPos].ParameterType.IsArray && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true) && paramOrder[i][lastArgPos] == lastArgPos) { if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos])) paramArrayType = par[lastArgPos].ParameterType.GetElementType(); } #endregion } #endregion Type pCls; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type for (j = 0; j < argsToCheck; j++) { #region Classic argument coersion checks // get the formal type pCls = par[j].ParameterType; if (pCls.IsByRef) pCls = pCls.GetElementType()!; // the type is the same if (pCls == argTypes[paramOrder[i][j]]) continue; // a default value is available if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing) continue; // the argument was null, so it matches with everything if (args[paramOrder[i][j]] == null) continue; // the type is Object, so it will match everything if (pCls == typeof(object)) continue; // now do a "classic" type check if (pCls.IsPrimitive) { if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitive(args[paramOrder[i][j]]?.GetType(), pCls)) { break; } } else { if (argTypes[paramOrder[i][j]] == null) continue; if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]])) { if (argTypes[paramOrder[i][j]].IsCOMObject) { if (pCls.IsInstanceOfType(args[paramOrder[i][j]])) continue; } break; } } #endregion } if (paramArrayType != null && j == par.Length - 1) { #region Check that excess arguments can be placed in the param array for (; j < args.Length; j++) { if (paramArrayType.IsPrimitive) { if (argTypes[j] == null || !CanChangePrimitive(args[j]?.GetType(), paramArrayType)) break; } else { if (argTypes[j] == null) continue; if (!paramArrayType.IsAssignableFrom(argTypes[j])) { if (argTypes[j].IsCOMObject) { if (paramArrayType.IsInstanceOfType(args[j])) continue; } break; } } } #endregion } #endregion if (j == args.Length) { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; paramArrayTypes[CurIdx] = paramArrayType!; candidates[CurIdx++] = candidates[i]; #endregion } } #endregion // If we didn't find a method if (CurIdx == 0) throw new MissingMethodException(SR.MissingMember); if (CurIdx == 1) { #region Found only one method if (names != null) { state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null); ReorderParams(paramOrder[0], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parms = candidates[0]!.GetParametersNoCopy(); if (parms.Length == args.Length) { if (paramArrayTypes[0] != null) { object[] objs = new object[parms.Length]; int lastPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.CreateInstance(paramArrayTypes[0], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parms.Length > args.Length) { object?[] objs = new object[parms.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; for (; i < parms.Length - 1; i++) objs[i] = parms[i].DefaultValue; if (paramArrayTypes[0] != null) objs[i] = Array.CreateInstance(paramArrayTypes[0], 0); // create an empty array for the else objs[i] = parms[i].DefaultValue; args = objs; } else { if ((candidates[0]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parms.Length]; int paramArrayPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[0], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } #endregion return candidates[0]!; } int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke int newMin = FindMostSpecificMethod(candidates[currentMin]!, paramOrder[currentMin], paramArrayTypes[currentMin], candidates[i]!, paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { ambig = true; } else if (newMin == 2) { currentMin = i; ambig = false; } #endregion } if (ambig) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); // Reorder (if needed) if (names != null) { state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null); ReorderParams(paramOrder[currentMin], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parameters = candidates[currentMin]!.GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) { object[] objs = new object[parameters.Length]; int lastPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.CreateInstance(paramArrayTypes[currentMin], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parameters.Length > args.Length) { object?[] objs = new object[parameters.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; for (; i < parameters.Length - 1; i++) objs[i] = parameters[i].DefaultValue; if (paramArrayTypes[currentMin] != null) { objs[i] = Array.CreateInstance(paramArrayTypes[currentMin], 0); } else { objs[i] = parameters[i].DefaultValue; } args = objs; } else { if ((candidates[currentMin]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parameters.Length]; int paramArrayPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } return candidates[currentMin]!; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? cultureInfo) { if (match == null) { throw new ArgumentNullException(nameof(match)); } int i; // Find the method that match... int CurIdx = 0; Type valueType; FieldInfo[] candidates = (FieldInfo[])match.Clone(); // If we are a FieldSet, then use the value's type to disambiguate if ((bindingAttr & BindingFlags.SetField) != 0) { valueType = value.GetType(); for (i = 0; i < candidates.Length; i++) { Type pCls = candidates[i].FieldType; if (pCls == valueType) { candidates[CurIdx++] = candidates[i]; continue; } if (value == Empty.Value) { // the object passed in was null which would match any non primitive non value type if (pCls.IsClass) { candidates[CurIdx++] = candidates[i]; continue; } } if (pCls == typeof(object)) { candidates[CurIdx++] = candidates[i]; continue; } if (pCls.IsPrimitive) { if (CanChangePrimitive(valueType, pCls)) { candidates[CurIdx++] = candidates[i]; continue; } } else { if (pCls.IsAssignableFrom(valueType)) { candidates[CurIdx++] = candidates[i]; continue; } } } if (CurIdx == 0) throw new MissingFieldException(SR.MissingField); if (CurIdx == 1) return candidates[0]; } // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; } } } if (ambig) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); return candidates[currentMin]; } // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. public sealed override MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { int i; int j; Type[] realTypes = new Type[types.Length]; for (i = 0; i < types.Length; i++) { realTypes[i] = types[i].UnderlyingSystemType; if (!(realTypes[i].IsRuntimeImplemented() || realTypes[i] is SignatureType)) throw new ArgumentException(SR.Arg_MustBeType, nameof(types)); } types = realTypes; // We don't automatically jump out on exact match. if (match == null || match.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); MethodBase[] candidates = (MethodBase[])match.Clone(); // Find all the methods that can be described by the types parameter. // Remove all of them that cannot. int CurIdx = 0; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); if (par.Length != types.Length) continue; for (j = 0; j < types.Length; j++) { Type pCls = par[j].ParameterType; if (types[j].MatchesParameterTypeExactly(par[j])) continue; if (pCls == typeof(object)) continue; Type? type = types[j]; if (type is SignatureType signatureType) { if (!(candidates[i] is MethodInfo methodInfo)) break; type = signatureType.TryResolveAgainstGenericMethod(methodInfo); if (type == null) break; } if (pCls.IsPrimitive) { if (!(type.UnderlyingSystemType.IsRuntimeImplemented()) || !CanChangePrimitive(type.UnderlyingSystemType, pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(type)) break; } } if (j == types.Length) candidates[CurIdx++] = candidates[i]; } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[types.Length]; for (i = 0; i < types.Length; i++) paramOrder[i] = i; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; currentMin = i; } } } if (ambig) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); return candidates[currentMin]; } // Given a set of properties that match the base criteria, select one. public sealed override PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, Type[]? indexes, ParameterModifier[]? modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null) { foreach (Type index in indexes) { if (index == null) throw new ArgumentNullException(nameof(indexes)); } } if (match == null || match.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); PropertyInfo[] candidates = (PropertyInfo[])match.Clone(); int i, j = 0; // Find all the properties that can be described by type indexes parameter int CurIdx = 0; int indexesLength = (indexes != null) ? indexes.Length : 0; for (i = 0; i < candidates.Length; i++) { if (indexes != null) { ParameterInfo[] par = candidates[i].GetIndexParameters(); if (par.Length != indexesLength) continue; for (j = 0; j < indexesLength; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls == indexes[j]) continue; if (pCls == typeof(object)) continue; if (pCls.IsPrimitive) { if (!(indexes[j].UnderlyingSystemType.IsRuntimeImplemented()) || !CanChangePrimitive(indexes[j].UnderlyingSystemType, pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(indexes[j])) break; } } } if (j == indexesLength) { if (returnType != null) { if (candidates[i].PropertyType.IsPrimitive) { if (!(returnType.UnderlyingSystemType.IsRuntimeImplemented()) || !CanChangePrimitive(returnType.UnderlyingSystemType, candidates[i].PropertyType.UnderlyingSystemType)) continue; } else { if (!candidates[i].PropertyType.IsAssignableFrom(returnType)) continue; } } candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the properties looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[indexesLength]; for (i = 0; i < indexesLength; i++) paramOrder[i] = i; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType, returnType); if (newMin == 0 && indexes != null) newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(), paramOrder, null, candidates[i].GetIndexParameters(), paramOrder, null, indexes, null); if (newMin == 0) { newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; } if (newMin == 2) { ambig = false; currentMin = i; } } if (ambig) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); return candidates[currentMin]; } // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. public override object ChangeType(object value, Type type, CultureInfo? cultureInfo) { throw new NotSupportedException(SR.NotSupported_ChangeType); } public sealed override void ReorderArgumentArray(ref object?[] args, object state) { BinderState binderState = (BinderState)state; ReorderParams(binderState._argsMap, args); if (binderState._isParamArray) { int paramArrayPos = args.Length - 1; if (args.Length == binderState._originalSize) { args[paramArrayPos] = ((object[])args[paramArrayPos]!)[0]; } else { // must be args.Length < state.originalSize object[] newArgs = new object[args.Length]; Array.Copy(args, 0, newArgs, 0, paramArrayPos); for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) { newArgs[i] = ((object[])args[paramArrayPos]!)[j]; } args = newArgs; } } else { if (args.Length > binderState._originalSize) { object[] newArgs = new object[binderState._originalSize]; Array.Copy(args, 0, newArgs, 0, binderState._originalSize); args = newArgs; } } } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; for (int i = 0; i < match.Length; i++) { ParameterInfo[] par = match[i].GetParametersNoCopy(); if (par.Length == 0) { continue; } int j; for (j = 0; j < types.Length; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (!pCls.Equals(types[j])) break; } if (j < types.Length) continue; // Add the exact match to the array of exact matches. aExactMatches[cExactMatches] = match[i]; cExactMatches++; } if (cExactMatches == 0) return null; if (cExactMatches == 1) return aExactMatches[0]; return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches); } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) { ParameterInfo[] par = match[i].GetIndexParameters(); int j; for (j = 0; j < typesLength; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls != types![j]) break; } if (j < typesLength) continue; if (returnType != null && returnType != match[i].PropertyType) continue; if (bestMatch != null) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); bestMatch = match[i]; } return bestMatch; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type? paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type? paramArrayType2, Type[] types, object?[]? args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; if (paramArrayType2 != null && paramArrayType1 == null) return 1; // now either p1 and p2 both use params or neither does. bool p1Less = false; bool p2Less = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) continue; Type c1, c2; // If a param array is present, then either // the user re-ordered the parameters in which case // the argument to the param array is either an array // in which case the params is conceptually ignored and so paramArrayType1 == null // or the argument to the param array is a single element // in which case paramOrder[i] == p1.Length - 1 for that element // or the user did not re-order the parameters in which case // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) // so any index >= p.Length - 1 is being put in the param array if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1) c1 = paramArrayType1; else c1 = p1[paramOrder1[i]].ParameterType; if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1) c2 = paramArrayType2; else c2 = p2[paramOrder2[i]].ParameterType; if (c1 == c2) continue; switch (FindMostSpecificType(c1, c2, types[i])) { case 0: return 0; case 1: p1Less = true; break; case 2: p2Less = true; break; } } // Two way p1Less and p2Less can be equal. All the arguments are the // same they both equal false, otherwise there were things that both // were the most specific type on.... if (p1Less == p2Less) { // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), // let's see which one has the most matches without using the params array (the longer one wins). if (!p1Less && args != null) { if (p1.Length > p2.Length) { return 1; } else if (p2.Length > p1.Length) { return 2; } } return 0; } else { return (p1Less == true) ? 1 : 2; } } private static int FindMostSpecificType(Type c1, Type c2, Type? t) { // If the two types are exact move on... if (c1 == c2) return 0; if (t is SignatureType signatureType) { if (signatureType.MatchesExactly(c1)) return 1; if (signatureType.MatchesExactly(c2)) return 2; } else { if (c1 == t) return 1; if (c2 == t) return 2; } bool c1FromC2; bool c2FromC1; if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType()!; c2 = c2.GetElementType()!; } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; c1 = c1.GetElementType()!; } else // if (c2.IsByRef) { if (c2.GetElementType() == c1) return 1; c2 = c2.GetElementType()!; } } if (c1.IsPrimitive && c2.IsPrimitive) { c1FromC2 = CanChangePrimitive(c2, c1); c2FromC1 = CanChangePrimitive(c1, c2); } else { c1FromC2 = c1.IsAssignableFrom(c2); c2FromC1 = c2.IsAssignableFrom(c1); } if (c1FromC2 == c2FromC1) return 0; if (c1FromC2) { return 2; } else { return 1; } } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type? paramArrayType1, MethodBase m2, int[] paramOrder2, Type? paramArrayType2, Type[] types, object?[]? args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args); // If the match was not ambigous then return the result. if (res != 0) return res; // Check to see if the methods have the exact same name and signature. if (CompareMethodSig(m1, m2)) { // Determine the depth of the declaring types for both methods. int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType!); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType!); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambigous. return 0; } private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } public static bool CompareMethodSig(MethodBase m1, MethodBase m2) { ParameterInfo[] params1 = m1.GetParametersNoCopy(); ParameterInfo[] params2 = m2.GetParametersNoCopy(); if (params1.Length != params2.Length) return false; int numParams = params1.Length; for (int i = 0; i < numParams; i++) { if (params1[i].ParameterType != params2[i].ParameterType) return false; } return true; } private static int GetHierarchyDepth(Type t) { int depth = 0; Type? currentType = t; do { depth++; currentType = currentType.BaseType; } while (currentType != null); return depth; } internal static MethodBase? FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; MethodBase? methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType!); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. if (currentHierarchyDepth == deepestHierarchy) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } // Check to see if this method is on the most derived class. if (currentHierarchyDepth > deepestHierarchy) { deepestHierarchy = currentHierarchyDepth; methWithDeepestHierarchy = match[i]; } } return methWithDeepestHierarchy; } // This method will sort the vars array into the mapping order stored // in the paramOrder array. private static void ReorderParams(int[] paramOrder, object?[] vars) { object?[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) varsCopy[i] = vars[i]; for (int i = 0; i < vars.Length; i++) vars[i] = varsCopy[paramOrder[i]]; } // This method will create the mapping between the Parameters and the underlying // data based upon the names array. The names array is stored in the same order // as the values and maps to the parameters of the method. We store the mapping // from the parameters to the names in the paramOrder array. All parameters that // don't have matching names are then stored in the array in order. private static bool CreateParamOrder(int[] paramOrder, ParameterInfo[] pars, string[] names) { bool[] used = new bool[pars.Length]; // Mark which parameters have not been found in the names list for (int i = 0; i < pars.Length; i++) paramOrder[i] = -1; // Find the parameters with names. for (int i = 0; i < names.Length; i++) { int j; for (j = 0; j < pars.Length; j++) { if (names[i].Equals(pars[j].Name)) { paramOrder[j] = i; used[i] = true; break; } } // This is an error condition. The name was not found. This // method must not match what we sent. if (j == pars.Length) return false; } // Now we fill in the holes with the parameters that are unused. int pos = 0; for (int i = 0; i < pars.Length; i++) { if (paramOrder[i] == -1) { for (; pos < pars.Length; pos++) { if (!used[pos]) { paramOrder[i] = pos; pos++; break; } } } } return true; } // CanChangePrimitive // This will determine if the source can be converted to the target type internal static bool CanChangePrimitive(Type? source, Type? target) { if ((source == typeof(IntPtr) && target == typeof(IntPtr)) || (source == typeof(UIntPtr) && target == typeof(UIntPtr))) return true; Primitives widerCodes = s_primitiveConversions[(int)(Type.GetTypeCode(source))]; Primitives targetCode = (Primitives)(1 << (int)(Type.GetTypeCode(target))); return (widerCodes & targetCode) != 0; } private static readonly Primitives[] s_primitiveConversions = { /* Empty */ 0, // not primitive /* Object */ 0, // not primitive /* DBNull */ 0, // not primitive /* Boolean */ Primitives.Boolean, /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, /* Single */ Primitives.Single | Primitives.Double, /* Double */ Primitives.Double, /* Decimal */ Primitives.Decimal, /* DateTime */ Primitives.DateTime, /* [Unused] */ 0, /* String */ Primitives.String, }; [Flags] private enum Primitives { Boolean = 1 << TypeCode.Boolean, Char = 1 << TypeCode.Char, SByte = 1 << TypeCode.SByte, Byte = 1 << TypeCode.Byte, Int16 = 1 << TypeCode.Int16, UInt16 = 1 << TypeCode.UInt16, Int32 = 1 << TypeCode.Int32, UInt32 = 1 << TypeCode.UInt32, Int64 = 1 << TypeCode.Int64, UInt64 = 1 << TypeCode.UInt64, Single = 1 << TypeCode.Single, Double = 1 << TypeCode.Double, Decimal = 1 << TypeCode.Decimal, DateTime = 1 << TypeCode.DateTime, String = 1 << TypeCode.String, } internal class BinderState { internal readonly int[] _argsMap; internal readonly int _originalSize; internal readonly bool _isParamArray; internal BinderState(int[] argsMap, int originalSize, bool isParamArray) { _argsMap = argsMap; _originalSize = originalSize; _isParamArray = isParamArray; } } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Diagnostics; using System.Threading; using System.Text; namespace OpenMetaverse.Voice { public partial class VoiceGateway { public delegate void DaemonRunningCallback(); public delegate void DaemonExitedCallback(); public delegate void DaemonCouldntRunCallback(); public delegate void DaemonConnectedCallback(); public delegate void DaemonDisconnectedCallback(); public delegate void DaemonCouldntConnectCallback(); public event DaemonRunningCallback OnDaemonRunning; public event DaemonExitedCallback OnDaemonExited; public event DaemonCouldntRunCallback OnDaemonCouldntRun; public event DaemonConnectedCallback OnDaemonConnected; public event DaemonDisconnectedCallback OnDaemonDisconnected; public event DaemonCouldntConnectCallback OnDaemonCouldntConnect; public bool DaemonIsRunning { get { return daemonIsRunning; } } public bool DaemonIsConnected { get { return daemonIsConnected; } } public int RequestId { get { return requestId; } } protected Process daemonProcess; protected ManualResetEvent daemonLoopSignal = new ManualResetEvent(false); protected TCPPipe daemonPipe; protected bool daemonIsRunning = false; protected bool daemonIsConnected = false; protected int requestId = 0; #region Daemon Management /// <summary> /// Starts a thread that keeps the daemon running /// </summary> /// <param name="path"></param> /// <param name="args"></param> public void StartDaemon(string path, string args) { StopDaemon(); daemonLoopSignal.Set(); Thread thread = new Thread(new ThreadStart(delegate() { while (daemonLoopSignal.WaitOne(500, false)) { daemonProcess = new Process(); daemonProcess.StartInfo.FileName = path; daemonProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(path); daemonProcess.StartInfo.Arguments = args; daemonProcess.StartInfo.UseShellExecute = false; if (Environment.OSVersion.Platform == PlatformID.Unix) { string ldPath = string.Empty; try { ldPath = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH"); } catch { } string newLdPath = daemonProcess.StartInfo.WorkingDirectory; if (!string.IsNullOrEmpty(ldPath)) newLdPath += ":" + ldPath; daemonProcess.StartInfo.EnvironmentVariables.Add("LD_LIBRARY_PATH", newLdPath); } Logger.DebugLog("Voice folder: " + daemonProcess.StartInfo.WorkingDirectory); Logger.DebugLog(path + " " + args); bool ok = true; if (!File.Exists(path)) ok = false; if (ok) { // Attempt to start the process if (!daemonProcess.Start()) ok = false; } if (!ok) { daemonIsRunning = false; daemonLoopSignal.Reset(); if (OnDaemonCouldntRun != null) { try { OnDaemonCouldntRun(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return; } else { Thread.Sleep(2000); daemonIsRunning = true; if (OnDaemonRunning != null) { try { OnDaemonRunning(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.DebugLog("Started voice daemon, waiting for exit..."); daemonProcess.WaitForExit(); Logger.DebugLog("Voice daemon exited"); daemonIsRunning = false; if (OnDaemonExited != null) { try { OnDaemonExited(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } } } })); thread.Name = "VoiceDaemonController"; thread.IsBackground = true; thread.Start(); } /// <summary> /// Stops the daemon and the thread keeping it running /// </summary> public void StopDaemon() { daemonLoopSignal.Reset(); if (daemonProcess != null) { try { daemonProcess.Kill(); } catch (InvalidOperationException ex) { Logger.Log("Failed to stop the voice daemon", Helpers.LogLevel.Error, ex); } } } /// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <returns></returns> public bool ConnectToDaemon(string address, int port) { daemonIsConnected = false; daemonPipe = new TCPPipe(); daemonPipe.OnDisconnected += delegate(SocketException e) { if (OnDaemonDisconnected != null) { try { OnDaemonDisconnected(); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, null, ex); } } }; daemonPipe.OnReceiveLine += new TCPPipe.OnReceiveLineCallback(daemonPipe_OnReceiveLine); SocketException se = daemonPipe.Connect(address, port); if (se == null) { daemonIsConnected = true; if (OnDaemonConnected != null) { try { OnDaemonConnected(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } return true; } else { daemonIsConnected = false; if (OnDaemonCouldntConnect != null) { try { OnDaemonCouldntConnect(); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, null, e); } } Logger.Log("Voice daemon connection failed: " + se.Message, Helpers.LogLevel.Error); return false; } } #endregion Daemon Management public int Request(string action) { return Request(action, null); } public int Request(string action, string requestXML) { int returnId = requestId; if (daemonIsConnected) { StringBuilder sb = new StringBuilder(); sb.Append(String.Format("<Request requestId=\"{0}\" action=\"{1}\"", requestId++, action)); if (string.IsNullOrEmpty(requestXML)) { sb.Append(" />"); } else { sb.Append(">"); sb.Append(requestXML); sb.Append("</Request>"); } sb.Append("\n\n\n"); #if DEBUG Logger.Log("Request: " + sb.ToString(), Helpers.LogLevel.Debug); #endif try { daemonPipe.SendData(Encoding.ASCII.GetBytes(sb.ToString())); } catch { returnId = -1; } return returnId; } else { return -1; } } public static string MakeXML(string name, string text) { if (string.IsNullOrEmpty(text)) return string.Format("<{0} />", name); else return string.Format("<{0}>{1}</{0}>", name, text); } private void daemonPipe_OnReceiveLine(string line) { #if DEBUG Logger.Log(line, Helpers.LogLevel.Debug); #endif if (line.Substring(0, 10) == "<Response ") { VoiceResponse rsp = null; try { rsp = (VoiceResponse)ResponseSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon response", Helpers.LogLevel.Error, e); return; } ResponseType genericResponse = ResponseType.None; switch (rsp.Action) { // These first responses carry useful information beyond simple status, // so they each have a specific Event. case "Connector.Create.1": if (OnConnectorCreateResponse != null) { OnConnectorCreateResponse( rsp.InputXml.Request, new VoiceConnectorEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.VersionID, rsp.Results.ConnectorHandle)); } break; case "Aux.GetCaptureDevices.1": inputDevices = new List<string>(); if (rsp.Results.CaptureDevices.Count == 0 || rsp.Results.CurrentCaptureDevice == null) break; foreach (CaptureDevice device in rsp.Results.CaptureDevices) inputDevices.Add(device.Device); currentCaptureDevice = rsp.Results.CurrentCaptureDevice.Device; if (OnAuxGetCaptureDevicesResponse != null && rsp.Results.CaptureDevices.Count > 0) { OnAuxGetCaptureDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentCaptureDevice.Device, inputDevices)); } break; case "Aux.GetRenderDevices.1": outputDevices = new List<string>(); if (rsp.Results.RenderDevices.Count == 0 || rsp.Results.CurrentRenderDevice == null) break; foreach (RenderDevice device in rsp.Results.RenderDevices) outputDevices.Add(device.Device); currentPlaybackDevice = rsp.Results.CurrentRenderDevice.Device; if (OnAuxGetRenderDevicesResponse != null) { OnAuxGetRenderDevicesResponse( rsp.InputXml.Request, new VoiceDevicesEventArgs( ResponseType.GetCaptureDevices, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.CurrentRenderDevice.Device, outputDevices)); } break; case "Account.Login.1": if (OnAccountLoginResponse != null) { OnAccountLoginResponse(rsp.InputXml.Request, new VoiceAccountEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.AccountHandle)); } break; case "Session.Create.1": if (OnSessionCreateResponse != null) { OnSessionCreateResponse( rsp.InputXml.Request, new VoiceSessionEventArgs( int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.SessionHandle)); } break; // All the remaining responses below this point just report status, // so they all share the same Event. Most are useful only for // detecting coding errors. case "Connector.InitiateShutdown.1": genericResponse = ResponseType.ConnectorInitiateShutdown; break; case "Aux.SetRenderDevice.1": genericResponse = ResponseType.SetRenderDevice; break; case "Connector.MuteLocalMic.1": genericResponse = ResponseType.MuteLocalMic; break; case "Connector.MuteLocalSpeaker.1": genericResponse = ResponseType.MuteLocalSpeaker; break; case "Connector.SetLocalMicVolume.1": genericResponse = ResponseType.SetLocalMicVolume; break; case "Connector.SetLocalSpeakerVolume.1": genericResponse = ResponseType.SetLocalSpeakerVolume; break; case "Aux.SetCaptureDevice.1": genericResponse = ResponseType.SetCaptureDevice; break; case "Session.RenderAudioStart.1": genericResponse = ResponseType.RenderAudioStart; break; case "Session.RenderAudioStop.1": genericResponse = ResponseType.RenderAudioStop; break; case "Aux.CaptureAudioStart.1": genericResponse = ResponseType.CaptureAudioStart; break; case "Aux.CaptureAudioStop.1": genericResponse = ResponseType.CaptureAudioStop; break; case "Aux.SetMicLevel.1": genericResponse = ResponseType.SetMicLevel; break; case "Aux.SetSpeakerLevel.1": genericResponse = ResponseType.SetSpeakerLevel; break; case "Account.Logout.1": genericResponse = ResponseType.AccountLogout; break; case "Session.Connect.1": genericResponse = ResponseType.SessionConnect; break; case "Session.Terminate.1": genericResponse = ResponseType.SessionTerminate; break; case "Session.SetParticipantVolumeForMe.1": genericResponse = ResponseType.SetParticipantVolumeForMe; break; case "Session.SetParticipantMuteForMe.1": genericResponse = ResponseType.SetParticipantMuteForMe; break; case "Session.Set3DPosition.1": genericResponse = ResponseType.Set3DPosition; break; default: Logger.Log("Unimplemented response from the voice daemon: " + line, Helpers.LogLevel.Error); break; } // Send the Response Event for all the simple cases. if (genericResponse != ResponseType.None && OnVoiceResponse != null) { OnVoiceResponse(rsp.InputXml.Request, new VoiceResponseEventArgs( genericResponse, int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString)); } } else if (line.Substring(0, 7) == "<Event ") { VoiceEvent evt = null; try { evt = (VoiceEvent)EventSerializer.Deserialize(new StringReader(line)); } catch (Exception e) { Logger.Log("Failed to deserialize voice daemon event", Helpers.LogLevel.Error, e); return; } switch (evt.Type) { case "LoginStateChangeEvent": case "AccountLoginStateChangeEvent": if (OnAccountLoginStateChangeEvent != null) { OnAccountLoginStateChangeEvent(this, new AccountLoginStateChangeEventArgs( evt.AccountHandle, int.Parse(evt.StatusCode), evt.StatusString, (LoginState)int.Parse(evt.State))); } break; case "SessionNewEvent": if (OnSessionNewEvent != null) { OnSessionNewEvent(this, new NewSessionEventArgs( evt.AccountHandle, evt.SessionHandle, evt.URI, bool.Parse(evt.IsChannel), evt.Name, evt.AudioMedia)); } break; case "SessionStateChangeEvent": if (OnSessionStateChangeEvent != null) { OnSessionStateChangeEvent(this, new SessionStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (SessionState)int.Parse(evt.State), evt.URI, bool.Parse(evt.IsChannel), evt.ChannelName)); } break; case "ParticipantAddedEvent": Logger.Log("Add participant " + evt.ParticipantUri, Helpers.LogLevel.Debug); if (OnSessionParticipantAddedEvent != null) { OnSessionParticipantAddedEvent(this, new ParticipantAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType), evt.Application)); } break; case "ParticipantRemovedEvent": if (OnSessionParticipantRemovedEvent != null) { OnSessionParticipantRemovedEvent(this, new ParticipantRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.ParticipantUri, evt.AccountName, evt.Reason)); } break; case "ParticipantStateChangeEvent": // Useful in person-to-person calls if (OnSessionParticipantStateChangeEvent != null) { OnSessionParticipantStateChangeEvent(this, new ParticipantStateChangeEventArgs( evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (ParticipantState)int.Parse(evt.State), // Ringing, Connected, etc evt.ParticipantUri, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType))); } break; case "ParticipantPropertiesEvent": if (OnSessionParticipantPropertiesEvent != null) { OnSessionParticipantPropertiesEvent(this, new ParticipantPropertiesEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsLocallyMuted), bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "ParticipantUpdatedEvent": if (OnSessionParticipantUpdatedEvent != null) { OnSessionParticipantUpdatedEvent(this, new ParticipantUpdatedEventArgs( evt.SessionHandle, evt.ParticipantUri, bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy))); } break; case "SessionGroupAddedEvent": if (OnSessionGroupAddedEvent != null) { OnSessionGroupAddedEvent(this, new SessionGroupAddedEventArgs( evt.AccountHandle, evt.SessionGroupHandle, evt.Type)); } break; case "SessionAddedEvent": if (OnSessionAddedEvent != null) { OnSessionAddedEvent(this, new SessionAddedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, bool.Parse(evt.IsChannel), bool.Parse(evt.Incoming))); } break; case "SessionRemovedEvent": if (OnSessionRemovedEvent != null) { OnSessionRemovedEvent(this, new SessionRemovedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri)); } break; case "SessionUpdatedEvent": if (OnSessionRemovedEvent != null) { OnSessionUpdatedEvent(this, new SessionUpdatedEventArgs( evt.SessionGroupHandle, evt.SessionHandle, evt.Uri, int.Parse(evt.IsMuted) != 0, int.Parse(evt.Volume), int.Parse(evt.TransmitEnabled) != 0, + int.Parse(evt.IsFocused) != 0)); } break; case "AuxAudioPropertiesEvent": if (OnAuxAudioPropertiesEvent != null) { OnAuxAudioPropertiesEvent(this, new AudioPropertiesEventArgs( bool.Parse(evt.MicIsActive), float.Parse(evt.MicEnergy), int.Parse(evt.MicVolume), int.Parse(evt.SpeakerVolume))); } break; case "SessionMediaEvent": if (OnSessionMediaEvent != null) { OnSessionMediaEvent(this, new SessionMediaEventArgs( evt.SessionHandle, bool.Parse(evt.HasText), bool.Parse(evt.HasAudio), bool.Parse(evt.HasVideo), bool.Parse(evt.Terminated))); } break; case "BuddyAndGroupListChangedEvent": // TODO * <AccountHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==</AccountHandle><Buddies /><Groups /> break; case "MediaStreamUpdatedEvent": // TODO <SessionGroupHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==_sg0</SessionGroupHandle> // <SessionHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==0</SessionHandle> //<StatusCode>0</StatusCode><StatusString /><State>1</State><Incoming>false</Incoming> break; default: Logger.Log("Unimplemented event from the voice daemon: " + line, Helpers.LogLevel.Error); break; } } else { Logger.Log("Unrecognized data from the voice daemon: " + line, Helpers.LogLevel.Error); } } } }
//------------------------------------------------------------------------------ // <copyright file="DBDataPermission.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System.Collections; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, ControlEvidence=true, ControlPolicy=true)] [Serializable] public abstract class DBDataPermission : CodeAccessPermission, IUnrestrictedPermission { private bool _isUnrestricted;// = false; private bool _allowBlankPassword;// = false; private NameValuePermission _keyvaluetree = NameValuePermission.Default; private /*DBConnectionString[]*/ArrayList _keyvalues; // = null; [ Obsolete("DBDataPermission() has been deprecated. Use the DBDataPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true) ] // V1.2.3300, MDAC 86034 protected DBDataPermission() : this(PermissionState.None) { // V1.0.3300 } protected DBDataPermission(PermissionState state) { // V1.0.3300 if (state == PermissionState.Unrestricted) { _isUnrestricted = true; } else if (state == PermissionState.None) { _isUnrestricted = false; } else { throw ADP.InvalidPermissionState(state); } } [ Obsolete("DBDataPermission(PermissionState state,Boolean allowBlankPassword) has been deprecated. Use the DBDataPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true) ] // V1.2.3300, MDAC 86034 protected DBDataPermission(PermissionState state, bool allowBlankPassword) : this(state) { // V1.0.3300, MDAC 84281 AllowBlankPassword = allowBlankPassword; } protected DBDataPermission(DBDataPermission permission) { // V1.0.5000, for Copy if (null == permission) { throw ADP.ArgumentNull("permissionAttribute"); } CopyFrom(permission); } protected DBDataPermission(DBDataPermissionAttribute permissionAttribute) { // V1.0.5000, for CreatePermission if (null == permissionAttribute) { throw ADP.ArgumentNull("permissionAttribute"); } _isUnrestricted = permissionAttribute.Unrestricted; if (!_isUnrestricted) { _allowBlankPassword = permissionAttribute.AllowBlankPassword; if (permissionAttribute.ShouldSerializeConnectionString() || permissionAttribute.ShouldSerializeKeyRestrictions()) { // MDAC 86773 Add(permissionAttribute.ConnectionString, permissionAttribute.KeyRestrictions, permissionAttribute.KeyRestrictionBehavior); } } } // how connectionString security is used // parsetable (all string) is shared with connection internal DBDataPermission(DbConnectionOptions connectionOptions) { // v2.0 if (null != connectionOptions) { _allowBlankPassword = connectionOptions.HasBlankPassword; // MDAC 84563 AddPermissionEntry(new DBConnectionString(connectionOptions)); } } public bool AllowBlankPassword { // V1.0.3300 get { return _allowBlankPassword; } set { // MDAC 61263 // for behavioral backward compatability with V1.1 // set_AllowBlankPassword does not _isUnrestricted=false _allowBlankPassword = value; } } public virtual void Add(string connectionString, string restrictions, KeyRestrictionBehavior behavior) { // V1.0.5000 DBConnectionString constr = new DBConnectionString(connectionString, restrictions, behavior, null, false); AddPermissionEntry(constr); } internal void AddPermissionEntry(DBConnectionString entry) { if (null == _keyvaluetree) { _keyvaluetree = new NameValuePermission(); } if (null == _keyvalues) { _keyvalues = new ArrayList(); } NameValuePermission.AddEntry(_keyvaluetree, _keyvalues, entry); _isUnrestricted = false; // MDAC 84639 } protected void Clear() { // V1.2.3300, MDAC 83105 _keyvaluetree = null; _keyvalues = null; } // IPermission interface methods // [ObsoleteAttribute("override Copy instead of using default implementation")] // not inherited override public IPermission Copy() { DBDataPermission copy = CreateInstance(); copy.CopyFrom(this); return copy; } private void CopyFrom(DBDataPermission permission) { _isUnrestricted = permission.IsUnrestricted(); if (!_isUnrestricted) { _allowBlankPassword = permission.AllowBlankPassword; if (null != permission._keyvalues) { _keyvalues = (ArrayList) permission._keyvalues.Clone(); if (null != permission._keyvaluetree) { _keyvaluetree = permission._keyvaluetree.CopyNameValue(); } } } } // [ Obsolete("use DBDataPermission(DBDataPermission) ctor") ] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] // V1.0.5000, MDAC 82936 virtual protected DBDataPermission CreateInstance() { // derived class should override with a different implementation avoiding reflection to allow semi-trusted scenarios return (Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null) as DBDataPermission); } override public IPermission Intersect(IPermission target) { // used during Deny actions if (null == target) { return null; } if (target.GetType() != this.GetType()) { throw ADP.PermissionTypeMismatch(); } if (this.IsUnrestricted()) { // MDAC 84803, NDPWhidbey 29121 return target.Copy(); } DBDataPermission operand = (DBDataPermission) target; if (operand.IsUnrestricted()) { // NDPWhidbey 29121 return this.Copy(); } DBDataPermission newPermission = (DBDataPermission) operand.Copy(); newPermission._allowBlankPassword &= AllowBlankPassword; if ((null != _keyvalues) && (null != newPermission._keyvalues)) { newPermission._keyvalues.Clear(); newPermission._keyvaluetree.Intersect(newPermission._keyvalues, _keyvaluetree); } else { // either target.Add or this.Add have not been called // return a non-null object so IsSubset calls will fail newPermission._keyvalues = null; newPermission._keyvaluetree = null; } if (newPermission.IsEmpty()) { // no intersection, MDAC 86773 newPermission = null; } return newPermission; } private bool IsEmpty() { // MDAC 84804 ArrayList keyvalues = _keyvalues; bool flag = (!IsUnrestricted() && !AllowBlankPassword && ((null == keyvalues) || (0 == keyvalues.Count))); return flag; } override public bool IsSubsetOf(IPermission target) { if (null == target) { return IsEmpty(); } if (target.GetType() != this.GetType()) { throw ADP.PermissionTypeMismatch(); } DBDataPermission superset = (target as DBDataPermission); bool subset = superset.IsUnrestricted(); if (!subset) { if (!IsUnrestricted() && (!AllowBlankPassword || superset.AllowBlankPassword) && ((null == _keyvalues) || (null != superset._keyvaluetree))) { subset = true; if (null != _keyvalues) { foreach(DBConnectionString kventry in _keyvalues) { if(!superset._keyvaluetree.CheckValueForKeyPermit(kventry)) { subset = false; break; } } } } } return subset; } // IUnrestrictedPermission interface methods public bool IsUnrestricted() { return _isUnrestricted; } override public IPermission Union(IPermission target) { if (null == target) { return this.Copy(); } if (target.GetType() != this.GetType()) { throw ADP.PermissionTypeMismatch(); } if (IsUnrestricted()) { // MDAC 84803 return this.Copy(); } DBDataPermission newPermission = (DBDataPermission) target.Copy(); if (!newPermission.IsUnrestricted()) { newPermission._allowBlankPassword |= AllowBlankPassword; if (null != _keyvalues) { foreach(DBConnectionString entry in _keyvalues) { newPermission.AddPermissionEntry(entry); } } } return (newPermission.IsEmpty() ? null : newPermission); } private string DecodeXmlValue(string value) { if ((null != value) && (0 < value.Length)) { value = value.Replace("&quot;", "\""); value = value.Replace("&apos;", "\'"); value = value.Replace("&lt;", "<"); value = value.Replace("&gt;", ">"); value = value.Replace("&amp;", "&"); } return value; } private string EncodeXmlValue(string value) { if ((null != value) && (0 < value.Length)) { value = value.Replace('\0', ' '); // assumption that '\0' will only be at end of string value = value.Trim(); value = value.Replace("&", "&amp;"); value = value.Replace(">", "&gt;"); value = value.Replace("<", "&lt;"); value = value.Replace("\'", "&apos;"); value = value.Replace("\"", "&quot;"); } return value; } // <IPermission class="...Permission" version="1" AllowBlankPassword=false> // <add ConnectionString="provider=x;data source=y;" KeyRestrictions="address=;server=" KeyRestrictionBehavior=PreventUsage/> // </IPermission> override public void FromXml(SecurityElement securityElement) { // code derived from CodeAccessPermission.ValidateElement if (null == securityElement) { throw ADP.ArgumentNull("securityElement"); } string tag = securityElement.Tag; if (!tag.Equals(XmlStr._Permission) && !tag.Equals(XmlStr._IPermission)) { throw ADP.NotAPermissionElement(); } String version = securityElement.Attribute(XmlStr._Version); if ((null != version) && !version.Equals(XmlStr._VersionNumber)) { throw ADP.InvalidXMLBadVersion(); } string unrestrictedValue = securityElement.Attribute(XmlStr._Unrestricted); _isUnrestricted = (null != unrestrictedValue) && Boolean.Parse(unrestrictedValue); Clear(); // MDAC 83105 if (!_isUnrestricted) { string allowNull = securityElement.Attribute(XmlStr._AllowBlankPassword); _allowBlankPassword = (null != allowNull) && Boolean.Parse(allowNull); ArrayList children = securityElement.Children; if (null != children) { foreach(SecurityElement keyElement in children) { tag = keyElement.Tag; if ((XmlStr._add == tag) || ((null != tag) && (XmlStr._add == tag.ToLower(CultureInfo.InvariantCulture)))) { string constr = keyElement.Attribute(XmlStr._ConnectionString); string restrt = keyElement.Attribute(XmlStr._KeyRestrictions); string behavr = keyElement.Attribute(XmlStr._KeyRestrictionBehavior); KeyRestrictionBehavior behavior = KeyRestrictionBehavior.AllowOnly; if (null != behavr) { behavior = (KeyRestrictionBehavior) Enum.Parse(typeof(KeyRestrictionBehavior), behavr, true); } constr = DecodeXmlValue(constr); restrt = DecodeXmlValue(restrt); Add(constr, restrt, behavior); } } } } else { _allowBlankPassword = false; } } // <IPermission class="...Permission" version="1" AllowBlankPassword=false> // <add ConnectionString="provider=x;data source=y;"/> // <add ConnectionString="provider=x;data source=y;" KeyRestrictions="user id=;password=;" KeyRestrictionBehavior=AllowOnly/> // <add ConnectionString="provider=x;data source=y;" KeyRestrictions="address=;server=" KeyRestrictionBehavior=PreventUsage/> // </IPermission> override public SecurityElement ToXml() { Type type = this.GetType(); SecurityElement root = new SecurityElement(XmlStr._IPermission); root.AddAttribute(XmlStr._class, type.AssemblyQualifiedName.Replace('\"', '\'')); root.AddAttribute(XmlStr._Version, XmlStr._VersionNumber); if (IsUnrestricted()) { root.AddAttribute(XmlStr._Unrestricted, XmlStr._true); } else { root.AddAttribute(XmlStr._AllowBlankPassword, _allowBlankPassword.ToString(CultureInfo.InvariantCulture)); if (null != _keyvalues) { foreach(DBConnectionString value in _keyvalues) { SecurityElement valueElement = new SecurityElement(XmlStr._add); string tmp; tmp = value.ConnectionString; // WebData 97375 tmp = EncodeXmlValue(tmp); if (!ADP.IsEmpty(tmp)) { valueElement.AddAttribute(XmlStr._ConnectionString, tmp); } tmp = value.Restrictions; tmp = EncodeXmlValue(tmp); if (null == tmp) { tmp = ADP.StrEmpty; } valueElement.AddAttribute(XmlStr._KeyRestrictions, tmp); tmp = value.Behavior.ToString(); valueElement.AddAttribute(XmlStr._KeyRestrictionBehavior, tmp); root.AddChild(valueElement); } } } return root; } private static class XmlStr { internal const string _class = "class"; internal const string _IPermission = "IPermission"; internal const string _Permission = "Permission"; internal const string _Unrestricted = "Unrestricted"; internal const string _AllowBlankPassword = "AllowBlankPassword"; internal const string _true = "true"; internal const string _Version = "version"; internal const string _VersionNumber = "1"; internal const string _add = "add"; internal const string _ConnectionString = "ConnectionString"; internal const string _KeyRestrictions = "KeyRestrictions"; internal const string _KeyRestrictionBehavior = "KeyRestrictionBehavior"; } } }
// 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 Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class ImplementIDisposableCorrectlyTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new ImplementIDisposableCorrectlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new ImplementIDisposableCorrectlyAnalyzer(); } #region CSharp Unit Tests [Fact] public void CSharp_CA1063_DisposeSignature_NoDiagnostic_GoodDisposablePattern() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } "); } [Fact] public void CSharp_CA1063_DisposeSignature_NoDiagnostic_NotImplementingDisposable() { VerifyCSharp(@" using System; public class C { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } "); } #endregion #region CSharp IDisposableReimplementation Unit Tests [Fact] public void CSharp_CA1063_IDisposableReimplementation_Diagnostic_ReimplementingIDisposable() { VerifyCSharp(@" using System; public class B : IDisposable { public virtual void Dispose() { } } [|public class C : B, IDisposable { public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } }|] ", GetCA1063CSharpIDisposableReimplementationResultAt(11, 14, "C", "B"), GetCA1063CSharpDisposeSignatureResultAt(13, 26, "C", "Dispose")); } [Fact] public void CSharp_CA1063_IDisposableReimplementation_Diagnostic_ReimplementingIDisposableWithDeepInheritance() { VerifyCSharp(@" using System; public class A : IDisposable { public virtual void Dispose() { } } public class B : A { } [|public class C : B, IDisposable { public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } }|] ", GetCA1063CSharpIDisposableReimplementationResultAt(15, 14, "C", "B"), GetCA1063CSharpDisposeSignatureResultAt(17, 26, "C", "Dispose")); } [Fact] public void CSharp_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInterfaceInheritedFromIDisposable() { VerifyCSharp(@" using System; public interface ITest : IDisposable { int Test { get; set; } } public class B : IDisposable { public void Dispose() { } } [|public class C : B, ITest { public int Test { get; set; } public new void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } }|] "); } [Fact] public void CSharp_CA1063_IDisposableReimplementation_NoDiagnostic_ReImplementingIDisposableWithNoDisposeMethod() { VerifyCSharp(@" using System; public interface ITest : IDisposable { int Test { get; set; } } public class B : IDisposable { public void Dispose() { } } [|public class C : B, ITest, IDisposable { public int Test { get; set; } }|] ", GetCA1063CSharpIDisposableReimplementationResultAt(16, 14, "C", "B")); } [Fact] public void CSharp_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation() { VerifyCSharp(@" using System; public interface ITest : IDisposable { int Test { get; set; } } public class B : IDisposable { public void Dispose() { } } [|public class C : B, ITest { public int Test { get; set; } }|] "); } #endregion #region CSharp DisposeSignature Unit Tests [Fact] public void CSharp_CA1063_DisposeSignature_Diagnostic_DisposeNotPublic() { VerifyCSharp(@" using System; public class C : IDisposable { void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeSignatureResultAt(6, 22, "C", "System.IDisposable.Dispose"), GetCA1063CSharpRenameDisposeResultAt(6, 22, "C", "System.IDisposable.Dispose")); } [Fact] public void CSharp_CA1063_DisposeSignature_Diagnostic_DisposeIsVirtual() { VerifyCSharp(@" using System; public class C : IDisposable { public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeSignatureResultAt(6, 25, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeSignature_Diagnostic_DisposeIsOverriden() { VerifyCSharp(@" using System; public class B { public virtual void Dispose() { } } public class C : B, IDisposable { public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeSignatureResultAt(13, 26, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeSignature_NoDiagnostic_DisposeIsOverridenAndSealed() { VerifyCSharp(@" using System; public class B { public virtual void Dispose() { } } public class C : B, IDisposable { public sealed override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } "); } #endregion #region CSharp DisposeOverride Unit Tests [Fact] public void CSharp_CA1063_DisposeOverride_Diagnostic_SimpleDisposeOverride() { VerifyCSharp(@" using System; public class B : IDisposable { public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~B() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } [|public class C : B { public override void Dispose() { } }|] ", GetCA1063CSharpDisposeOverrideResultAt(24, 26, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeOverride_Diagnostic_DoubleDisposeOverride() { VerifyCSharp(@" using System; public class A : IDisposable { public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~A() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } public class B : A { public override void Dispose() { } } [|public class C : B { public override void Dispose() { Dispose(true); } }|] ", GetCA1063CSharpDisposeOverrideResultAt(31, 26, "C", "Dispose")); } #endregion #region CSharp FinalizeOverride Unit Tests [Fact] public void CSharp_CA1063_FinalizeOverride_Diagnostic_SimpleFinalizeOverride() { VerifyCSharp(@" using System; public class B : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~B() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } [|public class C : B { ~C() { } }|] ", GetCA1063CSharpFinalizeOverrideResultAt(22, 14, "C")); } [Fact] public void CSharp_CA1063_FinalizeOverride_Diagnostic_DoubleFinalizeOverride() { VerifyCSharp(@" using System; public class A : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~A() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } public class B : A { ~B() { } } [|public class C : B { ~C() { } }|] ", GetCA1063CSharpFinalizeOverrideResultAt(29, 14, "C")); } [Fact] public void CSharp_CA1063_FinalizeOverride_NoDiagnostic_FinalizeNotInBaseType() { VerifyCSharp(@" using System; public class B : IDisposable { public void Dispose() { } } [|public class C : B { ~C() { } }|] "); } #endregion #region CSharp ProvideDisposeBool Unit Tests [Fact] public void CSharp_CA1063_ProvideDisposeBool_Diagnostic_MissingDisposeBool() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { } ~C() { } } ", GetCA1063CSharpProvideDisposeBoolResultAt(4, 14, "C"), GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_ProvideDisposeBool_NoDiagnostic_SealedClassAndMissingDisposeBool() { VerifyCSharp(@" using System; public sealed class C : IDisposable { public void Dispose() { } ~C() { } } "); } #endregion #region CSharp DisposeBoolSignature Unit Tests [Fact] public void CSharp_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsPublic() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } public virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeBoolSignatureResultAt(17, 25, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsProtectedInternal() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected internal virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeBoolSignatureResultAt(17, 37, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsNotVirtual() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeBoolSignatureResultAt(17, 20, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsSealedOverriden() { VerifyCSharp(@" using System; public abstract class B { protected abstract void Dispose(bool disposing); } public class C : B, IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected sealed override void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeBoolSignatureResultAt(22, 36, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsOverriden() { VerifyCSharp(@" using System; public abstract class B { protected abstract void Dispose(bool disposing); } public class C : B, IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected override void Dispose(bool disposing) { } } "); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsAbstract() { VerifyCSharp(@" using System; public abstract class C : IDisposable { public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected abstract void Dispose(bool disposing); } "); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsPublicAndClassIsSealed() { VerifyCSharp(@" using System; public sealed class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } public void Dispose(bool disposing) { } } "); } [Fact] public void CSharp_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsPrivateAndClassIsSealed() { VerifyCSharp(@" using System; public sealed class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } private void Dispose(bool disposing) { } } "); } #endregion #region CSharp DisposeImplementation Unit Tests [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_MissingCallDisposeBool() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_MissingCallSuppressFinalize() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_EmptyDisposeBody() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_CallDisposeWithFalseArgument() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(false); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_ConditionalStatement() { VerifyCSharp(@" using System; public class C : IDisposable { private bool disposed; public void Dispose() { if (!disposed) { Dispose(true); GC.SuppressFinalize(this); } } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(8, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_Diagnostic_CallDisposeBoolTwice() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(6, 17, "C", "Dispose")); } [Fact] public void CSharp_CA1063_DisposeImplementation_NoDiagnostic_EmptyDisposeBodyInSealedClass() { VerifyCSharp(@" using System; public sealed class C : IDisposable { public void Dispose() { } ~C() { } } "); } #endregion #region CSharp FinalizeImplementation Unit Tests [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void CSharp_CA1063_FinalizeImplementation_Diagnostic_MissingCallDisposeBool() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(12, 5, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void CSharp_CA1063_FinalizeImplementation_Diagnostic_CallDisposeWithTrueArgument() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(true); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(12, 5, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void CSharp_CA1063_FinalizeImplementation_Diagnostic_ConditionalStatement() { VerifyCSharp(@" using System; public class C : IDisposable { private bool disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { if (!disposed) { Dispose(false); } } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(14, 5, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void CSharp_CA1063_FinalizeImplementation_Diagnostic_CallDisposeBoolTwice() { VerifyCSharp(@" using System; public class C : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~C() { Dispose(false); Dispose(false); } protected virtual void Dispose(bool disposing) { } } ", GetCA1063CSharpDisposeImplementationResultAt(12, 5, "C", "Finalize")); } #endregion #region VB Unit Tests [Fact] public void Basic_CA1063_DisposeSignature_NoDiagnostic_GoodDisposablePattern() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class "); } [Fact] public void Basic_CA1063_DisposeSignature_NoDiagnostic_NotImplementingDisposable() { VerifyBasic(@" Imports System Public Class C Public Sub Dispose() Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class "); } #endregion #region VB IDisposableReimplementation Unit Tests [Fact] public void Basic_CA1063_IDisposableReimplementation_Diagnostic_ReimplementingIDisposable() { VerifyBasic(@" Imports System Public Class B Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose End Sub End Class [|Public Class C Inherits B Implements IDisposable Public Overrides Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Overloads Sub Dispose(disposing As Boolean) End Sub End Class|] ", GetCA1063BasicIDisposableReimplementationResultAt(11, 14, "C", "B"), GetCA1063BasicDisposeSignatureResultAt(15, 26, "C", "Dispose")); } [Fact] public void Basic_CA1063_IDisposableReimplementation_Diagnostic_ReimplementingIDisposableWithDeepInheritance() { VerifyBasic(@" Imports System Public Class A Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose End Sub End Class Public Class B Inherits A End Class [|Public Class C Inherits B Implements IDisposable Public Overrides Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Overloads Sub Dispose(disposing As Boolean) End Sub End Class|] ", GetCA1063BasicIDisposableReimplementationResultAt(15, 14, "C", "B"), GetCA1063BasicDisposeSignatureResultAt(19, 26, "C", "Dispose")); } [Fact] public void Basic_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInterfaceInheritedFromIDisposable() { VerifyBasic(@" Imports System Public Interface ITest Inherits IDisposable Property Test As Integer End Interface Public Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class [|Public Class C Inherits B Implements ITest Public Property Test As Integer Implements ITest.Test Public Overloads Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Overloads Sub Dispose(disposing As Boolean) End Sub End Class|] "); } [Fact] public void Basic_CA1063_IDisposableReimplementation_Diagnostic_ReImplementingIDisposableWithNoDisposeMethod() { VerifyBasic(@" Imports System Public Interface ITest Inherits IDisposable Property Test As Integer End Interface Public Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class [|Public NotInheritable Class C Inherits B Implements ITest Implements IDisposable Public Property Test As Integer Implements ITest.Test End Class|] ", GetCA1063BasicIDisposableReimplementationResultAt(17, 29, "C", "B")); } [Fact] public void Basic_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation() { VerifyBasic(@" Imports System Public Interface ITest Inherits IDisposable Property Test As Integer End Interface Public Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class [|Public NotInheritable Class C Inherits B Implements ITest Public Property Test As Integer Implements ITest.Test End Class|] "); } #endregion #region VB DisposeSignature Unit Tests [Fact] public void Basic_CA1063_DisposeSignature_Diagnostic_DisposeProtected() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Protected Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeSignatureResultAt(7, 19, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeSignature_Diagnostic_DisposePrivate() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Private Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeSignatureResultAt(7, 17, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeSignature_Diagnostic_DisposeIsVirtual() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeSignatureResultAt(7, 28, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeSignature_Diagnostic_DisposeIsOverriden() { VerifyBasic(@" Imports System Public Class B Public Overridable Sub Dispose() End Sub End Class Public Class C Inherits B Implements IDisposable Public Overrides Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Overloads Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeSignatureResultAt(13, 26, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeSignature_Diagnostic_DisposeIsOverridenAndSealed() { VerifyBasic(@" Imports System Public Class B Public Overridable Sub Dispose() End Sub End Class Public Class C Inherits B Implements IDisposable Public NotOverridable Overrides Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Overloads Sub Dispose(disposing As Boolean) End Sub End Class "); } #endregion #region VB RenameDispose Unit Tests [Fact] public void Basic_CA1063_RenameDispose_Diagnostic_DisposeNamedD() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub D() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicRenameDisposeResultAt(7, 16, "C", "D")); } #endregion #region VB DisposeOverride Unit Tests [Fact] public void Basic_CA1063_DisposeOverride_Diagnostic_SimpleDisposeOverride() { VerifyBasic(@" Imports System Public Class B Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class [|Public Class C Inherits B Public Overrides Sub Dispose() End Sub End Class|] ", GetCA1063BasicDisposeOverrideResultAt(25, 26, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeOverride_Diagnostic_DoubleDisposeOverride() { VerifyBasic(@" Imports System Public Class A Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class Public Class B Inherits A Public Overrides Sub Dispose() End Sub End Class [|Public Class C Inherits B Public Overrides Sub Dispose() Dispose(True) End Sub End Class|] ", GetCA1063BasicDisposeOverrideResultAt(32, 26, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeOverride_Diagnostic_2DisposeImplementationsOverriden() { VerifyBasic(@" Imports System Public Class A Implements IDisposable Public Overridable Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class Public Class B Inherits A Implements IDisposable Public Overridable Sub D() Implements IDisposable.Dispose End Sub End Class [|Public Class C Inherits B Public Overrides Sub Dispose() Dispose(True) End Sub Public Overrides Sub D() Dispose() End Sub End Class|] ", GetCA1063BasicDisposeOverrideResultAt(33, 26, "C", "Dispose"), GetCA1063BasicDisposeOverrideResultAt(37, 26, "C", "D")); } #endregion #region VB FinalizeOverride Unit Tests [Fact] public void Basic_CA1063_FinalizeOverride_Diagnostic_SimpleFinalizeOverride() { VerifyBasic(@" Imports System Public Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class [|Public Class C Inherits B Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class|] ", GetCA1063BasicFinalizeOverrideResultAt(22, 14, "C")); } [Fact] public void Basic_CA1063_FinalizeOverride_Diagnostic_DoubleFinalizeOverride() { VerifyBasic(@" Imports System Public Class A Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class Public Class B Inherits A Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class [|Public Class C Inherits B Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class|] ", GetCA1063BasicFinalizeOverrideResultAt(30, 14, "C")); } [Fact] public void Basic_CA1063_FinalizeOverride_NoDiagnostic_FinalizeNotInBaseType() { VerifyBasic(@" Imports System Public Class B Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class [|Public Class C Inherits B Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class|] "); } #endregion #region VB ProvideDisposeBool Unit Tests [Fact] public void Basic_CA1063_ProvideDisposeBool_Diagnostic_MissingDisposeBool() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class ", GetCA1063BasicProvideDisposeBoolResultAt(4, 14, "C"), GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_ProvideDisposeBool_Diagnostic_SealedClassAndMissingDisposeBool() { VerifyBasic(@" Imports System Public NotInheritable Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class "); } #endregion #region VB DisposeBoolSignature Unit Tests [Fact] public void Basic_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsPublic() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Public Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeBoolSignatureResultAt(17, 28, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsProtectedInternal() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Friend Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeBoolSignatureResultAt(17, 38, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsNotVirtual() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeBoolSignatureResultAt(17, 19, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeBoolSignature_Diagnostic_DisposeBoolIsSealedOverriden() { VerifyBasic(@" Imports System Public MustInherit Class B Protected MustOverride Sub Dispose(disposing As Boolean) End Class Public Class C Inherits B Implements IDisposable Public Overloads Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected NotOverridable Overrides Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeBoolSignatureResultAt(22, 44, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsOverriden() { VerifyBasic(@" Imports System Public MustInherit Class B Protected MustOverride Sub Dispose(disposing As Boolean) End Class Public Class C Inherits B Implements IDisposable Public Overloads Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overrides Sub Dispose(disposing As Boolean) End Sub End Class "); } [Fact] public void Basic_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsAbstract() { VerifyBasic(@" Imports System Public MustInherit Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected MustOverride Sub Dispose(disposing As Boolean) End Class "); } [Fact] public void Basic_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsPublicAndClassIsSealed() { VerifyBasic(@" Imports System Public NotInheritable Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Public Sub Dispose(disposing As Boolean) End Sub End Class "); } [Fact] public void Basic_CA1063_DisposeBoolSignature_NoDiagnostic_DisposeBoolIsPrivateAndClassIsSealed() { VerifyBasic(@" Imports System Public NotInheritable Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Private Sub Dispose(disposing As Boolean) End Sub End Class "); } #endregion #region VB DisposeImplementation Unit Tests [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_MissingCallDisposeBool() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_MissingCallSuppressFinalize() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_EmptyDisposeBody() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_CallDisposeWithFalseArgument() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(False) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_ConditionalStatement() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Private disposed As Boolean Public Sub Dispose() Implements IDisposable.Dispose If Not disposed Then Dispose(True) GC.SuppressFinalize(Me) End If End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(9, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_Diagnostic_CallDisposeBoolTwice() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(7, 16, "C", "Dispose")); } [Fact] public void Basic_CA1063_DisposeImplementation_NoDiagnostic_EmptyDisposeBodyInSealedClass() { VerifyBasic(@" Imports System Public NotInheritable Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class "); } #endregion #region VB FinalizeImplementation Unit Tests [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void Basic_CA1063_FinalizeImplementation_Diagnostic_MissingCallDisposeBool() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(15, 20, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void Basic_CA1063_FinalizeImplementation_Diagnostic_CallDisposeWithTrueArgument() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(True) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(15, 20, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void Basic_CA1063_FinalizeImplementation_Diagnostic_ConditionalStatement() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Private disposed As Boolean Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() If Not disposed Then Dispose(False) End If MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(17, 20, "C", "Finalize")); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")] public void Basic_CA1063_FinalizeImplementation_Diagnostic_CallDisposeBoolTwice() { VerifyBasic(@" Imports System Public Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose(False) Dispose(False) MyBase.Finalize() End Sub Protected Overridable Sub Dispose(disposing As Boolean) End Sub End Class ", GetCA1063BasicDisposeImplementationResultAt(15, 20, "C", "Finalize")); } #endregion #region Helpers private static DiagnosticResult GetCA1063CSharpIDisposableReimplementationResultAt(int line, int column, string typeName, string baseTypeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageIDisposableReimplementation, typeName, baseTypeName); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicIDisposableReimplementationResultAt(int line, int column, string typeName, string baseTypeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageIDisposableReimplementation, typeName, baseTypeName); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpDisposeSignatureResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeSignature, typeName + "." + disposeMethod); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicDisposeSignatureResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeSignature, typeName + "." + disposeMethod); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpRenameDisposeResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageRenameDispose, typeName + "." + disposeMethod); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicRenameDisposeResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageRenameDispose, typeName + "." + disposeMethod); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpDisposeOverrideResultAt(int line, int column, string typeName, string method) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeOverride, typeName + "." + method); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicDisposeOverrideResultAt(int line, int column, string typeName, string method) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeOverride, typeName + "." + method); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpFinalizeOverrideResultAt(int line, int column, string typeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeOverride, typeName); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicFinalizeOverrideResultAt(int line, int column, string typeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeOverride, typeName); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpProvideDisposeBoolResultAt(int line, int column, string typeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageProvideDisposeBool, typeName); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicProvideDisposeBoolResultAt(int line, int column, string typeName) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageProvideDisposeBool, typeName); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpDisposeBoolSignatureResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeBoolSignature, typeName + "." + disposeMethod); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicDisposeBoolSignatureResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeBoolSignature, typeName + "." + disposeMethod); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063CSharpDisposeImplementationResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeImplementation, typeName + "." + disposeMethod); return GetCSharpResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1063BasicDisposeImplementationResultAt(int line, int column, string typeName, string disposeMethod) { string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeImplementation, typeName + "." + disposeMethod); return GetBasicResultAt(line, column, ImplementIDisposableCorrectlyAnalyzer.RuleId, message); } #endregion } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u16 = System.UInt16; using Pgno = System.UInt32; namespace Community.CsharpSqlite { using sqlite3_int64 = System.Int64; using sqlite3_stmt = Sqlite3.Vdbe; using System.Security.Cryptography; using System.IO; public partial class Sqlite3 { /* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres ** C#-SQLite is an independent reimplementation of the SQLite software library ** ************************************************************************* */ /* ** SQLCipher ** crypto.c developed by Stephen Lombardo (Zetetic LLC) ** sjlombardo at zetetic dot net ** http://zetetic.net ** ** Copyright (c) 2009, ZETETIC LLC ** 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 ZETETIC LLC 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 ZETETIC LLC ''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 ZETETIC LLC 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. ** */ /* BEGIN CRYPTO */ #if SQLITE_HAS_CODEC //#include <assert.h> //#include <openssl/evp.h> //#include <openssl/rand.h> //#include <openssl/hmac.h> //#include "sqliteInt.h" //#include "btreeInt.h" //#include "crypto.h" #if CODEC_DEBUG || TRACE //#define CODEC_TRACE(X) {printf X;fflush(stdout);} static void CODEC_TRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); } #else //#define CODEC_TRACE(X) static void CODEC_TRACE( string T, params object[] ap ) { } #endif //void sqlite3FreeCodecArg(void *pCodecArg); public class cipher_ctx {//typedef struct { public string pass; public int pass_sz; public bool derive_key; public byte[] key; public int key_sz; public byte[] iv; public int iv_sz; public ICryptoTransform encryptor; public ICryptoTransform decryptor; public cipher_ctx Copy() { cipher_ctx c = new cipher_ctx(); c.derive_key = derive_key; c.pass = pass; c.pass_sz = pass_sz; if ( key != null ) { c.key = new byte[key.Length]; key.CopyTo( c.key, 0 ); } c.key_sz = key_sz; if ( iv != null ) { c.iv = new byte[iv.Length]; iv.CopyTo( c.iv, 0 ); } c.iv_sz = iv_sz; c.encryptor = encryptor; c.decryptor = decryptor; return c; } public void CopyTo( cipher_ctx ct ) { ct.derive_key = derive_key; ct.pass = pass; ct.pass_sz = pass_sz; if ( key != null ) { ct.key = new byte[key.Length]; key.CopyTo( ct.key, 0 ); } ct.key_sz = key_sz; if ( iv != null ) { ct.iv = new byte[iv.Length]; iv.CopyTo( ct.iv, 0 ); } ct.iv_sz = iv_sz; ct.encryptor = encryptor; ct.decryptor = decryptor; } } public class codec_ctx {//typedef struct { public int mode_rekey; public byte[] buffer; public Btree pBt; public cipher_ctx read_ctx; public cipher_ctx write_ctx; public codec_ctx Copy() { codec_ctx c = new codec_ctx(); c.mode_rekey = mode_rekey; c.buffer = sqlite3MemMalloc( buffer.Length ); c.pBt = pBt; if ( read_ctx != null ) c.read_ctx = read_ctx.Copy(); if ( write_ctx != null ) c.write_ctx = write_ctx.Copy(); return c; } } const int FILE_HEADER_SZ = 16; //#define FILE_HEADER_SZ 16 const string CIPHER = "aes-256-cbc"; //#define CIPHER "aes-256-cbc" const int CIPHER_DECRYPT = 0; //#define CIPHER_DECRYPT 0 const int CIPHER_ENCRYPT = 1; //#define CIPHER_ENCRYPT 1 #if NET_2_0 static RijndaelManaged Aes = new RijndaelManaged(); #else static AesManaged Aes = new AesManaged(); #endif /* BEGIN CRYPTO */ static void sqlite3pager_get_codec( Pager pPager, ref codec_ctx ctx ) { ctx = pPager.pCodec; } static int sqlite3pager_is_mj_pgno( Pager pPager, Pgno pgno ) { return ( PAGER_MJ_PGNO( pPager ) == pgno ) ? 1 : 0; } static sqlite3_file sqlite3Pager_get_fd( Pager pPager ) { return ( isOpen( pPager.fd ) ) ? pPager.fd : null; } static void sqlite3pager_sqlite3PagerSetCodec( Pager pPager, dxCodec xCodec, dxCodecSizeChng xCodecSizeChng, dxCodecFree xCodecFree, codec_ctx pCodec ) { sqlite3PagerSetCodec( pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec ); } /* END CRYPTO */ //static void activate_openssl() { // if(EVP_get_cipherbyname(CIPHER) == null) { // OpenSSL_add_all_algorithms(); // } //} /** * Free and wipe memory * If ptr is not null memory will be freed. * If sz is greater than zero, the memory will be overwritten with zero before it is freed */ static void codec_free( ref byte[] ptr, int sz ) { if ( ptr != null ) { if ( sz > 0 ) Array.Clear( ptr, 0, sz );//memset( ptr, 0, sz ); sqlite3_free( ref ptr ); } } /** * Set the raw password / key data for a cipher context * * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory * returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero */ static int cipher_ctx_set_pass( cipher_ctx ctx, string zKey, int nKey ) { ctx.pass = null; // codec_free( ctx.pass, ctx.pass_sz ); ctx.pass_sz = nKey; if ( !String.IsNullOrEmpty( zKey ) && nKey > 0 ) { //ctx.pass = sqlite3Malloc(nKey); //if(ctx.pass == null) return SQLITE_NOMEM; ctx.pass = zKey;//memcpy(ctx.pass, zKey, nKey); return SQLITE_OK; } return SQLITE_ERROR; } /** * Initialize a new cipher_ctx struct. This function will allocate memory * for the cipher context and for the key * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int cipher_ctx_init( ref cipher_ctx iCtx ) { iCtx = new cipher_ctx(); //iCtx = sqlite3Malloc( sizeof( cipher_ctx ) ); //ctx = *iCtx; //if ( ctx == null ) return SQLITE_NOMEM; //memset( ctx, 0, sizeof( cipher_ctx ) ); //ctx.key = sqlite3Malloc( EVP_MAX_KEY_LENGTH ); //if ( ctx.key == null ) return SQLITE_NOMEM; return SQLITE_OK; } /** * free and wipe memory associated with a cipher_ctx */ static void cipher_ctx_free( ref cipher_ctx ictx ) { cipher_ctx ctx = ictx; CODEC_TRACE( "cipher_ctx_free: entered ictx=%d\n", ictx ); ctx.pass = null;//codec_free(ctx.pass, ctx.pass_sz); if ( ctx.key != null ) Array.Clear( ctx.key, 0, ctx.key.Length );//codec_free(ctx.key, ctx.key_sz); if ( ctx.iv != null ) Array.Clear( ctx.iv, 0, ctx.iv.Length ); ictx = new cipher_ctx();// codec_free( ref ctx, sizeof( cipher_ctx ) ); } /** * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a * fully initialized context, you could copy it to write_ctx and all yet data * and pass information across * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int cipher_ctx_copy( cipher_ctx target, cipher_ctx source ) { //byte[] key = target.key; CODEC_TRACE( "cipher_ctx_copy: entered target=%d, source=%d\n", target, source ); //codec_free(target.pass, target.pass_sz); source.CopyTo( target );//memcpy(target, source, sizeof(cipher_ctx); //target.key = key; //restore pointer to previously allocated key data //memcpy(target.key, source.key, EVP_MAX_KEY_LENGTH); //target.pass = sqlite3Malloc(source.pass_sz); //if(target.pass == null) return SQLITE_NOMEM; //memcpy(target.pass, source.pass, source.pass_sz); return SQLITE_OK; } /** * Compare one cipher_ctx to another. * * returns 0 if all the parameters (except the derived key data) are the same * returns 1 otherwise */ static int cipher_ctx_cmp( cipher_ctx c1, cipher_ctx c2 ) { CODEC_TRACE( "cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2 ); if ( c1.key_sz == c2.key_sz && c1.pass_sz == c2.pass_sz && c1.pass == c2.pass ) return 0; return 1; } /** * Free and wipe memory associated with a cipher_ctx, including the allocated * read_ctx and write_ctx. */ static void codec_ctx_free( ref codec_ctx iCtx ) { codec_ctx ctx = iCtx; CODEC_TRACE( "codec_ctx_free: entered iCtx=%d\n", iCtx ); cipher_ctx_free( ref ctx.read_ctx ); cipher_ctx_free( ref ctx.write_ctx ); iCtx = new codec_ctx();//codec_free(ctx, sizeof(codec_ctx); } /** * Derive an encryption key for a cipher contex key based on the raw password. * * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. * * Otherwise, a key data will be derived using PBKDF2 * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if the key could't be derived (for instance if pass is null or pass_sz is 0) */ static int codec_key_derive( codec_ctx ctx, cipher_ctx c_ctx ) { CODEC_TRACE( "codec_key_derive: entered c_ctx.pass=%s, c_ctx.pass_sz=%d ctx.iv=%d ctx.iv_sz=%d c_ctx.kdf_iter=%d c_ctx.key_sz=%d\n", c_ctx.pass, c_ctx.pass_sz, c_ctx.iv, c_ctx.iv_sz, c_ctx.key_sz ); if ( c_ctx.pass != null && c_ctx.pass_sz > 0 ) { // if pass is not null if ( ( c_ctx.pass_sz == ( c_ctx.key_sz * 2 ) + 3 ) && c_ctx.pass.StartsWith( "x'", StringComparison.InvariantCultureIgnoreCase ) ) { int n = c_ctx.pass_sz - 3; /* adjust for leading x' and tailing ' */ string z = c_ctx.pass.Substring( 2 );// + 2; /* adjust lead offset of x' */ CODEC_TRACE( "codec_key_derive: deriving key from hex\n" ); c_ctx.key = sqlite3HexToBlob( null, z, n ); } else { CODEC_TRACE( "codec_key_derive: deriving key using AES256\n" ); Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes( c_ctx.pass, c_ctx.iv, 2010 ); c_ctx.key_sz = 32; c_ctx.key = k1.GetBytes( c_ctx.key_sz ); } #if NET_2_0 Aes.BlockSize = 0x80; Aes.FeedbackSize = 8; Aes.KeySize = 0x100; Aes.Mode = CipherMode.CBC; #endif c_ctx.encryptor = Aes.CreateEncryptor( c_ctx.key, c_ctx.iv ); c_ctx.decryptor = Aes.CreateDecryptor( c_ctx.key, c_ctx.iv ); return SQLITE_OK; }; return SQLITE_ERROR; } /* * ctx - codec context * pgno - page number in database * size - size in bytes of input and output buffers * mode - 1 to encrypt, 0 to decrypt * in - pointer to input bytes * out - pouter to output bytes */ static int codec_cipher( cipher_ctx ctx, Pgno pgno, int mode, int size, byte[] bIn, byte[] bOut ) { int iv; int tmp_csz, csz; CODEC_TRACE( "codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size ); /* just copy raw data from in to out when key size is 0 * i.e. during a rekey of a plaintext database */ if ( ctx.key_sz == 0 ) { Array.Copy( bIn, bOut, bIn.Length );//memcpy(out, in, size); return SQLITE_OK; } MemoryStream dataStream = new MemoryStream(); CryptoStream encryptionStream; if ( mode == CIPHER_ENCRYPT ) { encryptionStream = new CryptoStream( dataStream, ctx.encryptor, CryptoStreamMode.Write ); } else { encryptionStream = new CryptoStream( dataStream, ctx.decryptor, CryptoStreamMode.Write ); } encryptionStream.Write( bIn, 0, size ); encryptionStream.FlushFinalBlock(); dataStream.Position = 0; dataStream.Read( bOut, 0, (int)dataStream.Length ); encryptionStream.Close(); dataStream.Close(); return SQLITE_OK; } /** * * when for_ctx == 0 then it will change for read * when for_ctx == 1 then it will change for write * when for_ctx == 2 then it will change for both */ static int codec_set_cipher_name( sqlite3 db, int nDb, string cipher_name, int for_ctx ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx ); if ( pDb.pBt != null ) { codec_ctx ctx = null; cipher_ctx c_ctx; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; c_ctx.derive_key = true; if ( for_ctx == 2 ) cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); return SQLITE_OK; } return SQLITE_ERROR; } static int codec_set_pass_key( sqlite3 db, int nDb, string zKey, int nKey, int for_ctx ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "codec_set_pass_key: entered db=%d nDb=%d cipher_name=%s nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx ); if ( pDb.pBt != null ) { codec_ctx ctx = null; cipher_ctx c_ctx; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; cipher_ctx_set_pass( c_ctx, zKey, nKey ); c_ctx.derive_key = true; if ( for_ctx == 2 ) cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); return SQLITE_OK; } return SQLITE_ERROR; } /* * sqlite3Codec can be called in multiple modes. * encrypt mode - expected to return a pointer to the * encrypted data without altering pData. * decrypt mode - expected to return a pointer to pData, with * the data decrypted in the input buffer */ static byte[] sqlite3Codec( codec_ctx iCtx, byte[] data, Pgno pgno, int mode ) { codec_ctx ctx = (codec_ctx)iCtx; int pg_sz = sqlite3BtreeGetPageSize( ctx.pBt ); int offset = 0; byte[] pData = data; CODEC_TRACE( "sqlite3Codec: entered pgno=%d, mode=%d, ctx.mode_rekey=%d, pg_sz=%d\n", pgno, mode, ctx.mode_rekey, pg_sz ); /* derive key on first use if necessary */ if ( ctx.read_ctx.derive_key ) { codec_key_derive( ctx, ctx.read_ctx ); ctx.read_ctx.derive_key = false; } if ( ctx.write_ctx.derive_key ) { if ( cipher_ctx_cmp( ctx.write_ctx, ctx.read_ctx ) == 0 ) { cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); // the relevant parameters are the same, just copy read key } else { codec_key_derive( ctx, ctx.write_ctx ); ctx.write_ctx.derive_key = false; } } CODEC_TRACE( "sqlite3Codec: switch mode=%d offset=%d\n", mode, offset ); if ( ctx.buffer.Length != pg_sz ) ctx.buffer = sqlite3MemMalloc( pg_sz ); switch ( mode ) { case SQLITE_DECRYPT: codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz, pData, ctx.buffer ); if ( pgno == 1 ) Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.buffer, 0, FILE_HEADER_SZ );// memcpy( ctx.buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ ); /* copy file header to the first 16 bytes of the page */ Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz ); //memcpy( pData, ctx.buffer, pg_sz ); /* copy buffer data back to pData and return */ return pData; case SQLITE_ENCRYPT_WRITE_CTX: /* encrypt */ if ( pgno == 1 ) Buffer.BlockCopy( ctx.write_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); return ctx.buffer; /* return persistent buffer data, pData remains intact */ case SQLITE_ENCRYPT_READ_CTX: if ( pgno == 1 ) Buffer.BlockCopy( ctx.read_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); return ctx.buffer; /* return persistent buffer data, pData remains intact */ default: return pData; } } static int sqlite3CodecAttach( sqlite3 db, int nDb, string zKey, int nKey ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey ); //activate_openssl(); if ( zKey != null && pDb.pBt != null ) { Aes.KeySize = 256; #if !SQLITE_SILVERLIGHT Aes.Padding = PaddingMode.None; #endif codec_ctx ctx; int rc; Pager pPager = pDb.pBt.pBt.pPager; sqlite3_file fd; ctx = new codec_ctx();//sqlite3Malloc(sizeof(codec_ctx); //if(ctx == null) return SQLITE_NOMEM; //memset(ctx, 0, sizeof(codec_ctx); /* initialize all pointers and values to 0 */ ctx.pBt = pDb.pBt; /* assign pointer to database btree structure */ if ( ( rc = cipher_ctx_init( ref ctx.read_ctx ) ) != SQLITE_OK ) return rc; if ( ( rc = cipher_ctx_init( ref ctx.write_ctx ) ) != SQLITE_OK ) return rc; /* pre-allocate a page buffer of PageSize bytes. This will be used as a persistent buffer for encryption and decryption operations to avoid overhead of multiple memory allocations*/ ctx.buffer = sqlite3MemMalloc( sqlite3BtreeGetPageSize( ctx.pBt ) );//sqlite3Malloc(sqlite3BtreeGetPageSize(ctx.pBt); //if(ctx.buffer == null) return SQLITE_NOMEM; /* allocate space for salt data. Then read the first 16 bytes header as the salt for the key derivation */ ctx.read_ctx.iv_sz = FILE_HEADER_SZ; ctx.read_ctx.iv = new byte[ctx.read_ctx.iv_sz];//sqlite3Malloc( ctx.iv_sz ); Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); sqlite3pager_sqlite3PagerSetCodec( sqlite3BtreePager( pDb.pBt ), sqlite3Codec, null, sqlite3FreeCodecArg, ctx ); codec_set_cipher_name( db, nDb, CIPHER, 0 ); codec_set_pass_key( db, nDb, zKey, nKey, 0 ); cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); //sqlite3BtreeSetPageSize( ctx.pBt, sqlite3BtreeGetPageSize( ctx.pBt ), MAX_IV_LENGTH, 0 ); } return SQLITE_OK; } static void sqlite3FreeCodecArg( ref codec_ctx pCodecArg ) { if ( pCodecArg == null ) return; codec_ctx_free( ref pCodecArg ); // wipe and free allocated memory for the context } static void sqlite3_activate_see( string zPassword ) { /* do nothing, security enhancements are always active */ } static public int sqlite3_key( sqlite3 db, string pKey, int nKey ) { CODEC_TRACE( "sqlite3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey ); /* attach key if db and pKey are not null and nKey is > 0 */ if ( db != null && pKey != null ) { sqlite3CodecAttach( db, 0, pKey, nKey ); // operate only on the main db // // If we are reopening an existing database, redo the header information setup // BtShared pBt = db.aDb[0].pBt.pBt; byte[] zDbHeader = sqlite3MemMalloc( (int)pBt.pageSize );// pBt.pPager.pCodec.buffer; sqlite3PagerReadFileheader( pBt.pPager, zDbHeader.Length, zDbHeader ); if ( sqlite3Get4byte( zDbHeader ) > 0 ) // Existing Database, need to reset some values { CODEC2( pBt.pPager, zDbHeader, 2, SQLITE_DECRYPT, ref zDbHeader ); byte nReserve = zDbHeader[20]; pBt.pageSize = (uint)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 16 ) ); if ( pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE || ( ( pBt.pageSize - 1 ) & pBt.pageSize ) != 0 ) pBt.pageSize = 0; pBt.pageSizeFixed = true; #if !SQLITE_OMIT_AUTOVACUUM pBt.autoVacuum = sqlite3Get4byte( zDbHeader, 36 + 4 * 4 ) != 0; pBt.incrVacuum = sqlite3Get4byte( zDbHeader, 36 + 7 * 4 ) != 0; #endif sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve ); pBt.usableSize = (u16)( pBt.pageSize - nReserve ); } return SQLITE_OK; } return SQLITE_ERROR; } /* sqlite3_rekey ** Given a database, this will reencrypt the database using a new key. ** There are two possible modes of operation. The first is rekeying ** an existing database that was not previously encrypted. The second ** is to change the key on an existing database. ** ** The proposed logic for this function follows: ** 1. Determine if there is already a key present ** 2. If there is NOT already a key present, create one and attach a codec (key would be null) ** 3. Initialize a ctx.rekey parameter of the codec ** ** Note: this will require modifications to the sqlite3Codec to support rekey ** */ static int sqlite3_rekey( sqlite3 db, string pKey, int nKey ) { CODEC_TRACE( "sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey ); //activate_openssl(); if ( db != null && pKey != null ) { Db pDb = db.aDb[0]; CODEC_TRACE( "sqlite3_rekey: database pDb=%d\n", pDb ); if ( pDb.pBt != null ) { codec_ctx ctx = null; int rc; Pgno page_count = 0; Pgno pgno; PgHdr page = null; Pager pPager = pDb.pBt.pBt.pPager; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); if ( ctx == null ) { CODEC_TRACE( "sqlite3_rekey: no codec attached to db, attaching now\n" ); /* there was no codec attached to this database,so attach one now with a null password */ sqlite3CodecAttach( db, 0, pKey, nKey ); sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); /* prepare this setup as if it had already been initialized */ Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); ctx.read_ctx.key_sz = ctx.read_ctx.iv_sz = ctx.read_ctx.pass_sz = 0; } //if ( ctx.read_ctx.iv_sz != ctx.write_ctx.iv_sz ) //{ // string error = ""; // CODEC_TRACE( "sqlite3_rekey: updating page size for iv_sz change from %d to %d\n", ctx.read_ctx.iv_sz, ctx.write_ctx.iv_sz ); // db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); // pDb.pBt.pBt.pageSizeFixed = false; /* required for sqlite3BtreeSetPageSize to modify pagesize setting */ // sqlite3BtreeSetPageSize( pDb.pBt, db.nextPagesize, MAX_IV_LENGTH, 0 ); // sqlite3RunVacuum( ref error, db ); //} codec_set_pass_key( db, 0, pKey, nKey, 1 ); ctx.mode_rekey = 1; /* do stuff here to rewrite the database ** 1. Create a transaction on the database ** 2. Iterate through each page, reading it and then writing it. ** 3. If that goes ok then commit and put ctx.rekey into ctx.key ** note: don't deallocate rekey since it may be used in a subsequent iteration */ rc = sqlite3BtreeBeginTrans( pDb.pBt, 1 ); /* begin write transaction */ sqlite3PagerPagecount( pPager, ref page_count ); for ( pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++ ) { /* pgno's start at 1 see pager.c:pagerAcquire */ if ( 0 == sqlite3pager_is_mj_pgno( pPager, pgno ) ) { /* skip this page (see pager.c:pagerAcquire for reasoning) */ rc = sqlite3PagerGet( pPager, pgno, ref page ); if ( rc == SQLITE_OK ) { /* write page see pager_incr_changecounter for example */ rc = sqlite3PagerWrite( page ); //printf("sqlite3PagerWrite(%d)\n", pgno); if ( rc == SQLITE_OK ) { sqlite3PagerUnref( page ); } } } } /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */ if ( rc == SQLITE_OK ) { CODEC_TRACE( "sqlite3_rekey: committing\n" ); db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); rc = sqlite3BtreeCommit( pDb.pBt ); if ( ctx != null ) cipher_ctx_copy( ctx.read_ctx, ctx.write_ctx ); } else { CODEC_TRACE( "sqlite3_rekey: rollback\n" ); sqlite3BtreeRollback( pDb.pBt ); } ctx.mode_rekey = 0; } return SQLITE_OK; } return SQLITE_ERROR; } static void sqlite3CodecGetKey( sqlite3 db, int nDb, out string zKey, out int nKey ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "sqlite3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb ); if ( pDb.pBt != null ) { codec_ctx ctx = null; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); if ( ctx != null ) { /* if the codec has an attached codec_context user the raw key data */ zKey = ctx.read_ctx.pass; nKey = ctx.read_ctx.pass_sz; return; } } zKey = null; nKey = 0; } /* END CRYPTO */ #endif const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */ const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */ const int SQLITE_DECRYPT = 3; /* Decode page */ } }
/* skybox.cs Skybox Script * author: SoulofDeity * * Features: * - animation via rotation on y axis, speed adjustable * - skybox tinting (requires skybox shader) * - smooth fading color transitioning over a specified * period of time * - multiple skyboxes * - smooth fading skybox transitioning over a specified * period of time (works in conjunction with color * fading as well) * * Technical Details: * - uses user layer 8 for the skybox layer, which is * rendered at a depth of -1 * - gSkybox is the global declaration of the skybox * transform * - tSkybox is the global declaration of the target * skybox transform used when transitioning * - skyboxColorTrans tells whether or not the skybox * is transitioning from one color to another. you * cannot transition to another color while this is * happening. * - skyboxTexTrans tells whether or not the skybox * is transitioning from one set of textures to * another. you cannot transition to another set of * textures while this is happening. * - skybox texture arrays are stored in the order: * front, back, left, right, top, bottom ***************************************************************/ using UnityEngine; using System.Collections; public class skybox : MonoBehaviour { enum SkyboxType { DAY = 0, NIGHT = 1 }; static Transform gSkybox; static Transform tSkybox = null; static bool skyboxColorTrans = false; static bool skyboxTexTrans = false; public float rotationSpeed = 5.0f; public Shader shader; public Color hue = new Color(1.0f, 1.0f, 1.0f, 1.0f); public Texture[] daySkybox = new Texture[6]; public Texture[] nightSkybox = new Texture[6]; private Mesh cubeMesh; void Start() { initCubeMesh(); Camera camera = (Camera)transform.GetComponent("Camera"); camera.clearFlags = CameraClearFlags.Depth; camera.cullingMask = ~(1 << 8); camera.depth = 0; Transform skyboxCam = (new GameObject("skyboxCam")).transform; Camera cam = (Camera)skyboxCam.gameObject.AddComponent<Camera>(); cam.enabled = true; cam.clearFlags = CameraClearFlags.SolidColor; cam.cullingMask = 1 << 8; cam.depth = -1; gSkybox = createSkybox("skybox", daySkybox); gSkybox.parent = skyboxCam; } void Update() { gSkybox.Rotate(new Vector3(0, rotationSpeed * Time.deltaTime, 0)); if (tSkybox) tSkybox.rotation = gSkybox.rotation; if (Input.GetKeyDown(KeyCode.Z)) { Transition(SkyboxType.DAY, Color.white, 3.0f); } else if (Input.GetKeyDown(KeyCode.X)) { Transition(SkyboxType.DAY, new Color(0.75f, 0.15f, 0.0f, 1.0f), 3.0f); } else if (Input.GetKeyDown(KeyCode.C)) { Transition(SkyboxType.NIGHT, new Color(0.75f, 0.75f, 1.0f, 1.0f), 3.0f); } } IEnumerator crTransition(Color color, float time) { if (skyboxColorTrans) yield break; float i = 0.0f; MeshRenderer gmr = (MeshRenderer)gSkybox.GetComponent("MeshRenderer"); Color start = gmr.materials[0].color; skyboxColorTrans = true; while (i <= 1.0f) { Color tc = Color.Lerp(start, color, i); gmr.materials[0].color = new Color(tc.r, tc.g, tc.b, gmr.materials[0].color.a); for (int j = 1; j < 6; j++) gmr.materials[j].color = gmr.materials[0].color; i += Time.deltaTime / time; yield return null; } skyboxColorTrans = false; } IEnumerator crTransition(SkyboxType type, float time) { if (skyboxTexTrans) yield break; Texture[] textures; switch (type) { case SkyboxType.NIGHT: { textures = nightSkybox; break; } default: { textures = daySkybox; break; } } tSkybox = createSkybox("skybox", textures); tSkybox.parent = gSkybox.parent; MeshRenderer gmr = (MeshRenderer)gSkybox.GetComponent("MeshRenderer"); MeshRenderer tmr = (MeshRenderer)tSkybox.GetComponent("MeshRenderer"); Color color = new Color( gmr.materials[0].color.r, gmr.materials[0].color.g, gmr.materials[0].color.b, 0.0f); for (int i = 0; i < 6; i++) tmr.materials[i].color = color; skyboxTexTrans = true; float j = 0.0f; while (j <= 1.0f) { gmr.materials[0].color = new Color( gmr.materials[0].color.r, gmr.materials[0].color.g, gmr.materials[0].color.b, 1.0f - j); tmr.materials[0].color = new Color( gmr.materials[0].color.r, gmr.materials[0].color.g, gmr.materials[0].color.b, j); for (int i = 1; i < 6; i++) { gmr.materials[i].color = gmr.materials[0].color; tmr.materials[i].color = tmr.materials[0].color; } j += Time.deltaTime / time; yield return null; } tmr.materials[0].color = new Color( gmr.materials[0].color.r, gmr.materials[0].color.g, gmr.materials[0].color.b, 1.0f); for (int i = 1; i < 6; i++) tmr.materials[i].color = tmr.materials[0].color; GameObject.Destroy(gSkybox.gameObject); gSkybox = tSkybox; tSkybox = null; skyboxTexTrans = false; } void Transition(Color color, float time) { StartCoroutine(crTransition(color, time)); } void Transition(SkyboxType type, float time) { StartCoroutine(crTransition(type, time)); } void Transition(SkyboxType type, Color color, float time) { StartCoroutine(crTransition(color, time)); StartCoroutine(crTransition(type, time)); } Transform createSkybox(string name, Texture[] textures) { Transform sb = (new GameObject(name)).transform; sb.gameObject.layer = 8; MeshFilter mf = (MeshFilter)sb.gameObject.AddComponent<MeshFilter>(); mf.mesh = cubeMesh; MeshRenderer mr = (MeshRenderer)sb.gameObject.AddComponent<MeshRenderer>(); mr.enabled = true; mr.castShadows = false; mr.receiveShadows = false; mr.materials = new Material[6]; for (int i = 0; i < 6; i++) { mr.materials[i] = new Material(shader); mr.materials[i].shader = shader; mr.materials[i].color = hue; mr.materials[i].mainTexture = textures[i]; } return sb; } void initCubeMesh() { cubeMesh = new Mesh(); cubeMesh.vertices = new Vector3[] { new Vector3(-1,-1, 1), // front new Vector3(-1, 1, 1), new Vector3( 1, 1, 1), new Vector3( 1,-1, 1), new Vector3(-1,-1,-1), // back new Vector3(-1, 1,-1), new Vector3( 1, 1,-1), new Vector3( 1,-1,-1), new Vector3(-1,-1,-1), // left new Vector3(-1, 1,-1), new Vector3(-1, 1, 1), new Vector3(-1,-1, 1), new Vector3( 1,-1,-1), // right new Vector3( 1, 1,-1), new Vector3( 1, 1, 1), new Vector3( 1,-1, 1), new Vector3(-1, 1,-1), // top new Vector3(-1, 1, 1), new Vector3( 1, 1, 1), new Vector3( 1, 1,-1), new Vector3(-1,-1,-1), // bottom new Vector3(-1,-1, 1), new Vector3( 1,-1, 1), new Vector3( 1,-1,-1) }; cubeMesh.uv = new Vector2[] { new Vector2(0, 0), // front new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(1, 0), // back new Vector2(1, 1), new Vector2(0, 1), new Vector2(0, 0), new Vector2(0, 0), // left new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(1, 0), // right new Vector2(1, 1), new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0), // top new Vector2(1, 1), new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 1), // bottom new Vector2(1, 0), new Vector2(0, 0), new Vector2(0, 1) }; cubeMesh.subMeshCount = 6; cubeMesh.SetTriangles(new int[] { 0, 1, 2, 2, 3, 0}, 0); // front cubeMesh.SetTriangles(new int[] { 6, 5, 4, 4, 7, 6}, 1); // back cubeMesh.SetTriangles(new int[] { 8, 9,10,10,11, 8}, 2); // left cubeMesh.SetTriangles(new int[] {14,13,12,12,15,14}, 3); // right cubeMesh.SetTriangles(new int[] {18,17,16,16,19,18}, 4); // top cubeMesh.SetTriangles(new int[] {20,21,22,22,23,20}, 5); // bottom cubeMesh.RecalculateNormals(); cubeMesh.Optimize(); } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Region.Framework.Interfaces { /// <summary> /// Interface to an entity's (SceneObjectPart's) inventory /// </summary> /// /// This is not a finished 1.0 candidate interface public interface IEntityInventory { /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> void ForceInventoryPersistence(); /// <summary> /// Marks the inventory as saved /// </summary> void MarkInventoryClean(); /// <summary> /// Reset UUIDs for all the items in the prim's inventory. /// </summary> /// /// This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// /// <param name="linkNum">Link number for the part</param> void ResetInventoryIDs(); /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> void ChangeInventoryOwner(UUID ownerId); /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> void ChangeInventoryGroup(UUID groupID); /// <summary> /// Start all the scripts contained in this entity's inventory /// </summary> void CreateScriptInstances(int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener); /// <summary> /// Stop all the scripts in this entity. /// </summary> void RemoveScriptInstances(); /// <summary> /// Resets all the scripts and item attributes in this prim. /// </summary> void ResetItems(bool isNewInstance, bool isScriptReset, UUID itemId); /// <summary> /// Start a script which is in this entity's inventory. /// </summary> /// <param name="item"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> void CreateScriptInstance( TaskInventoryItem item, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener); /// <summary> /// Start a script which is in this entity's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> void CreateScriptInstance(UUID itemId, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener); /// <summary> /// Start or restart a script which is in this entity's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="engine"></param> /// <param name="stateSource"></param> void CreateScriptInstance(UUID itemId, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener, bool isReload); /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> void RemoveScriptInstance(UUID itemId); /// <summary> /// Add an item to this entity's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> void AddInventoryItem(TaskInventoryItem item, bool allowedDrop, bool fireEvents); /// <summary> /// Add an item to this entity's inventory. If an item with the same name already exists, it is replaced. /// If replaceArgs is null, it's a remove, otherwise it's a replace (remove plus add). /// </summary> void AddReplaceInventoryItem(TaskInventoryItem item, bool allowedDrop, bool fireEvents, ReplaceItemArgs replaceArgs); /// <summary> /// Scans the items to see how many have scripted controls. /// </summary> /// <returns>The total number of scripts holding controls.</returns> int GetScriptedControlsCount(); /// <summary> /// Restore a whole collection of items to the entity's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> void RestoreInventoryItems(ICollection<TaskInventoryItem> items); void RestoreSingleInventoryItem(TaskInventoryItem item); /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> TaskInventoryItem GetInventoryItem(UUID itemId); /// <summary> /// Update an existing inventory item with a new asset (ID). /// </summary> /// <param name="ParentPartID">The UUID of the prim containing the task inventory item.</param> /// <param name="ItemID">The item to update. An item with the same id must already exist /// in the inventory of the prim specified by ParentPartID.</param> /// <param name="AssetID">The ID of the new asset to replace in the item above.</param> /// <returns>false if the item did not exist or a null ID was passed, true if the update occurred successfully</returns> bool UpdateTaskInventoryItemAsset(UUID ParentID, UUID ItemID, UUID AssetID); /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in the inventory of the prim specified by item.ParentPartID.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> bool UpdateTaskInventoryItemFromItem(TaskInventoryItem item); /// <summary> /// Remove an item from this entity's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> int RemoveInventoryItem(UUID itemID); /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> void RequestInventoryFile(IClientAPI client, IXfer xferManager); /// <summary> /// Returns the list of deleted item UUIDs for this inventory and then clears the list /// of deleted items /// </summary> /// <returns>The list of deleted items</returns> KeyValuePair<UUID, IEnumerable<UUID>> GetDeletedItemList(); /// <summary> /// Clears the list of items that were removed since the last persistence /// </summary> void ClearDeletedItemList(); /// <summary> /// Returns the inventory for this entity <PartId, items> /// </summary> /// <returns></returns> KeyValuePair<UUID, IEnumerable<TaskInventoryItem>> CollectInventoryForBackup(); /// <summary> /// Returns true if the inventory for this object needs persistence /// </summary> /// <returns></returns> bool InventoryNeedsBackup(); uint MaskEffectivePermissions(); uint MaskEffectiveNextPermissions(); // same as above but NextOwner void ApplyNextOwnerPermissions(); // called on rezzing for late last-minute fixes // returns true if the owner changed bool Rationalize(UUID itemOwner); void ApplyGodPermissions(uint perms); /// <summary> /// Returns true if this inventory contains any scripts /// </summary></returns> bool ContainsScripts(); /// <summary> /// Get the uuids of all items in this inventory /// </summary> /// <returns></returns> List<UUID> GetInventoryList(); /// <summary> /// Get the xml representing the saved states of scripts in this inventory. /// </summary> /// <returns> /// A <see cref="Dictionary`2"/> /// </returns> Dictionary<UUID, string> GetScriptStates(StopScriptReason stopScriptReason); /// <summary> /// Get the engine defined binary script state data /// </summary> /// <returns> /// A <see cref="Dictionary`2"/> /// </returns> Dictionary<UUID, byte[]> GetBinaryScriptStates(StopScriptReason stopScriptReason); /// <summary> /// Get the engine defined binary script state data and compiled script bytecode /// data for each script asset from this entity /// </summary> Tuple<Dictionary<UUID, byte[]>, Dictionary<UUID, byte[]>> GetBinaryScriptStatesAndCompiledScripts(StopScriptReason stopScriptReason); /// <summary> /// Returns all scripts in the collection /// </summary> /// <returns></returns> IList<TaskInventoryItem> GetScripts(); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Threading; public class Maze : MonoBehaviour { public enum SeedMode { TIME, PRESET } public enum StartMode { RANDOM, PRESET } public enum Mode { PERFECT, CREATELOOPS } public class DoesntWorkItsFuckedException : Exception {} private const int SOLUTION_MAX_ITERATIONS = 1000; public int width = 5; public int height = 5; public int seed = 0; public SeedMode seedMode = SeedMode.TIME; public StartMode startMode; public Point genStart = new Point(1, 1); public Mode generationMode = Mode.PERFECT; public Cell[,] Grid { get { return grid; } } public List<Cell> DeadEnds { get { return deadends; } } public List<Cell> OpenCells { get { return opencells; } } public bool autoPlay = false; private Cell[,] grid; private List<Cell> deadends; private List<Cell> opencells; private Mesh mesh; private System.Random generator; public void Start() { // Seed random number generator if (seedMode == SeedMode.TIME) generator = new System.Random(); else generator = new System.Random(seed); // Pass over reference to rng so it uses the same one Extensions.generator = generator; } public void Regenerate() { Regenerate(generationMode); } public void Regenerate(Mode mode) { // Set start point if (startMode == StartMode.RANDOM) { genStart.x = generator.Next(0, (width)/2 - 1) * 2 + 1; genStart.y = generator.Next(0, (height)/2 - 1) * 2 + 1; } // Stuff grid = new Cell[width, height]; deadends = new List<Cell>(); opencells = new List<Cell>(); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { grid[x, y] = new Cell(x, y); } } // Generate maze GenerateDepthFirst(); if (mode == Mode.CREATELOOPS) { foreach (Cell cell in deadends) { // Find neighbours List<Cell> neighbours = NeighboursPastWalls(this, cell.position); neighbours.Shuffle(); // Go through neighbours at random // until we find an open one foreach (Cell neighbour in neighbours) { if (neighbour.visited) { // Carve a path to first open cell Point wallPos = new Point((cell.position.x + neighbour.position.x) / 2, (cell.position.y + neighbour.position.y) / 2); grid[wallPos.x, wallPos.y].visited = true; break; } } } } // Add cells to open list foreach (Cell cell in Grid) { if (cell.visited) { OpenCells.Add(cell); } } } public void GenerateDepthFirst() { // Start generation Maze.GenerateDepthFirstWork(this); } public static void GenerateDepthFirstWork(Maze maze) { // Set the start cell maze.grid[maze.genStart.x, maze.genStart.y].end = true; maze.deadends.Add(maze.grid[maze.genStart.x, maze.genStart.y]); // Start generation Maze.GenerateDepthFirstRecursive(maze, maze.grid[maze.genStart.x, maze.genStart.y]); } static void GenerateDepthFirstRecursive(Maze maze, Cell cell) { // Mark as visited cell.visited = true; // Set dead end to true until we move to a neighbour cell.deadend = true; maze.deadends.Add(cell); // Get list of neighbours List<Cell> neighbours = NeighboursPastWalls(maze, cell.position); // Randomised their order neighbours.Shuffle(); // Iterate through them foreach (Cell neighbour in neighbours) { // If we haven't already visited this cell if (!neighbour.visited) { // This can't possibly be an end cell.deadend = false; neighbour.next = cell; maze.deadends.Remove(cell); // Break down wall in between int wallX = cell.position.x + (neighbour.position.x - cell.position.x) / 2; int wallY = cell.position.y + (neighbour.position.y - cell.position.y) / 2; maze.grid[wallX, wallY].visited = true; // Recurse on this cell GenerateDepthFirstRecursive(maze, neighbour); } } } public static List<Cell> Neighbours(Maze maze, Point point) { List<Cell> neighbours = new List<Cell>(); if (point.y > 1) { neighbours.Add(maze.Grid[point.x, point.y-1]); } if (point.y < maze.height-2) { neighbours.Add(maze.Grid[point.x, point.y+1]); } if (point.x > 1) { neighbours.Add(maze.Grid[point.x-1, point.y]); } if (point.x < maze.width-2) { neighbours.Add(maze.Grid[point.x+1, point.y]); } return neighbours; } public static List<Cell> NeighboursPastWalls(Maze maze, Point point) { List<Cell> neighbours = new List<Cell>(); if (point.y > 2) { neighbours.Add(maze.Grid[point.x, point.y-2]); } if (point.y < maze.height-3) { neighbours.Add(maze.Grid[point.x, point.y+2]); } if (point.x > 2) { neighbours.Add(maze.Grid[point.x-2, point.y]); } if (point.x < maze.width-3) { neighbours.Add(maze.Grid[point.x+2, point.y]); } return neighbours; } }
// 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.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Windows.Input; using TestUtilities; namespace TestUtilities.UI { /// <summary> /// Exposes a simple interface to common mouse operations, allowing the user to simulate mouse input. /// </summary> /// <example>The following code moves to screen coordinate 100,100 and left clicks. /// <code> /** Mouse.MoveTo(new Point(100, 100)); Mouse.Click(MouseButton.Left); */ /// </code> /// </example> public static class Mouse { /// <summary> /// Clicks a mouse button. /// </summary> /// <param name="mouseButton">The mouse button to click.</param> public static void Click(MouseButton mouseButton = MouseButton.Left) { Down(mouseButton); Up(mouseButton); } /// <summary> /// Double-clicks a mouse button. /// </summary> /// <param name="mouseButton">The mouse button to click.</param> public static void DoubleClick(MouseButton mouseButton) { Down(mouseButton, delay: false); Up(mouseButton, delay: false); Down(mouseButton, delay: false); Up(mouseButton); } /// <summary> /// Performs a mouse-down operation for a specified mouse button. /// </summary> /// <param name="mouseButton">The mouse button to use.</param> public static void Down(MouseButton mouseButton, bool delay = true) { switch (mouseButton) { case MouseButton.Left: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.LeftDown, delay); break; case MouseButton.Right: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.RightDown, delay); break; case MouseButton.Middle: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.MiddleDown, delay); break; case MouseButton.XButton1: SendMouseInput(0, 0, NativeMethods.XButton1, NativeMethods.SendMouseInputFlags.XDown, delay); break; case MouseButton.XButton2: SendMouseInput(0, 0, NativeMethods.XButton2, NativeMethods.SendMouseInputFlags.XDown, delay); break; default: throw new InvalidOperationException("Unsupported MouseButton input."); } } public static void MoveTo(System.Windows.Point point) { SendMouseInput((int)point.X, (int)point.Y, 0, NativeMethods.SendMouseInputFlags.Move | NativeMethods.SendMouseInputFlags.Absolute); } /// <summary> /// Moves the mouse pointer to the specified screen coordinates. /// </summary> /// <param name="point">The screen coordinates to move to.</param> public static void MoveTo(System.Drawing.Point point) { SendMouseInput(point.X, point.Y, 0, NativeMethods.SendMouseInputFlags.Move | NativeMethods.SendMouseInputFlags.Absolute); } /// <summary> /// Resets the system mouse to a clean state. /// </summary> public static void Reset() { MoveTo(new Point(0, 0)); if (System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed) { SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.LeftUp); } if (System.Windows.Input.Mouse.MiddleButton == MouseButtonState.Pressed) { SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.MiddleUp); } if (System.Windows.Input.Mouse.RightButton == MouseButtonState.Pressed) { SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.RightUp); } if (System.Windows.Input.Mouse.XButton1 == MouseButtonState.Pressed) { SendMouseInput(0, 0, NativeMethods.XButton1, NativeMethods.SendMouseInputFlags.XUp); } if (System.Windows.Input.Mouse.XButton2 == MouseButtonState.Pressed) { SendMouseInput(0, 0, NativeMethods.XButton2, NativeMethods.SendMouseInputFlags.XUp); } } /// <summary> /// Simulates scrolling of the mouse wheel up or down. /// </summary> /// <param name="lines">The number of lines to scroll. Use positive numbers to scroll up and negative numbers to scroll down.</param> public static void Scroll(double lines) { int amount = (int)(NativeMethods.WheelDelta * lines); SendMouseInput(0, 0, amount, NativeMethods.SendMouseInputFlags.Wheel); } /// <summary> /// Performs a mouse-up operation for a specified mouse button. /// </summary> /// <param name="mouseButton">The mouse button to use.</param> public static void Up(MouseButton mouseButton, bool delay = true) { switch (mouseButton) { case MouseButton.Left: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.LeftUp, delay); break; case MouseButton.Right: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.RightUp, delay); break; case MouseButton.Middle: SendMouseInput(0, 0, 0, NativeMethods.SendMouseInputFlags.MiddleUp, delay); break; case MouseButton.XButton1: SendMouseInput(0, 0, NativeMethods.XButton1, NativeMethods.SendMouseInputFlags.XUp, delay); break; case MouseButton.XButton2: SendMouseInput(0, 0, NativeMethods.XButton2, NativeMethods.SendMouseInputFlags.XUp, delay); break; default: throw new InvalidOperationException("Unsupported MouseButton input."); } } /// <summary> /// Sends mouse input. /// </summary> /// <param name="x">x coordinate</param> /// <param name="y">y coordinate</param> /// <param name="data">scroll wheel amount</param> /// <param name="flags">SendMouseInputFlags flags</param> [PermissionSet(SecurityAction.Assert, Name = "FullTrust")] private static void SendMouseInput(int x, int y, int data, NativeMethods.SendMouseInputFlags flags, bool delay = true) { PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted); permissions.Demand(); int intflags = (int)flags; if ((intflags & (int)NativeMethods.SendMouseInputFlags.Absolute) != 0) { // Absolute position requires normalized coordinates. NormalizeCoordinates(ref x, ref y); intflags |= NativeMethods.MouseeventfVirtualdesk; } NativeMethods.INPUT mi = new NativeMethods.INPUT(); mi.type = NativeMethods.InputMouse; mi.union.mouseInput.dx = x; mi.union.mouseInput.dy = y; mi.union.mouseInput.mouseData = data; mi.union.mouseInput.dwFlags = intflags; mi.union.mouseInput.time = 0; mi.union.mouseInput.dwExtraInfo = new IntPtr(0); if (NativeMethods.SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (delay) { System.Threading.Thread.Sleep(250); } } private static void NormalizeCoordinates(ref int x, ref int y) { int vScreenWidth = NativeMethods.GetSystemMetrics(NativeMethods.SMCxvirtualscreen); int vScreenHeight = NativeMethods.GetSystemMetrics(NativeMethods.SMCyvirtualscreen); int vScreenLeft = NativeMethods.GetSystemMetrics(NativeMethods.SMXvirtualscreen); int vScreenTop = NativeMethods.GetSystemMetrics(NativeMethods.SMYvirtualscreen); // Absolute input requires that input is in 'normalized' coords - with the entire // desktop being (0,0)...(65536,65536). Need to convert input x,y coords to this // first. // // In this normalized world, any pixel on the screen corresponds to a block of values // of normalized coords - eg. on a 1024x768 screen, // y pixel 0 corresponds to range 0 to 85.333, // y pixel 1 corresponds to range 85.333 to 170.666, // y pixel 2 correpsonds to range 170.666 to 256 - and so on. // Doing basic scaling math - (x-top)*65536/Width - gets us the start of the range. // However, because int math is used, this can end up being rounded into the wrong // pixel. For example, if we wanted pixel 1, we'd get 85.333, but that comes out as // 85 as an int, which falls into pixel 0's range - and that's where the pointer goes. // To avoid this, we add on half-a-"screen pixel"'s worth of normalized coords - to // push us into the middle of any given pixel's range - that's the 65536/(Width*2) // part of the formula. So now pixel 1 maps to 85+42 = 127 - which is comfortably // in the middle of that pixel's block. // The key ting here is that unlike points in coordinate geometry, pixels take up // space, so are often better treated like rectangles - and if you want to target // a particular pixel, target its rectangle's midpoint, not its edge. x = ((x - vScreenLeft) * 65536) / vScreenWidth + 65536 / (vScreenWidth * 2); y = ((y - vScreenTop) * 65536) / vScreenHeight + 65536 / (vScreenHeight * 2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using Microsoft.Win32.SafeHandles; using Internal.Cryptography; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS public partial class RSA : AsymmetricAlgorithm { public static RSA Create() { return new RSAImplementation.RSAOpenSsl(); } } internal static partial class RSAImplementation { #endif public sealed partial class RSAOpenSsl : RSA { private const int BitsPerByte = 8; // 65537 (0x10001) in big-endian form private static readonly byte[] s_defaultExponent = { 0x01, 0x00, 0x01 }; private Lazy<SafeRsaHandle> _key; public RSAOpenSsl() : this(2048) { } public RSAOpenSsl(int keySize) { KeySize = keySize; _key = new Lazy<SafeRsaHandle>(GenerateKey); } public override int KeySize { set { if (KeySize == value) { return; } // Set the KeySize before FreeKey so that an invalid value doesn't throw away the key base.KeySize = value; FreeKey(); _key = new Lazy<SafeRsaHandle>(GenerateKey); } } private void ForceSetKeySize(int newKeySize) { // In the event that a key was loaded via ImportParameters or an IntPtr/SafeHandle // it could be outside of the bounds that we currently represent as "legal key sizes". // Since that is our view into the underlying component it can be detached from the // component's understanding. If it said it has opened a key, and this is the size, trust it. KeySizeValue = newKeySize; } public override KeySizes[] LegalKeySizes { get { // OpenSSL seems to accept answers of all sizes. // Choosing a non-multiple of 8 would make some calculations misalign // (like assertions of (output.Length * 8) == KeySize). // Choosing a number too small is insecure. // Choosing a number too large will cause GenerateKey to take much // longer than anyone would be willing to wait. // // So, copying the values from RSACryptoServiceProvider return new[] { new KeySizes(384, 16384, 8) }; } } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPrivateDecrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); // If the padding mode is RSA_NO_PADDING then the size of the decrypted block // will be RSA_size, so let's just return buf. // // If any padding was used, then some amount (determined by the padding algorithm) // will have been reduced, and only returnValue bytes were part of the decrypted // body, so copy the decrypted bytes to an appropriately sized array before // returning it. if (returnValue == buf.Length) { return buf; } byte[] plainBytes = new byte[returnValue]; Buffer.BlockCopy(buf, 0, plainBytes, 0, returnValue); return plainBytes; } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPublicEncrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); return buf; } private static Interop.Crypto.RsaPadding GetInteropPadding(RSAEncryptionPadding padding) { if (padding == RSAEncryptionPadding.Pkcs1) { return Interop.Crypto.RsaPadding.Pkcs1; } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Interop.Crypto.RsaPadding.OaepSHA1; } else { throw PaddingModeNotSupported(); } } public override RSAParameters ExportParameters(bool includePrivateParameters) { // It's entirely possible that this line will cause the key to be generated in the first place. SafeRsaHandle key = _key.Value; CheckInvalidKey(key); RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(key, includePrivateParameters); bool hasPrivateKey = rsaParameters.D != null; if (hasPrivateKey != includePrivateParameters || !HasConsistentPrivateKey(ref rsaParameters)) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } return rsaParameters; } public override void ImportParameters(RSAParameters parameters) { ValidateParameters(ref parameters); SafeRsaHandle key = Interop.Crypto.RsaCreate(); bool imported = false; Interop.Crypto.CheckValidOpenSslHandle(key); try { Interop.Crypto.SetRsaParameters( key, parameters.Modulus, parameters.Modulus != null ? parameters.Modulus.Length : 0, parameters.Exponent, parameters.Exponent != null ? parameters.Exponent.Length : 0, parameters.D, parameters.D != null ? parameters.D.Length : 0, parameters.P, parameters.P != null ? parameters.P.Length : 0, parameters.DP, parameters.DP != null ? parameters.DP.Length : 0, parameters.Q, parameters.Q != null ? parameters.Q.Length : 0, parameters.DQ, parameters.DQ != null ? parameters.DQ.Length : 0, parameters.InverseQ, parameters.InverseQ != null ? parameters.InverseQ.Length : 0); imported = true; } finally { if (!imported) { key.Dispose(); } } FreeKey(); _key = new Lazy<SafeRsaHandle>(() => key); // Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere // with the already loaded key. ForceSetKeySize(BitsPerByte * Interop.Crypto.RsaSize(key)); } protected override void Dispose(bool disposing) { if (disposing) { FreeKey(); } base.Dispose(disposing); } private void FreeKey() { if (_key != null && _key.IsValueCreated) { SafeRsaHandle handle = _key.Value; if (handle != null) { handle.Dispose(); } } } private static void ValidateParameters(ref RSAParameters parameters) { if (parameters.Modulus == null || parameters.Exponent == null) throw new CryptographicException(SR.Argument_InvalidValue); if (!HasConsistentPrivateKey(ref parameters)) throw new CryptographicException(SR.Argument_InvalidValue); } private static bool HasConsistentPrivateKey(ref RSAParameters parameters) { if (parameters.D == null) { if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null) { return false; } } else { if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null) { return false; } } return true; } private static void CheckInvalidKey(SafeRsaHandle key) { if (key == null || key.IsInvalid) { throw new CryptographicException(SR.Cryptography_OpenInvalidHandle); } } private static void CheckReturn(int returnValue) { if (returnValue == -1) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } private static void CheckBoolReturn(int returnValue) { if (returnValue == 1) { return; } throw Interop.Crypto.CreateOpenSslCryptographicException(); } private SafeRsaHandle GenerateKey() { SafeRsaHandle key = Interop.Crypto.RsaCreate(); bool generated = false; Interop.Crypto.CheckValidOpenSslHandle(key); try { using (SafeBignumHandle exponent = Interop.Crypto.CreateBignum(s_defaultExponent)) { // The documentation for RSA_generate_key_ex does not say that it returns only // 0 or 1, so the call marshals it back as a full Int32 and checks for a value // of 1 explicitly. int response = Interop.Crypto.RsaGenerateKeyEx( key, KeySize, exponent); CheckBoolReturn(response); generated = true; } } finally { if (!generated) { key.Dispose(); } } return key; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { return OpenSslAsymmetricAlgorithmCore.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { return OpenSslAsymmetricAlgorithmCore.HashData(data, hashAlgorithm); } public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return SignHash(hash, hashAlgorithm); } private byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithmName) { int algorithmNid = GetAlgorithmNid(hashAlgorithmName); SafeRsaHandle rsa = _key.Value; byte[] signature = new byte[Interop.Crypto.RsaSize(rsa)]; int signatureSize; bool success = Interop.Crypto.RsaSign( algorithmNid, hash, hash.Length, signature, out signatureSize, rsa); if (!success) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } Debug.Assert( signatureSize == signature.Length, "RSA_sign reported an unexpected signature size", "RSA_sign reported signatureSize was {0}, when {1} was expected", signatureSize, signature.Length); return signature; } public override bool VerifyHash( byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException(nameof(hash)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return VerifyHash(hash, signature, hashAlgorithm); } private bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithmName) { int algorithmNid = GetAlgorithmNid(hashAlgorithmName); SafeRsaHandle rsa = _key.Value; return Interop.Crypto.RsaVerify( algorithmNid, hash, hash.Length, signature, signature.Length, rsa); } private static int GetAlgorithmNid(HashAlgorithmName hashAlgorithmName) { // All of the current HashAlgorithmName values correspond to the SN values in OpenSSL 0.9.8. // If there's ever a new one that doesn't, translate it here. string sn = hashAlgorithmName.Name; int nid = Interop.Crypto.ObjSn2Nid(sn); if (nid == Interop.Crypto.NID_undef) { throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name); } return nid; } private static Exception PaddingModeNotSupported() { return new CryptographicException(SR.Cryptography_InvalidPaddingMode); } private static Exception HashAlgorithmNameNullOrEmpty() { return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif }
// 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.Security; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Linq; #if USE_REFEMIT public sealed class ClassDataContract : DataContract #else internal sealed class ClassDataContract : DataContract #endif { public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; private XmlDictionaryString[] _childElementNamespaces; private ClassDataContractCriticalHelper _helper; private bool _isScriptObject; internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } private void InitClassDataContract() { _helper = base.Helper as ClassDataContractCriticalHelper; this.ContractNamespaces = _helper.ContractNamespaces; this.MemberNames = _helper.MemberNames; this.MemberNamespaces = _helper.MemberNamespaces; _isScriptObject = _helper.IsScriptObject; } internal ClassDataContract BaseContract { get { return _helper.BaseContract; } } internal List<DataMember> Members { get { return _helper.Members; } } public XmlDictionaryString[] ChildElementNamespaces { get { if (_childElementNamespaces == null) { lock (this) { if (_childElementNamespaces == null) { if (_helper.ChildElementNamespaces == null) { XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); _helper.ChildElementNamespaces = tempChildElementamespaces; } _childElementNamespaces = _helper.ChildElementNamespaces; } } } return _childElementNamespaces; } set { _childElementNamespaces = value; } } internal MethodInfo OnSerializing { get { return _helper.OnSerializing; } } internal MethodInfo OnSerialized { get { return _helper.OnSerialized; } } internal MethodInfo OnDeserializing { get { return _helper.OnDeserializing; } } internal MethodInfo OnDeserialized { get { return _helper.OnDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { return _helper.ExtensionDataSetMethod; } } public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } } public override bool IsISerializable { get { return _helper.IsISerializable; } set { _helper.IsISerializable = value; } } internal bool IsNonAttributedType { get { return _helper.IsNonAttributedType; } } public bool HasExtensionData { get { return _helper.HasExtensionData; } set { _helper.HasExtensionData = value; } } internal bool IsKeyValuePairAdapter { get { return _helper.IsKeyValuePairAdapter; } } internal Type[] KeyValuePairGenericArguments { get { return _helper.KeyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _helper.KeyValuePairAdapterConstructorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _helper.GetKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { return _helper.GetISerializableConstructor(); } private ConstructorInfo _nonAttributedTypeConstructor; internal ConstructorInfo GetNonAttributedTypeConstructor() { if (_nonAttributedTypeConstructor == null) { // Cache the ConstructorInfo to improve performance. _nonAttributedTypeConstructor = _helper.GetNonAttributedTypeConstructor(); } return _nonAttributedTypeConstructor; } private Func<object> _makeNewInstance; private Func<object> MakeNewInstance { get { if (_makeNewInstance == null) { _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); } return _makeNewInstance; } } internal bool CreateNewInstanceViaDefaultConstructor(out object obj) { ConstructorInfo ci = GetNonAttributedTypeConstructor(); if (ci == null) { obj = null; return false; } if (ci.IsPublic) { // Optimization for calling public default ctor. obj = MakeNewInstance(); } else { obj = ci.Invoke(Array.Empty<object>()); } return true; } private XmlFormatClassWriterDelegate CreateXmlFormatWriterDelegate() { return new XmlFormatWriterGenerator().GenerateClassWriter(this); } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { } } private XmlFormatClassReaderDelegate CreateXmlFormatReaderDelegate() { return new XmlFormatReaderGenerator().GenerateClassReader(this); } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatClassReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { } } internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type); if (cdc == null) { return new ClassDataContract(type, ns, memberNames); } else { ClassDataContract cloned = cdc.Clone(); cloned.UpdateNamespaceAndMembers(type, ns, memberNames); return cloned; } } internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.Format((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) return dictionary.Add(ns); } return null; } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } /// <SecurityNote> /// RequiresReview - callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and /// is therefore marked SRR /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) return false; if (type.IsEnum) return false; if (type.IsGenericParameter) return false; if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) return false; if (type.IsPointer) return false; if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) return false; Type[] interfaceTypes = type.GetInterfaces(); if (!IsArraySegment(type)) { foreach (Type interfaceType in interfaceTypes) { if (CollectionDataContract.IsCollectionInterface(interfaceType)) return false; } } if (type.IsSerializable) return false; if (Globals.TypeOfISerializable.IsAssignableFrom(type)) return false; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) return false; if (type.IsValueType) { return type.IsVisible; } else { return (type.IsVisible && type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null); } } private static readonly Dictionary<string, string[]> s_knownSerializableTypeInfos = new Dictionary<string, string[]> { { "System.Collections.Generic.KeyValuePair`2", Array.Empty<string>() }, { "System.Collections.Generic.Queue`1", new [] { "_syncRoot" } }, { "System.Collections.Generic.Stack`1", new [] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyCollection`1", new [] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyDictionary`2", new [] {"_syncRoot", "_keys","_values" } }, { "System.Tuple`1", Array.Empty<string>() }, { "System.Tuple`2", Array.Empty<string>() }, { "System.Tuple`3", Array.Empty<string>() }, { "System.Tuple`4", Array.Empty<string>() }, { "System.Tuple`5", Array.Empty<string>() }, { "System.Tuple`6", Array.Empty<string>() }, { "System.Tuple`7", Array.Empty<string>() }, { "System.Tuple`8", Array.Empty<string>() }, { "System.Collections.Queue", new [] {"_syncRoot" } }, { "System.Collections.Stack", new [] {"_syncRoot" } }, { "System.Globalization.CultureInfo", Array.Empty<string>() }, { "System.Version", Array.Empty<string>() }, }; private static string GetGeneralTypeName(Type type) { return type.IsGenericType && !type.IsGenericParameter ? type.GetGenericTypeDefinition().FullName : type.FullName; } internal static bool IsKnownSerializableType(Type type) { // Applies to known types that DCS understands how to serialize/deserialize // string typeFullName = GetGeneralTypeName(type); return s_knownSerializableTypeInfos.ContainsKey(typeFullName); } internal static bool IsNonSerializedMember(Type type, string memberName) { string typeFullName = GetGeneralTypeName(type); string[] members; return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members) && members.Contains(memberName); } private XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) return null; XmlDictionaryString[] baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) { childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary); } return childElementNamespaces; } private void EnsureMethodsImported() { _helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } xmlReader.Read(); object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException)) return true; if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor())) { if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType)) { return true; } if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldSetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertySetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) return true; if (MethodRequiresMemberAccess(this.OnSerializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), this.OnSerializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnSerialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnSerialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertyGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[] s_serInfoCtorArgs; private ClassDataContract _baseContract; private List<DataMember> _members; private MethodInfo _onSerializing, _onSerialized; private MethodInfo _onDeserializing, _onDeserialized; private MethodInfo _extensionDataSetMethod; private DataContractDictionary _knownDataContracts; private bool _isISerializable; private bool _isKnownTypeAttributeChecked; private bool _isMethodChecked; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract /// </SecurityNote> private bool _isNonAttributedType; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType /// </SecurityNote> private bool _hasDataContract; private bool _hasExtensionData; private bool _isScriptObject; private XmlDictionaryString[] _childElementNamespaces; private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; internal ClassDataContractCriticalHelper() : base() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { this.StableName = stableName; _members = new List<DataMember>(); XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>(); EnsureMethodsImported(); return; } Type baseType = type.BaseType; _isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type)); SetIsNonAttributedType(type); if (_isISerializable) { if (HasDataContract) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.ISerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (baseType != null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) baseType = null; } SetKeyValuePairAdapterFlags(type); this.IsValueType = type.IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { // dotnet/corefx#19629: a DataContract created at runtime does not work with the base DataContract // pre-generated by SG. It's because the runtime DataContract requires full information of a base DataContract // while a pre-generated DataContract is incomplete. // // At this point in code, we're in the midlle of creating a new DataContract at runtime, so we need to make // sure that we create our own base type DataContract when the base type could potentially have SG generated // DataContract. // // We wanted to enable the fix for the issue described above only when SG generated DataContracts are available. // Currently we don't have a good way of detecting usage of SG (either globally or per data contract). DataContract baseContract = DataContract.GetDataContract(baseType); if (baseContract is CollectionDataContract) { this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract; } else { this.BaseContract = baseContract as ClassDataContract; } if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType)))); } } else { this.BaseContract = null; } _hasExtensionData = (Globals.TypeOfIExtensibleDataObject.IsAssignableFrom(type)); if (_hasExtensionData && !HasDataContract && !IsNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.OnlyDataContractTypesCanHaveExtensionData, DataContract.GetClrTypeFullName(type)))); } if (_isISerializable) { SetDataContractName(stableName); } else { this.StableName = stableName; ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseMemberCount = 0; int baseContractCount = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { baseMemberCount = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount); baseContractCount = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount); } ContractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name); MemberNamespaces[i + baseMemberCount] = Namespace; } } EnsureMethodsImported(); _isScriptObject = this.IsNonAttributedType && Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(1 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = ns; ContractNamespaces = new XmlDictionaryString[] { Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = dictionary.Add(Members[i].Name); MemberNamespaces[i] = Namespace; } EnsureMethodsImported(); } private void EnsureIsReferenceImported(Type type) { DataContractAttribute dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || (!baseIsReference && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.InconsistentIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType), this.BaseContract.IsReference), type); } else { isReference = dataContractAttribute.IsReference; } } else { isReference = this.BaseContract.IsReference; } } else if (hasDataContractAttribute) { if (dataContractAttribute.IsReference) isReference = dataContractAttribute.IsReference; } if (isReference && type.IsValueType) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.ValueTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), true, false), type); return; } this.IsReference = isReference; } private void ImportDataMembers() { Type type = this.UnderlyingType; EnsureIsReferenceImported(type); List<DataMember> tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type); if (!isPodSerializable) { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); } else { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); DataMember memberContract = new DataMember(member); if (member is PropertyInfo) { PropertyInfo property = (PropertyInfo)member; MethodInfo getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; MethodInfo setMethod = property.SetMethod; if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) { ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name)); } } if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } else if (!(member is FieldInfo)) ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } else memberContract.Name = member.Name; memberContract.Name = DataContract.EncodeLocalName(memberContract.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); memberContract.IsRequired = memberAttribute.IsRequired; if (memberAttribute.IsRequired && this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; memberContract.Order = memberAttribute.Order; CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } else if (!isPodSerializable) { FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { MethodInfo getMethod = property.GetGetMethod(); if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo setMethod = property.SetMethod; if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) continue; } else { if (!setMethod.IsPublic || IsMethodOverriding(setMethod)) continue; } } memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } else { FieldInfo field = member as FieldInfo; bool canSerializeMember; // Previously System.SerializableAttribute was not available in NetCore, so we had // a list of known [Serializable] types for type in the framework. Although now SerializableAttribute // is available in NetCore, some framework types still do not have [Serializable] // yet, e.g. ReadOnlyDictionary<TKey, TValue>. So, we still need to maintain the known serializable // type list. if (IsKnownSerializableType(type)) { canSerializeMember = CanSerializeMember(field); } else { canSerializeMember = field != null && !field.IsNotSerialized; } if (canSerializeMember) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.IsRequired = true; } memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } if (tempMembers.Count > 1) tempMembers.Sort(DataMemberComparer.Singleton); SetIfMembersHaveConflict(tempMembers); Interlocked.MemoryBarrier(); _members = tempMembers; } private static bool CanSerializeMember(FieldInfo field) { return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name); } private bool SetIfGetOnlyCollection(DataMember memberContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } private void SetIfMembersHaveConflict(List<DataMember> members) { if (BaseContract == null) return; int baseTypeIndex = 0; List<Member> membersInHierarchy = new List<Member>(); foreach (DataMember member in members) { membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); } ClassDataContract currContract = BaseContract; while (currContract != null) { baseTypeIndex++; foreach (DataMember member in currContract.Members) { membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } IComparer<Member> comparer = DataMemberConflictComparer.Singleton; membersInHierarchy.Sort(comparer); for (int i = 0; i < membersInHierarchy.Count - 1; i++) { int startIndex = i; int endIndex = i; bool hasConflictingType = false; while (endIndex < membersInHierarchy.Count - 1 && string.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0 && string.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0) { membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member; if (!hasConflictingType) { if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType) { hasConflictingType = true; } else { hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType); } } endIndex++; } if (hasConflictingType) { for (int j = startIndex; j <= endIndex; j++) { membersInHierarchy[j].member.HasConflictingNameAndType = true; } } i = endIndex + 1; } } private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out _hasDataContract); } /// <SecurityNote> /// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it /// is dependent on the correct calculation of hasDataContract /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> private void SetIsNonAttributedType(Type type) { _isNonAttributedType = !type.IsSerializable && !_hasDataContract && IsNonAttributedTypeValidForSerialization(type); } private static bool IsMethodOverriding(MethodInfo method) { return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0); } internal void EnsureMethodsImported() { if (!_isMethodChecked && UnderlyingType != null) { lock (this) { if (!_isMethodChecked) { Type type = this.UnderlyingType; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters)) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || !method.IsPublic) _extensionDataSetMethod = XmlFormatGeneratorStatics.ExtensionDataSetExplicitMethodInfo; else _extensionDataSetMethod = method; } if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType)) _onSerializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType)) _onSerialized = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType)) _onDeserializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType)) _onDeserialized = method; } Interlocked.MemoryBarrier(); _isMethodChecked = true; } } } } private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] parameters) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { if (_extensionDataSetMethod != null) ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); return true; } return false; } private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, false)) { if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; } return true; } return false; } internal ClassDataContract BaseContract { get { return _baseContract; } set { _baseContract = value; if (_baseContract != null && IsValueType) ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace)); } } internal List<DataMember> Members { get { return _members; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return _onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return _onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return _onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return _onDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { EnsureMethodsImported(); return _extensionDataSetMethod; } } internal override DataContractDictionary KnownDataContracts { get { if (_knownDataContracts != null) { return _knownDataContracts; } if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal override bool IsISerializable { get { return _isISerializable; } set { _isISerializable = value; } } internal bool HasDataContract { get { return _hasDataContract; } } internal bool HasExtensionData { get { return _hasExtensionData; } set { _hasExtensionData = value; } } internal bool IsNonAttributedType { get { return _isNonAttributedType; } } private void SetKeyValuePairAdapterFlags(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { _isKeyValuePairAdapter = true; _keyValuePairGenericArguments = type.GetGenericArguments(); _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) }); _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers); } } private bool _isKeyValuePairAdapter; private Type[] _keyValuePairGenericArguments; private ConstructorInfo _keyValuePairCtorInfo; private MethodInfo _getKeyValuePairMethodInfo; internal bool IsKeyValuePairAdapter { get { return _isKeyValuePairAdapter; } } internal bool IsScriptObject { get { return _isScriptObject; } } internal Type[] KeyValuePairGenericArguments { get { return _keyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _keyValuePairCtorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _getKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { if (!IsISerializable) return null; ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); if (ctor == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return _childElementNamespaces; } set { _childElementNamespaces = value; } } private static Type[] SerInfoCtorArgs { get { if (s_serInfoCtorArgs == null) s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; return s_serInfoCtorArgs; } } internal struct Member { internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } internal DataMember member; internal string ns; internal int baseTypeIndex; } internal class DataMemberConflictComparer : IComparer<Member> { public int Compare(Member x, Member y) { int nsCompare = string.CompareOrdinal(x.ns, y.ns); if (nsCompare != 0) return nsCompare; int nameCompare = string.CompareOrdinal(x.member.Name, y.member.Name); if (nameCompare != 0) return nameCompare; return x.baseTypeIndex - y.baseTypeIndex; } internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); } internal ClassDataContractCriticalHelper Clone() { ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType); clonedHelper._baseContract = this._baseContract; clonedHelper._childElementNamespaces = this._childElementNamespaces; clonedHelper.ContractNamespaces = this.ContractNamespaces; clonedHelper._hasDataContract = this._hasDataContract; clonedHelper._isMethodChecked = this._isMethodChecked; clonedHelper._isNonAttributedType = this._isNonAttributedType; clonedHelper.IsReference = this.IsReference; clonedHelper.IsValueType = this.IsValueType; clonedHelper.MemberNames = this.MemberNames; clonedHelper.MemberNamespaces = this.MemberNamespaces; clonedHelper._members = this._members; clonedHelper.Name = this.Name; clonedHelper.Namespace = this.Namespace; clonedHelper._onDeserialized = this._onDeserialized; clonedHelper._onDeserializing = this._onDeserializing; clonedHelper._onSerialized = this._onSerialized; clonedHelper._onSerializing = this._onSerializing; clonedHelper.StableName = this.StableName; clonedHelper.TopLevelElementName = this.TopLevelElementName; clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace; clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate; clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate; return clonedHelper; } } internal class DataMemberComparer : IComparer<DataMember> { public int Compare(DataMember x, DataMember y) { int orderCompare = x.Order - y.Order; if (orderCompare != 0) return orderCompare; return string.CompareOrdinal(x.Name, y.Name); } internal static DataMemberComparer Singleton = new DataMemberComparer(); } /// <summary> /// Get object type for Xml/JsonFormmatReaderGenerator /// </summary> internal Type ObjectType { get { Type type = UnderlyingType; if (type.IsValueType && !IsNonAttributedType) { type = Globals.TypeOfValueType; } return type; } } internal ClassDataContract Clone() { ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType); clonedDc._helper = _helper.Clone(); clonedDc.ContractNamespaces = this.ContractNamespaces; clonedDc.ChildElementNamespaces = this.ChildElementNamespaces; clonedDc.MemberNames = this.MemberNames; clonedDc.MemberNamespaces = this.MemberNamespaces; clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate; clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate; return clonedDc; } internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames) { this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value); this.Namespace = ns; XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length); this.Name = dictionary.Add(StableName.Name); this.Namespace = ns; this.ContractNamespaces = new XmlDictionaryString[] { ns }; this.MemberNames = new XmlDictionaryString[memberNames.Length]; this.MemberNamespaces = new XmlDictionaryString[memberNames.Length]; for (int i = 0; i < memberNames.Length; i++) { this.MemberNames[i] = dictionary.Add(memberNames[i]); this.MemberNamespaces[i] = ns; } } internal Type UnadaptedClassType { get { if (IsKeyValuePairAdapter) { return Globals.TypeOfKeyValuePair.MakeGenericType(KeyValuePairGenericArguments); } else { return UnderlyingType; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// AccountOperations operations. /// </summary> internal partial class AccountOperations : Microsoft.Rest.IServiceOperations<BatchServiceClient>, IAccountOperations { /// <summary> /// Initializes a new instance of the AccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AccountOperations(BatchServiceClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the BatchServiceClient /// </summary> public BatchServiceClient Client { get; private set; } /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='accountListNodeAgentSkusOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusWithHttpMessagesAsync(AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions = default(AccountListNodeAgentSkusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } string filter = default(string); if (accountListNodeAgentSkusOptions != null) { filter = accountListNodeAgentSkusOptions.Filter; } int? maxResults = default(int?); if (accountListNodeAgentSkusOptions != null) { maxResults = accountListNodeAgentSkusOptions.MaxResults; } int? timeout = default(int?); if (accountListNodeAgentSkusOptions != null) { timeout = accountListNodeAgentSkusOptions.Timeout; } System.Guid? clientRequestId = default(System.Guid?); if (accountListNodeAgentSkusOptions != null) { clientRequestId = accountListNodeAgentSkusOptions.ClientRequestId; } bool? returnClientRequestId = default(bool?); if (accountListNodeAgentSkusOptions != null) { returnClientRequestId = accountListNodeAgentSkusOptions.ReturnClientRequestId; } System.DateTime? ocpDate = default(System.DateTime?); if (accountListNodeAgentSkusOptions != null) { ocpDate = accountListNodeAgentSkusOptions.OcpDate; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("filter", filter); tracingParameters.Add("maxResults", maxResults); tracingParameters.Add("timeout", timeout); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("returnClientRequestId", returnClientRequestId); tracingParameters.Add("ocpDate", ocpDate); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkus", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "nodeagentskus").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (maxResults != null) { _queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"')))); } if (timeout != null) { _queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (returnClientRequestId != null) { if (_httpRequest.Headers.Contains("return-client-request-id")) { _httpRequest.Headers.Remove("return-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ocpDate != null) { if (_httpRequest.Headers.Contains("ocp-date")) { _httpRequest.Headers.Remove("ocp-date"); } _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='accountListNodeAgentSkusNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusNextWithHttpMessagesAsync(string nextPageLink, AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = default(AccountListNodeAgentSkusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } System.Guid? clientRequestId = default(System.Guid?); if (accountListNodeAgentSkusNextOptions != null) { clientRequestId = accountListNodeAgentSkusNextOptions.ClientRequestId; } bool? returnClientRequestId = default(bool?); if (accountListNodeAgentSkusNextOptions != null) { returnClientRequestId = accountListNodeAgentSkusNextOptions.ReturnClientRequestId; } System.DateTime? ocpDate = default(System.DateTime?); if (accountListNodeAgentSkusNextOptions != null) { ocpDate = accountListNodeAgentSkusNextOptions.OcpDate; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("returnClientRequestId", returnClientRequestId); tracingParameters.Add("ocpDate", ocpDate); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkusNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (returnClientRequestId != null) { if (_httpRequest.Headers.Contains("return-client-request-id")) { _httpRequest.Headers.Remove("return-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ocpDate != null) { if (_httpRequest.Headers.Contains("ocp-date")) { _httpRequest.Headers.Remove("ocp-date"); } _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlSelectionListAdapter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Globalization; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.MobileControls; using System.Collections.Specialized; using System.Diagnostics; using System.Security.Permissions; #if COMPILING_FOR_SHIPPED_SOURCE namespace System.Web.UI.MobileControls.ShippedAdapterSource #else namespace System.Web.UI.MobileControls.Adapters #endif { /* * HtmlSelectionListAdapter provides the html device functionality for SelectionList controls. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class HtmlSelectionListAdapter : HtmlControlAdapter { /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter.Control"]/*' /> protected new SelectionList Control { get { return (SelectionList)base.Control; } } /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter.OnInit"]/*' /> public override void OnInit(EventArgs e) { } /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter.Render"]/*' /> public override void Render(HtmlMobileTextWriter writer) { MobileListItemCollection items = Control.Items; ListSelectType selectType = Control.SelectType; if (items.Count == 0 && selectType != ListSelectType.ListBox && selectType != ListSelectType.MultiSelectListBox) { return; } int selectedIndex = Control.SelectedIndex; String renderName; if(Device.RequiresAttributeColonSubstitution) { renderName = Control.UniqueID.Replace(':', ','); } else { renderName = Control.UniqueID; } switch(selectType) { case ListSelectType.DropDown: case ListSelectType.ListBox: case ListSelectType.MultiSelectListBox: if (items.Count == 0 && !Device.CanRenderEmptySelects) { break; } writer.EnterLayout(Style); writer.WriteBeginTag("select"); if (selectType == ListSelectType.MultiSelectListBox) { writer.Write(" multiple"); } if (selectType == ListSelectType.ListBox || selectType == ListSelectType.MultiSelectListBox) { writer.WriteAttribute("size", Control.Rows.ToString(CultureInfo.InvariantCulture)); } writer.WriteAttribute("name", renderName); writer.Write(">"); for(int itemIndex = 0; itemIndex < items.Count; itemIndex++) { MobileListItem item = items[itemIndex]; writer.WriteBeginTag("option"); WriteItemValueAttribute(writer, itemIndex, item.Value); if (item.Selected && (Control.IsMultiSelect || itemIndex == selectedIndex)) { writer.Write(" selected>"); } else { writer.Write(">"); } writer.WriteEncodedText(item.Text); writer.WriteLine(""); } writer.Write("</select>"); if(Device.HidesRightAlignedMultiselectScrollbars && selectType == ListSelectType.MultiSelectListBox) { // nested if for perf if((Alignment)Style[Style.AlignmentKey, true] == Alignment.Right) { writer.Write("&nbsp;&nbsp;&nbsp;&nbsp;"); } } writer.WriteLine(""); if (!Page.DesignMode) { writer.ExitLayout(Style, Control.BreakAfter); } else { writer.ExitLayout(Style, false); } break; case ListSelectType.Radio: case ListSelectType.CheckBox: String selectTypeString = (selectType == ListSelectType.Radio) ? "radio" : "checkbox"; Alignment alignment = (Alignment)Style[Style.AlignmentKey, true]; if(!Device.Tables || alignment == Alignment.Left || alignment == Alignment.NotSet) { writer.EnterStyle(Style); bool breakAfter = false; for(int itemIndex = 0; itemIndex < items.Count; itemIndex++) { if(breakAfter) { writer.WriteBreak(); } MobileListItem item = items[itemIndex]; writer.WriteBeginTag("input"); writer.WriteAttribute("type", selectTypeString); writer.WriteAttribute("name", renderName); WriteItemValueAttribute(writer, itemIndex, item.Value); if (item.Selected && (Control.IsMultiSelect || itemIndex == selectedIndex) && Device.SupportsUncheck) { writer.Write(" checked>"); } else { writer.Write(">"); } writer.WriteEncodedText(item.Text); breakAfter = true; } writer.ExitStyle(Style, Control.BreakAfter); } else // Device supports tables and alignment is non default. { Wrapping wrapping = (Wrapping) Style[Style.WrappingKey , true]; bool nowrap = (wrapping == Wrapping.NoWrap); writer.EnterLayout(Style); writer.WriteFullBeginTag("table"); writer.BeginStyleContext(); for(int itemIndex = 0; itemIndex < items.Count; itemIndex++) { MobileListItem item = items[itemIndex]; writer.WriteFullBeginTag("tr"); writer.WriteBeginTag("td"); if(nowrap) { writer.WriteAttribute("nowrap","true"); } writer.Write(">"); writer.WriteBeginTag("input"); writer.WriteAttribute("type", selectTypeString); writer.WriteAttribute("name", renderName); WriteItemValueAttribute(writer, itemIndex, item.Value); if (item.Selected && (Control.IsMultiSelect || itemIndex == selectedIndex) && Device.SupportsUncheck) { writer.Write(" checked>"); } else { writer.Write(">"); } writer.MarkStyleContext(); writer.EnterFormat(Style); writer.WriteEncodedText(item.Text); writer.ExitFormat(Style); writer.UnMarkStyleContext(); writer.WriteEndTag("td"); writer.WriteEndTag("tr"); } writer.WriteEndTag("table"); writer.EndStyleContext(); writer.ExitFormat(Style, Control.BreakAfter); } break; } } // Parse the HTML posted data appropriately. /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter.LoadPostData"]/*' /> public override bool LoadPostData(String key, NameValueCollection data, Object controlPrivateData, out bool dataChanged) { String[] selectedItems = data.GetValues(key); Debug.Assert (String.IsNullOrEmpty(Control.Form.Action), "Cross page post (!IsPostBack) assumed when Form.Action nonempty." + "LoadPostData should not have been be called."); // If no post data is included, and the control is either not visible, or // not on active form, this call should be ignored (the lack of post data // is not due to there being no selection, but due to there being no // markup rendered that could generate the post data). if (selectedItems == null && (!Control.Visible || Control.Form != Control.MobilePage.ActiveForm)) { dataChanged = false; return true; } // Case where nothing is selected. if(selectedItems == null || (selectedItems.Length == 1 && (selectedItems[0] != null && selectedItems[0].Length == 0))) { selectedItems = new String[]{}; } int[] selectedItemIndices = new int[selectedItems.Length]; // Note: controlPrivateData is selected indices from the viewstate. int[] originalSelectedIndices = (int[])controlPrivateData; dataChanged = false; // If SelectType is DropDown && nothing was selected, select // first elt. (Non-mobile DropDown does same by getting SelectedIndex). if(Control.SelectType == ListSelectType.DropDown && originalSelectedIndices.Length == 0 && Control.Items.Count > 0) { Control.Items[0].Selected = true; originalSelectedIndices = new int[]{0}; } for(int i = 0; i < selectedItems.Length; i++) { selectedItemIndices[i] = Int32.Parse(selectedItems[i], CultureInfo.InvariantCulture); } // Do not assume posted selected indices are ascending. // We do know originalSelectedIndices are ascending. Array.Sort(selectedItemIndices); // Check whether selections have changed. if(selectedItemIndices.Length != originalSelectedIndices.Length) { dataChanged = true; } else { for(int i = 0; i < selectedItems.Length; i++) { if(selectedItemIndices[i] != originalSelectedIndices[i]) { dataChanged = true; } } } for (int i = 0; i < Control.Items.Count; i++) { Control.Items[i].Selected = false; } for(int i = 0; i < selectedItemIndices.Length; i++) { Control.Items[selectedItemIndices[i]].Selected = true; } return true; } private void WriteItemValueAttribute(HtmlTextWriter writer, int index, String value) { if (Page.DesignMode || String.IsNullOrEmpty(Control.Form.Action)) { writer.WriteAttribute("value", index.ToString(CultureInfo.InvariantCulture)); } else { writer.WriteAttribute("value", value, true /*encode*/); } } /// <include file='doc\HtmlSelectionListAdapter.uex' path='docs/doc[@for="HtmlSelectionListAdapter.RenderAsHiddenInputField"]/*' /> protected override void RenderAsHiddenInputField(HtmlMobileTextWriter writer) { // Optimization - if viewstate is enabled for this control, and the // postback returns to this page, we just let it do the trick. // One catch though - if the control is multiselect, it always // interprets return values, so we do need to write out. if (Control.IsMultiSelect || Control.Form.Action.Length > 0 || !IsViewStateEnabled()) { String uniqueID = Control.UniqueID; MobileListItemCollection items = Control.Items; for (int i = 0; i < items.Count; i++) { if (items[i].Selected) { writer.WriteHiddenField(uniqueID, i.ToString(CultureInfo.InvariantCulture)); } } } } private bool IsViewStateEnabled() { Control ctl = Control; while (ctl != null) { if (!ctl.EnableViewState) { return false; } ctl = ctl.Parent; } return true; } } }
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 sep02v1.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleXmlTextReaderSetInsecureResolution).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleXmlTextReaderSetInsecureResolution).WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseXmlTextReaderNoCtorShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { var count = reader.AttributeCount; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Dim count = reader.AttributeCount End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderNoCtorSetResolverToNullShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { reader.XmlResolver = new XmlUrlResolver(); } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) reader.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13) ); } [Fact] public async Task XmlTextReaderNoCtorSetDtdProcessingToParseShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { reader.DtdProcessing = DtdProcessing.Parse; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) reader.DtdProcessing = DtdProcessing.Parse End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13) ); } [Fact] public async Task XmlTextReaderNoCtorSetBothToInsecureValuesShouldGenerateDiagnostics() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader, XmlUrlResolver resolver) { reader.XmlResolver = resolver; reader.DtdProcessing = DtdProcessing.Parse; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13), GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader, resolver As XmlUrlResolver) reader.XmlResolver = resolver reader.DtdProcessing = DtdProcessing.Parse End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13), GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 13) ); } [Fact] public async Task XmlTextReaderNoCtorSetInSecureResolverInTryClauseShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { reader.XmlResolver = new XmlUrlResolver(); } catch { throw; } } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try reader.XmlResolver = New XmlUrlResolver() Catch Throw End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17) ); } [Fact] public async Task XmlTextReaderNoCtorSetInSecureResolverInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { } catch { reader.XmlResolver = new XmlUrlResolver(); } finally {} } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try Catch reader.XmlResolver = New XmlUrlResolver() Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17) ); } [Fact] public async Task XmlTextReaderNoCtorSetInSecureResolverInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { } catch { throw; } finally { reader.XmlResolver = new XmlUrlResolver(); } } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try Catch Throw Finally reader.XmlResolver = New XmlUrlResolver() End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17) ); } [Fact] public async Task XmlTextReaderNoCtorSetDtdprocessingToParseInTryClauseShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { reader.DtdProcessing = DtdProcessing.Parse; } catch { throw; } } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try reader.DtdProcessing = DtdProcessing.Parse Catch Throw End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17) ); } [Fact] public async Task XmlTextReaderNoCtorSetDtdprocessingToParseInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { } catch { reader.DtdProcessing = DtdProcessing.Parse; } finally { } } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try Catch reader.DtdProcessing = DtdProcessing.Parse Finally End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17) ); } [Fact] public async Task XmlTextReaderNoCtorSetDtdprocessingToParseInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlTextReader reader) { try { } catch { throw; } finally { reader.DtdProcessing = DtdProcessing.Parse; } } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(reader As XmlTextReader) Try Catch Throw Finally reader.DtdProcessing = DtdProcessing.Parse End Try End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17) ); } [Fact] public async Task ConstructXmlTextReaderSetInsecureResolverInInitializerShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { XmlResolver = new XmlUrlResolver() }; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .XmlResolver = New XmlUrlResolver() _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24) ); } [Fact] public async Task ConstructXmlTextReaderSetDtdProcessingParseInInitializerShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { DtdProcessing = DtdProcessing.Parse }; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .DtdProcessing = DtdProcessing.Parse _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24) ); } [Fact] public async Task ConstructXmlTextReaderSetBothToInsecureValuesInInitializerShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(string path) { XmlTextReader doc = new XmlTextReader(path) { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(path As String) Dim doc As New XmlTextReader(path) With { _ .DtdProcessing = DtdProcessing.Parse, _ .XmlResolver = New XmlUrlResolver() _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24) ); } [Fact] public async Task XmlTextReaderDerivedTypeSetInsecureResolverShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlTextReader {} class TestClass { void TestMethod() { var c = new DerivedType(){ XmlResolver = new XmlUrlResolver() }; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlTextReader End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() With { _ .XmlResolver = New XmlUrlResolver() _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21) ); } [Fact] public async Task XmlTextReaderDerivedTypeSetDtdProcessingParseShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlTextReader {} class TestClass { void TestMethod() { var c = new DerivedType(){ DtdProcessing = DtdProcessing.Parse }; } } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlTextReader End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() With { _ .DtdProcessing = DtdProcessing.Parse _ } End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21) ); } [Fact] public async Task XmlTextReaderCreatedAsTempSetSecureSettingsShouldNotGenerateDiagnostics() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1(string path) { Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit }); } public void Method2(XmlTextReader reader){} } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1(path As String) Method2(New XmlTextReader(path) With { _ .XmlResolver = Nothing, _ .DtdProcessing = DtdProcessing.Prohibit _ }) End Sub Public Sub Method2(reader As XmlTextReader) End Sub End Class End Namespace"); } [Fact] public async Task XmlTextReaderCreatedAsTempSetInsecureResolverShouldGenerateDiagnostics() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1(string path) { Method2(new XmlTextReader(path){ XmlResolver = new XmlUrlResolver(), DtdProcessing = DtdProcessing.Prohibit }); } public void Method2(XmlTextReader reader){} } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1(path As String) Method2(New XmlTextReader(path) With { _ .XmlResolver = New XmlUrlResolver(), _ .DtdProcessing = DtdProcessing.Prohibit _ }) End Sub Public Sub Method2(reader As XmlTextReader) End Sub End Class End Namespace ", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21) ); } [Fact] public async Task XmlTextReaderCreatedAsTempSetDtdProcessingParseShouldGenerateDiagnostics() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1(string path) { Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Parse }); } public void Method2(XmlTextReader reader){} } }", GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1(path As String) Method2(New XmlTextReader(path) With { _ .XmlResolver = Nothing, _ .DtdProcessing = DtdProcessing.Parse _ }) End Sub Public Sub Method2(reader As XmlTextReader) End Sub End Class End Namespace", GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21) ); } } }
#region Header /** * JsonReader.cs * Stream-like access to JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PerfAssist.LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, Double, String, Boolean, Null } public class JsonReader { #region Fields private static IDictionary<int, IDictionary<int, int[]>> parse_table; private Stack<int> automaton_stack; private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private bool skip_non_members; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool SkipNonMembers { get { return skip_non_members; } set { skip_non_members = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors static JsonReader () { PopulateParseTable (); } public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; automaton_stack = new Stack<int> (); automaton_stack.Push ((int) ParserToken.End); automaton_stack.Push ((int) ParserToken.Text); lexer = new Lexer (reader); end_of_input = false; end_of_json = false; skip_non_members = true; this.reader = reader; reader_is_owned = owned; } #endregion #region Static Methods private static void PopulateParseTable () { // See section A.2. of the manual for details parse_table = new Dictionary<int, IDictionary<int, int[]>> (); TableAddRow (ParserToken.Array); TableAddCol (ParserToken.Array, '[', '[', (int) ParserToken.ArrayPrime); TableAddRow (ParserToken.ArrayPrime); TableAddCol (ParserToken.ArrayPrime, '"', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, '[', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, ']', ']'); TableAddCol (ParserToken.ArrayPrime, '{', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Number, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.True, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.False, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Null, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddRow (ParserToken.Object); TableAddCol (ParserToken.Object, '{', '{', (int) ParserToken.ObjectPrime); TableAddRow (ParserToken.ObjectPrime); TableAddCol (ParserToken.ObjectPrime, '"', (int) ParserToken.Pair, (int) ParserToken.PairRest, '}'); TableAddCol (ParserToken.ObjectPrime, '}', '}'); TableAddRow (ParserToken.Pair); TableAddCol (ParserToken.Pair, '"', (int) ParserToken.String, ':', (int) ParserToken.Value); TableAddRow (ParserToken.PairRest); TableAddCol (ParserToken.PairRest, ',', ',', (int) ParserToken.Pair, (int) ParserToken.PairRest); TableAddCol (ParserToken.PairRest, '}', (int) ParserToken.Epsilon); TableAddRow (ParserToken.String); TableAddCol (ParserToken.String, '"', '"', (int) ParserToken.CharSeq, '"'); TableAddRow (ParserToken.Text); TableAddCol (ParserToken.Text, '[', (int) ParserToken.Array); TableAddCol (ParserToken.Text, '{', (int) ParserToken.Object); TableAddRow (ParserToken.Value); TableAddCol (ParserToken.Value, '"', (int) ParserToken.String); TableAddCol (ParserToken.Value, '[', (int) ParserToken.Array); TableAddCol (ParserToken.Value, '{', (int) ParserToken.Object); TableAddCol (ParserToken.Value, (int) ParserToken.Number, (int) ParserToken.Number); TableAddCol (ParserToken.Value, (int) ParserToken.True, (int) ParserToken.True); TableAddCol (ParserToken.Value, (int) ParserToken.False, (int) ParserToken.False); TableAddCol (ParserToken.Value, (int) ParserToken.Null, (int) ParserToken.Null); TableAddRow (ParserToken.ValueRest); TableAddCol (ParserToken.ValueRest, ',', ',', (int) ParserToken.Value, (int) ParserToken.ValueRest); TableAddCol (ParserToken.ValueRest, ']', (int) ParserToken.Epsilon); } private static void TableAddCol (ParserToken row, int col, params int[] symbols) { parse_table[(int) row].Add (col, symbols); } private static void TableAddRow (ParserToken rule) { parse_table.Add ((int) rule, new Dictionary<int, int[]> ()); } #endregion #region Private Methods private void ProcessNumber (string number) { if (number.IndexOf ('.') != -1 || number.IndexOf ('e') != -1 || number.IndexOf ('E') != -1) { double n_double; if (Double.TryParse (number, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse (number, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse (number, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } ulong n_uint64; if (UInt64.TryParse(number, out n_uint64)) { token = JsonToken.Long; token_value = n_uint64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } #endregion public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; if (reader_is_owned) reader.Close (); reader = null; } public bool Read () { if (end_of_input) return false; if (end_of_json) { end_of_json = false; automaton_stack.Clear (); automaton_stack.Push ((int) ParserToken.End); automaton_stack.Push ((int) ParserToken.Text); } parser_in_string = false; parser_return = false; token = JsonToken.None; token_value = null; if (! read_started) { read_started = true; if (! ReadToken ()) return false; } int[] entry_symbols; while (true) { if (parser_return) { if (automaton_stack.Peek () == (int) ParserToken.End) end_of_json = true; return true; } current_symbol = automaton_stack.Pop (); ProcessSymbol (); if (current_symbol == current_input) { if (! ReadToken ()) { if (automaton_stack.Peek () != (int) ParserToken.End) throw new JsonException ( "Input doesn't evaluate to proper JSON text"); if (parser_return) return true; return false; } continue; } try { entry_symbols = parse_table[current_symbol][current_input]; } catch (KeyNotFoundException e) { throw new JsonException ((ParserToken) current_input, e); } if (entry_symbols[0] == (int) ParserToken.Epsilon) continue; for (int i = entry_symbols.Length - 1; i >= 0; i--) automaton_stack.Push (entry_symbols[i]); } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Encapsulates initialization and shutdown of gRPC library. /// </summary> public class GrpcEnvironment { const int MinDefaultThreadPoolSize = 4; const int DefaultBatchContextPoolSharedCapacity = 10000; const int DefaultBatchContextPoolThreadLocalCapacity = 64; const int DefaultRequestCallContextPoolSharedCapacity = 10000; const int DefaultRequestCallContextPoolThreadLocalCapacity = 64; static object staticLock = new object(); static GrpcEnvironment instance; static int refCount; static int? customThreadPoolSize; static int? customCompletionQueueCount; static bool inlineHandlers; static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity; static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity; static int requestCallContextPoolSharedCapacity = DefaultRequestCallContextPoolSharedCapacity; static int requestCallContextPoolThreadLocalCapacity = DefaultRequestCallContextPoolThreadLocalCapacity; static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>(); static readonly HashSet<Server> registeredServers = new HashSet<Server>(); static readonly AtomicCounter nativeInitCounter = new AtomicCounter(); static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true); readonly IObjectPool<BatchContextSafeHandle> batchContextPool; readonly IObjectPool<RequestCallContextSafeHandle> requestCallContextPool; readonly GrpcThreadPool threadPool; readonly DebugStats debugStats = new DebugStats(); readonly AtomicCounter cqPickerCounter = new AtomicCounter(); bool isShutdown; /// <summary> /// Returns a reference-counted instance of initialized gRPC environment. /// Subsequent invocations return the same instance unless reference count has dropped to zero previously. /// </summary> internal static GrpcEnvironment AddRef() { ShutdownHooks.Register(); lock (staticLock) { refCount++; if (instance == null) { instance = new GrpcEnvironment(); } return instance; } } /// <summary> /// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero. /// </summary> internal static async Task ReleaseAsync() { GrpcEnvironment instanceToShutdown = null; lock (staticLock) { GrpcPreconditions.CheckState(refCount > 0); refCount--; if (refCount == 0) { instanceToShutdown = instance; instance = null; } } if (instanceToShutdown != null) { await instanceToShutdown.ShutdownAsync().ConfigureAwait(false); } } internal static int GetRefCount() { lock (staticLock) { return refCount; } } internal static void RegisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); registeredChannels.Add(channel); } } internal static void UnregisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set."); } } internal static void RegisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); registeredServers.Add(server); } } internal static void UnregisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set."); } } /// <summary> /// Requests shutdown of all channels created by the current process. /// </summary> public static Task ShutdownChannelsAsync() { HashSet<Channel> snapshot = null; lock (staticLock) { snapshot = new HashSet<Channel>(registeredChannels); } return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync())); } /// <summary> /// Requests immediate shutdown of all servers created by the current process. /// </summary> public static Task KillServersAsync() { HashSet<Server> snapshot = null; lock (staticLock) { snapshot = new HashSet<Server>(registeredServers); } return Task.WhenAll(snapshot.Select((server) => server.KillAsync())); } /// <summary> /// Gets application-wide logger used by gRPC. /// </summary> /// <value>The logger.</value> public static ILogger Logger { get { return logger; } } /// <summary> /// Sets the application-wide logger that should be used by gRPC. /// </summary> public static void SetLogger(ILogger customLogger) { GrpcPreconditions.CheckNotNull(customLogger, "customLogger"); logger = customLogger; } /// <summary> /// Sets the number of threads in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetThreadPoolSize(int threadCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number"); customThreadPoolSize = threadCount; } } /// <summary> /// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetCompletionQueueCount(int completionQueueCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number"); customCompletionQueueCount = completionQueueCount; } } /// <summary> /// By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (<c>inlineHandlers=false</c>). /// Setting <c>inlineHandlers</c> to <c>true</c> will allow scheduling the event handlers directly to /// <c>GrpcThreadPool</c> internal threads. That can lead to significant performance gains in some situations, /// but requires user to never block in async code (incorrectly written code can easily lead to deadlocks). /// Inlining handlers is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// Note: <c>inlineHandlers=true</c> was the default in gRPC C# v1.4.x and earlier. /// </summary> public static void SetHandlerInlining(bool inlineHandlers) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcEnvironment.inlineHandlers = inlineHandlers; } } /// <summary> /// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances /// instead of creating a new one for every C core operation helps reducing the GC pressure. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// This is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); batchContextPoolSharedCapacity = sharedCapacity; batchContextPoolThreadLocalCapacity = threadLocalCapacity; } } /// <summary> /// Sets the parameters for a pool that caches request call context instances. Reusing request call context instances /// instead of creating a new one for every requested call in C core helps reducing the GC pressure. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// This is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetRequestCallContextPoolParams(int sharedCapacity, int threadLocalCapacity) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); requestCallContextPoolSharedCapacity = sharedCapacity; requestCallContextPoolThreadLocalCapacity = threadLocalCapacity; } } /// <summary> /// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic. /// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first). /// </summary> public static event EventHandler ShuttingDown; /// <summary> /// Creates gRPC environment. /// </summary> private GrpcEnvironment() { GrpcNativeInit(); batchContextPool = new DefaultObjectPool<BatchContextSafeHandle>(() => BatchContextSafeHandle.Create(), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity); requestCallContextPool = new DefaultObjectPool<RequestCallContextSafeHandle>(() => RequestCallContextSafeHandle.Create(), requestCallContextPoolSharedCapacity, requestCallContextPoolThreadLocalCapacity); threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers); threadPool.Start(); } /// <summary> /// Gets the completion queues used by this gRPC environment. /// </summary> internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues { get { return this.threadPool.CompletionQueues; } } internal IObjectPool<BatchContextSafeHandle> BatchContextPool => batchContextPool; internal IObjectPool<RequestCallContextSafeHandle> RequestCallContextPool => requestCallContextPool; internal bool IsAlive { get { return this.threadPool.IsAlive; } } /// <summary> /// Picks a completion queue in a round-robin fashion. /// Shouldn't be invoked on a per-call basis (used at per-channel basis). /// </summary> internal CompletionQueueSafeHandle PickCompletionQueue() { var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count); return this.threadPool.CompletionQueues.ElementAt(cqIndex); } /// <summary> /// Gets the completion queue used by this gRPC environment. /// </summary> internal DebugStats DebugStats { get { return this.debugStats; } } /// <summary> /// Gets version of gRPC C core. /// </summary> internal static string GetCoreVersionString() { var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned return Marshal.PtrToStringAnsi(ptr); } internal static void GrpcNativeInit() { if (!IsNativeShutdownAllowed && nativeInitCounter.Count > 0) { // Normally grpc_init and grpc_shutdown calls should come in pairs (C core does reference counting), // but in case we avoid grpc_shutdown calls altogether, calling grpc_init has no effect // besides incrementing an internal C core counter that could theoretically overflow. // To avoid this theoretical possibility we guard repeated calls to grpc_init() // with a 64-bit atomic counter (that can't realistically overflow). return; } NativeMethods.Get().grpcsharp_init(); nativeInitCounter.Increment(); } internal static void GrpcNativeShutdown() { if (IsNativeShutdownAllowed) { NativeMethods.Get().grpcsharp_shutdown(); } } /// <summary> /// Shuts down this environment. /// </summary> private async Task ShutdownAsync() { if (isShutdown) { throw new InvalidOperationException("ShutdownAsync has already been called"); } await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false); await threadPool.StopAsync().ConfigureAwait(false); requestCallContextPool.Dispose(); batchContextPool.Dispose(); GrpcNativeShutdown(); isShutdown = true; debugStats.CheckOK(); } private int GetThreadPoolSizeOrDefault() { if (customThreadPoolSize.HasValue) { return customThreadPoolSize.Value; } // In systems with many cores, use half of the cores for GrpcThreadPool // and the other half for .NET thread pool. This heuristic definitely needs // more work, but seems to work reasonably well for a start. return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2); } private int GetCompletionQueueCountOrDefault() { if (customCompletionQueueCount.HasValue) { return customCompletionQueueCount.Value; } // by default, create a completion queue for each thread return GetThreadPoolSizeOrDefault(); } // On some platforms (specifically iOS), thread local variables in native code // require initialization/destruction. By skipping the grpc_shutdown() call, // we avoid a potential crash where grpc_shutdown() has already destroyed // the thread local variables, but some C core's *_destroy() methods still // need to run (e.g. they may be run by finalizer thread which is out of our control) // For more context, see https://github.com/grpc/grpc/issues/16294 private static bool IsNativeShutdownAllowed => !PlatformApis.IsXamarinIOS && !PlatformApis.IsUnityIOS; private static class ShutdownHooks { static object staticLock = new object(); static bool hooksRegistered; public static void Register() { lock (staticLock) { if (!hooksRegistered) { // Under normal circumstances, the user is expected to shutdown all // the gRPC channels and servers before the application exits. The following // hooks provide some extra handling for cases when this is not the case, // in the effort to achieve a reasonable behavior on shutdown. #if NETSTANDARD // No action required at shutdown on .NET Core // - In-progress P/Invoke calls (such as grpc_completion_queue_next) don't seem // to prevent a .NET core application from terminating, so no special handling // is needed. // - .NET core doesn't run finalizers on shutdown, so there's no risk of getting // a crash because grpc_*_destroy methods for native objects being invoked // in wrong order. // TODO(jtattermusch): Verify that the shutdown hooks are still not needed // once we add support for new platforms using netstandard (e.g. Xamarin). #else // On desktop .NET framework and Mono, we need to register for a shutdown // event to explicitly shutdown the GrpcEnvironment. // - On Desktop .NET framework, we need to do a proper shutdown to prevent a crash // when the framework attempts to run the finalizers for SafeHandle object representing the native // grpc objects. The finalizers calls the native grpc_*_destroy methods (e.g. grpc_server_destroy) // in a random order, which is not supported by gRPC. // - On Mono, the process would freeze as the GrpcThreadPool threads are sleeping // in grpc_completion_queue_next P/Invoke invocation and mono won't let the // process shutdown until the P/Invoke calls return. We achieve that by shutting down // the completion queue(s) which associated with the GrpcThreadPool, which will // cause the grpc_completion_queue_next calls to return immediately. AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); }; AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); }; #endif } hooksRegistered = true; } } /// <summary> /// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks. /// </summary> private static void HandleShutdown() { Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync()); } } } }
// 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 * Google Analytics API Version v2.4 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/analytics/'>Google Analytics API</a> * <tr><th>API Version<td>v2.4 * <tr><th>API Rev<td>20170321 (810) * <tr><th>API Docs * <td><a href='https://developers.google.com/analytics/'> * https://developers.google.com/analytics/</a> * <tr><th>Discovery Name<td>analytics * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Analytics API can be found at * <a href='https://developers.google.com/analytics/'>https://developers.google.com/analytics/</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.Analytics.v2_4 { /// <summary>The Analytics Service.</summary> public class AnalyticsService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v2.4"; /// <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 AnalyticsService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public AnalyticsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { data = new DataResource(this); management = new ManagementResource(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 "analytics"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/analytics/v2.4/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "analytics/v2.4/"; } } #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 /// <summary>Available OAuth 2.0 scopes for use with the Google Analytics API.</summary> public class Scope { /// <summary>View and manage your Google Analytics data</summary> public static string Analytics = "https://www.googleapis.com/auth/analytics"; /// <summary>View your Google Analytics data</summary> public static string AnalyticsReadonly = "https://www.googleapis.com/auth/analytics.readonly"; } private readonly DataResource data; /// <summary>Gets the Data resource.</summary> public virtual DataResource Data { get { return data; } } private readonly ManagementResource management; /// <summary>Gets the Management resource.</summary> public virtual ManagementResource Management { get { return management; } } } ///<summary>A base abstract class for Analytics requests.</summary> public abstract class AnalyticsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new AnalyticsBaseServiceRequest instance.</summary> protected AnalyticsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: atom] [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/atom+xml</summary> [Google.Apis.Util.StringValueAttribute("atom")] Atom, } /// <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: false] [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 Analytics parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "atom", 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 = "false", 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 "data" collection of methods.</summary> public class DataResource { private const string Resource = "data"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public DataResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Returns Analytics report data for a view (profile).</summary> /// <param name="ids">Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the /// Analytics view (profile) ID.</param> /// <param name="startDate">Start date for fetching report data. All /// requests should specify a start date formatted as YYYY-MM-DD.</param> /// <param name="endDate">End date for /// fetching report data. All requests should specify an end date formatted as YYYY-MM-DD.</param> /// <param /// name="metrics">A comma-separated list of Analytics metrics. E.g., 'ga:sessions,ga:pageviews'. At least one metric /// must be specified to retrieve a valid Analytics report.</param> public virtual GetRequest Get(string ids, string startDate, string endDate, string metrics) { return new GetRequest(service, ids, startDate, endDate, metrics); } /// <summary>Returns Analytics report data for a view (profile).</summary> public class GetRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string ids, string startDate, string endDate, string metrics) : base(service) { Ids = ids; StartDate = startDate; EndDate = endDate; Metrics = metrics; InitParameters(); } /// <summary>Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the /// Analytics view (profile) ID.</summary> [Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)] public virtual string Ids { get; private set; } /// <summary>Start date for fetching report data. All requests should specify a start date formatted as /// YYYY-MM-DD.</summary> [Google.Apis.Util.RequestParameterAttribute("start-date", Google.Apis.Util.RequestParameterType.Query)] public virtual string StartDate { get; private set; } /// <summary>End date for fetching report data. All requests should specify an end date formatted as YYYY- /// MM-DD.</summary> [Google.Apis.Util.RequestParameterAttribute("end-date", Google.Apis.Util.RequestParameterType.Query)] public virtual string EndDate { get; private set; } /// <summary>A comma-separated list of Analytics metrics. E.g., 'ga:sessions,ga:pageviews'. At least one /// metric must be specified to retrieve a valid Analytics report.</summary> [Google.Apis.Util.RequestParameterAttribute("metrics", Google.Apis.Util.RequestParameterType.Query)] public virtual string Metrics { get; private set; } /// <summary>A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.</summary> [Google.Apis.Util.RequestParameterAttribute("dimensions", Google.Apis.Util.RequestParameterType.Query)] public virtual string Dimensions { get; set; } /// <summary>A comma-separated list of dimension or metric filters to be applied to the report /// data.</summary> [Google.Apis.Util.RequestParameterAttribute("filters", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filters { get; set; } /// <summary>The maximum number of entries to include in this feed.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An Analytics advanced segment to be applied to the report data.</summary> [Google.Apis.Util.RequestParameterAttribute("segment", Google.Apis.Util.RequestParameterType.Query)] public virtual string Segment { get; set; } /// <summary>A comma-separated list of dimensions or metrics that determine the sort order for the report /// data.</summary> [Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)] public virtual string Sort { get; set; } /// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism along /// with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<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 "data"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "ids", new Google.Apis.Discovery.Parameter { Name = "ids", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"ga:[0-9]+", }); RequestParameters.Add( "start-date", new Google.Apis.Discovery.Parameter { Name = "start-date", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"[0-9]{4}-[0-9]{2}-[0-9]{2}", }); RequestParameters.Add( "end-date", new Google.Apis.Discovery.Parameter { Name = "end-date", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"[0-9]{4}-[0-9]{2}-[0-9]{2}", }); RequestParameters.Add( "metrics", new Google.Apis.Discovery.Parameter { Name = "metrics", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"ga:.+", }); RequestParameters.Add( "dimensions", new Google.Apis.Discovery.Parameter { Name = "dimensions", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"(ga:.+)?", }); RequestParameters.Add( "filters", new Google.Apis.Discovery.Parameter { Name = "filters", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"ga:.+", }); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "segment", new Google.Apis.Discovery.Parameter { Name = "segment", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "sort", new Google.Apis.Discovery.Parameter { Name = "sort", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"(-)?ga:.+", }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "management" collection of methods.</summary> public class ManagementResource { private const string Resource = "management"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ManagementResource(Google.Apis.Services.IClientService service) { this.service = service; accounts = new AccountsResource(service); goals = new GoalsResource(service); profiles = new ProfilesResource(service); segments = new SegmentsResource(service); webproperties = new WebpropertiesResource(service); } private readonly AccountsResource accounts; /// <summary>Gets the Accounts resource.</summary> public virtual AccountsResource Accounts { get { return accounts; } } /// <summary>The "accounts" collection of methods.</summary> public class AccountsResource { private const string Resource = "accounts"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public AccountsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists all accounts to which the user has access.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists all accounts to which the user has access.</summary> public class ListRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>The maximum number of accounts to include in this response.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An index of the first account to retrieve. Use this parameter as a pagination mechanism /// along with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { 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 "management/accounts"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } private readonly GoalsResource goals; /// <summary>Gets the Goals resource.</summary> public virtual GoalsResource Goals { get { return goals; } } /// <summary>The "goals" collection of methods.</summary> public class GoalsResource { private const string Resource = "goals"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public GoalsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists goals to which the user has access.</summary> /// <param name="accountId">Account ID to retrieve goals for. Can either be a specific account ID or '~all', which /// refers to all the accounts that user has access to.</param> /// <param name="webPropertyId">Web property ID to /// retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that /// user has access to.</param> /// <param name="profileId">View (Profile) ID to retrieve goals for. Can either be a /// specific view (profile) ID or '~all', which refers to all the views (profiles) that user has access to.</param> public virtual ListRequest List(string accountId, string webPropertyId, string profileId) { return new ListRequest(service, accountId, webPropertyId, profileId); } /// <summary>Lists goals to which the user has access.</summary> public class ListRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string accountId, string webPropertyId, string profileId) : base(service) { AccountId = accountId; WebPropertyId = webPropertyId; ProfileId = profileId; InitParameters(); } /// <summary>Account ID to retrieve goals for. Can either be a specific account ID or '~all', which /// refers to all the accounts that user has access to.</summary> [Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)] public virtual string AccountId { get; private set; } /// <summary>Web property ID to retrieve goals for. Can either be a specific web property ID or '~all', /// which refers to all the web properties that user has access to.</summary> [Google.Apis.Util.RequestParameterAttribute("webPropertyId", Google.Apis.Util.RequestParameterType.Path)] public virtual string WebPropertyId { get; private set; } /// <summary>View (Profile) ID to retrieve goals for. Can either be a specific view (profile) ID or /// '~all', which refers to all the views (profiles) that user has access to.</summary> [Google.Apis.Util.RequestParameterAttribute("profileId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProfileId { get; private set; } /// <summary>The maximum number of goals to include in this response.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An index of the first goal to retrieve. Use this parameter as a pagination mechanism along /// with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { 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 "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "accountId", new Google.Apis.Discovery.Parameter { Name = "accountId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "webPropertyId", new Google.Apis.Discovery.Parameter { Name = "webPropertyId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "profileId", new Google.Apis.Discovery.Parameter { Name = "profileId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } private readonly ProfilesResource profiles; /// <summary>Gets the Profiles resource.</summary> public virtual ProfilesResource Profiles { get { return profiles; } } /// <summary>The "profiles" collection of methods.</summary> public class ProfilesResource { private const string Resource = "profiles"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProfilesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists views (profiles) to which the user has access.</summary> /// <param name="accountId">Account ID for the views (profiles) to retrieve. Can either be a specific account ID or /// '~all', which refers to all the accounts to which the user has access.</param> /// <param /// name="webPropertyId">Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID /// or '~all', which refers to all the web properties to which the user has access.</param> public virtual ListRequest List(string accountId, string webPropertyId) { return new ListRequest(service, accountId, webPropertyId); } /// <summary>Lists views (profiles) to which the user has access.</summary> public class ListRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string accountId, string webPropertyId) : base(service) { AccountId = accountId; WebPropertyId = webPropertyId; InitParameters(); } /// <summary>Account ID for the views (profiles) to retrieve. Can either be a specific account ID or /// '~all', which refers to all the accounts to which the user has access.</summary> [Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)] public virtual string AccountId { get; private set; } /// <summary>Web property ID for the views (profiles) to retrieve. Can either be a specific web property /// ID or '~all', which refers to all the web properties to which the user has access.</summary> [Google.Apis.Util.RequestParameterAttribute("webPropertyId", Google.Apis.Util.RequestParameterType.Path)] public virtual string WebPropertyId { get; private set; } /// <summary>The maximum number of views (profiles) to include in this response.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism /// along with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { 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 "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "accountId", new Google.Apis.Discovery.Parameter { Name = "accountId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "webPropertyId", new Google.Apis.Discovery.Parameter { Name = "webPropertyId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } private readonly SegmentsResource segments; /// <summary>Gets the Segments resource.</summary> public virtual SegmentsResource Segments { get { return segments; } } /// <summary>The "segments" collection of methods.</summary> public class SegmentsResource { private const string Resource = "segments"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SegmentsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists advanced segments to which the user has access.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists advanced segments to which the user has access.</summary> public class ListRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>The maximum number of advanced segments to include in this response.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An index of the first advanced segment to retrieve. Use this parameter as a pagination /// mechanism along with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { 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 "management/segments"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } private readonly WebpropertiesResource webproperties; /// <summary>Gets the Webproperties resource.</summary> public virtual WebpropertiesResource Webproperties { get { return webproperties; } } /// <summary>The "webproperties" collection of methods.</summary> public class WebpropertiesResource { private const string Resource = "webproperties"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public WebpropertiesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists web properties to which the user has access.</summary> /// <param name="accountId">Account ID to retrieve web properties for. Can either be a specific account ID or '~all', /// which refers to all the accounts that user has access to.</param> public virtual ListRequest List(string accountId) { return new ListRequest(service, accountId); } /// <summary>Lists web properties to which the user has access.</summary> public class ListRequest : AnalyticsBaseServiceRequest<string> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string accountId) : base(service) { AccountId = accountId; InitParameters(); } /// <summary>Account ID to retrieve web properties for. Can either be a specific account ID or '~all', /// which refers to all the accounts that user has access to.</summary> [Google.Apis.Util.RequestParameterAttribute("accountId", Google.Apis.Util.RequestParameterType.Path)] public virtual string AccountId { get; private set; } /// <summary>The maximum number of web properties to include in this response.</summary> [Google.Apis.Util.RequestParameterAttribute("max-results", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> MaxResults { get; set; } /// <summary>An index of the first entity to retrieve. Use this parameter as a pagination mechanism /// along with the max-results parameter.</summary> /// [minimum: 1] [Google.Apis.Util.RequestParameterAttribute("start-index", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> StartIndex { 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 "management/accounts/{accountId}/webproperties"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "accountId", new Google.Apis.Discovery.Parameter { Name = "accountId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "max-results", new Google.Apis.Discovery.Parameter { Name = "max-results", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "start-index", new Google.Apis.Discovery.Parameter { Name = "start-index", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } } namespace Google.Apis.Analytics.v2_4.Data { }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar presence information (for tracking current location and /// message routing) to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianPresenceServiceConnector")] public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_serverUrl = String.Empty; private SimianActivityDetector m_activityDetector; private bool m_Enabled = false; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianPresenceServiceConnector() { } public string Name { get { return "SimianPresenceServiceConnector"; } } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IPresenceService>(this); scene.RegisterModuleInterface<IGridUserService>(this); m_activityDetector.AddRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IPresenceService>(this); scene.UnregisterModuleInterface<IGridUserService>(this); m_activityDetector.RemoveRegion(scene); LogoutRegionAgents(scene.RegionInfo.RegionID); } } #endregion ISharedRegionModule public SimianPresenceServiceConnector(IConfigSource source) { CommonInit(source); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("PresenceServices", ""); if (name == Name) CommonInit(source); } } private void CommonInit(IConfigSource source) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig != null) { string serviceUrl = gridConfig.GetString("PresenceServerURI"); if (!String.IsNullOrEmpty(serviceUrl)) { if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("=")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; m_activityDetector = new SimianActivityDetector(this); m_Enabled = true; } } if (String.IsNullOrEmpty(m_serverUrl)) m_log.Info("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI specified, disabling connector"); } #region IPresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}", userID, sessionID, secureSessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddSession" }, { "UserID", userID.ToString() } }; if (sessionID != UUID.Zero) { requestArgs["SessionID"] = sessionID.ToString(); requestArgs["SecureSessionID"] = secureSessionID.ToString(); } OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString()); return success; } public bool LogoutAgent(UUID sessionID) { // m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSession" }, { "SessionID", sessionID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString()); return success; } public bool LogoutRegionAgents(UUID regionID) { // m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveSessions" }, { "SceneID", regionID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString()); return success; } public bool ReportAgent(UUID sessionID, UUID regionID) { // Not needed for SimianGrid return true; } public PresenceInfo GetAgent(UUID sessionID) { OSDMap sessionResponse = GetSessionDataFromSessionID(sessionID); if (sessionResponse == null) { m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session {0}: {1}",sessionID.ToString(),sessionResponse["Message"].AsString()); return null; } UUID userID = sessionResponse["UserID"].AsUUID(); OSDMap userResponse = GetUserData(userID); if (userResponse == null) { m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}: {1}",userID.ToString(),userResponse["Message"].AsString()); return null; } return ResponseToPresenceInfo(sessionResponse); } public PresenceInfo[] GetAgents(string[] userIDs) { List<PresenceInfo> presences = new List<PresenceInfo>(); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSessions" }, { "UserIDList", String.Join(",",userIDs) } }; OSDMap sessionListResponse = SimianGrid.PostToService(m_serverUrl, requestArgs); if (! sessionListResponse["Success"].AsBoolean()) { m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve sessions: {0}",sessionListResponse["Message"].AsString()); return null; } OSDArray sessionList = sessionListResponse["Sessions"] as OSDArray; for (int i = 0; i < sessionList.Count; i++) { OSDMap sessionInfo = sessionList[i] as OSDMap; presences.Add(ResponseToPresenceInfo(sessionInfo)); } return presences.ToArray(); } #endregion IPresenceService #region IGridUserService public GridUserInfo LoggedIn(string userID) { // Never implemented at the sim return null; } public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Logging out user " + userID); // Remove the session to mark this user offline if (!LogoutAgent(sessionID)) return false; // Save our last position as user data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "HomeLocation", SerializeLocation(regionID, position, lookAt) } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString()); return success; } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { return UpdateSession(sessionID, regionID, lastPosition, lastLookAt); } public GridUserInfo GetGridUserInfo(string user) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user); UUID userID = new UUID(user); OSDMap userResponse = GetUserData(userID); if (userResponse == null) { m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}", userID); } // Note that ResponseToGridUserInfo properly checks for and returns a null if passed a null. return ResponseToGridUserInfo(userResponse); } #endregion #region Helpers private OSDMap GetUserData(UUID userID) { // m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean() && response["User"] is OSDMap) return response; m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}; {1}",userID.ToString(),response["Message"].AsString()); return null; } private OSDMap GetSessionDataFromSessionID(UUID sessionID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetSession" }, { "SessionID", sessionID.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) return response; m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session data for {0}; {1}",sessionID.ToString(),response["Message"].AsString()); return null; } private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // Save our current location as session data NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "UpdateSession" }, { "SessionID", sessionID.ToString() }, { "SceneID", regionID.ToString() }, { "ScenePosition", lastPosition.ToString() }, { "SceneLookAt", lastLookAt.ToString() } }; OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString()); return success; } private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse) { if (sessionResponse == null) return null; PresenceInfo info = new PresenceInfo(); info.UserID = sessionResponse["UserID"].AsUUID().ToString(); info.RegionID = sessionResponse["SceneID"].AsUUID(); return info; } private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse) { if (userResponse != null && userResponse["User"] is OSDMap) { GridUserInfo info = new GridUserInfo(); info.Online = true; info.UserID = userResponse["UserID"].AsUUID().ToString(); info.LastRegionID = userResponse["SceneID"].AsUUID(); info.LastPosition = userResponse["ScenePosition"].AsVector3(); info.LastLookAt = userResponse["SceneLookAt"].AsVector3(); OSDMap user = (OSDMap)userResponse["User"]; info.Login = user["LastLoginDate"].AsDate(); info.Logout = user["LastLogoutDate"].AsDate(); DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt); return info; } return null; } private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt) { return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}"; } private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt) { OSDMap map = null; try { map = OSDParser.DeserializeJson(location) as OSDMap; } catch { } if (map != null) { regionID = map["SceneID"].AsUUID(); if (Vector3.TryParse(map["Position"].AsString(), out position) && Vector3.TryParse(map["LookAt"].AsString(), out lookAt)) { return true; } } regionID = UUID.Zero; position = Vector3.Zero; lookAt = Vector3.Zero; return false; } public GridUserInfo[] GetGridUserInfo(string[] userIDs) { return new GridUserInfo[0]; } #endregion Helpers } }
// // 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 Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the Virtual /// IPs for your deployment. /// </summary> internal partial class VirtualIPOperations : IServiceOperations<NetworkManagementClient>, IVirtualIPOperations { /// <summary> /// Initializes a new instance of the VirtualIPOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualIPOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Add Virtual IP operation adds a logical Virtual IP to the /// deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </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 Task<OperationStatusResponse> AddAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginAddingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Begin Adding Virtual IP operation adds a logical Virtual IP to /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </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 Task<OperationStatusResponse> BeginAddingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginAddingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/"; url = url + Uri.EscapeDataString(virtualIPName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Removing Virtual IP operation removes a logical Virtual /// IP from the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </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 Task<OperationStatusResponse> BeginRemovingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginRemovingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/virtualIPs/"; url = url + Uri.EscapeDataString(virtualIPName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Virtual IP operation removes a logical Virtual IP from /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be removed. /// </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 Task<OperationStatusResponse> RemoveAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginRemovingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.PythonTools.Analysis { class Deque<T> : IEnumerable, ICollection { private T[] _data; private int _head, _tail; private int _itemCnt, _version; private static IEqualityComparer<T> _comparer = EqualityComparer<T>.Default; public Deque() { Clear(); } #region core deque APIs public void Append(T x) { _version++; if (_itemCnt == _data.Length) { GrowArray(); } _itemCnt++; _data[_tail++] = x; if (_tail == _data.Length) { _tail = 0; } } public void AppendLeft(T x) { _version++; if (_itemCnt == _data.Length) { GrowArray(); } _itemCnt++; --_head; if (_head < 0) { _head = _data.Length - 1; } _data[_head] = x; } public void Clear() { _version++; _head = _tail = 0; _itemCnt = 0; _data = new T[8]; } public T Pop() { if (_itemCnt == 0) { throw new InvalidOperationException("pop from an empty deque"); } _version++; if (_tail != 0) { _tail--; } else { _tail = _data.Length - 1; } _itemCnt--; T res = _data[_tail]; _data[_tail] = default(T); return res; } public T PopLeft() { if (_itemCnt == 0) { throw new InvalidOperationException("pop from an empty deque"); } _version++; T res = _data[_head]; _data[_head] = default(T); if (_head != _data.Length - 1) { _head++; } else { _head = 0; } _itemCnt--; return res; } public void Remove(T value) { int found = -1; int startVersion = _version; WalkDeque(delegate(int index) { if (_comparer.Equals(_data[index], value)) { found = index; return false; } return true; }); if (_version != startVersion) { throw new InvalidOperationException("deque mutated during remove()."); } if (found == _head) { PopLeft(); } else if (found == (_tail > 0 ? _tail - 1 : _data.Length - 1)) { Pop(); } else if (found == -1) { throw new ArgumentException("deque.remove(value): value not in deque"); } else { // otherwise we're removing from the middle and need to slide the values over... _version++; int start; if (_head >= _tail) { start = 0; } else { start = _head; } bool finished = false; T copying = _tail != 0 ? _data[_tail - 1] : _data[_data.Length - 1]; for (int i = _tail - 2; i >= start; i--) { T tmp = _data[i]; _data[i] = copying; if (i == found) { finished = true; break; } copying = tmp; } if (_head >= _tail && !finished) { for (int i = _data.Length - 1; i >= _head; i--) { T tmp = _data[i]; _data[i] = copying; if (i == found) break; copying = tmp; } } // we're one smaller now _tail--; _itemCnt--; if (_tail < 0) { // and tail just wrapped to the beginning _tail = _data.Length - 1; } } } public T this[int index] { get { return _data[IndexToSlot(index)]; } set { _version++; _data[IndexToSlot(index)] = value; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new DequeIterator(this); } private sealed class DequeIterator : IEnumerable, IEnumerator { private readonly Deque<T> _deque; private int _curIndex, _moveCnt, _version; public DequeIterator(Deque<T> d) { _deque = d; _curIndex = d._head - 1; _version = d._version; } #region IEnumerator Members object IEnumerator.Current { get { return _deque._data[_curIndex]; } } bool IEnumerator.MoveNext() { if (_version != _deque._version) { throw new InvalidOperationException("deque mutated during iteration"); } if (_moveCnt < _deque._itemCnt) { _curIndex++; _moveCnt++; if (_curIndex == _deque._data.Length) { _curIndex = 0; } return true; } return false; } void IEnumerator.Reset() { _moveCnt = 0; _curIndex = _deque._head - 1; } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return this; } #endregion } #endregion #region private members private void GrowArray() { T[] newData = new T[_data.Length * 2]; // make the array completely sequential again // by starting head back at 0. int cnt1, cnt2; if (_head >= _tail) { cnt1 = _data.Length - _head; cnt2 = _data.Length - cnt1; } else { cnt1 = _tail - _head; cnt2 = _data.Length - cnt1; } Array.Copy(_data, _head, newData, 0, cnt1); Array.Copy(_data, 0, newData, cnt1, cnt2); _head = 0; _tail = _data.Length; _data = newData; } private int IndexToSlot(int intIndex) { if (_itemCnt == 0) { throw new IndexOutOfRangeException("deque index out of range"); } if (intIndex >= 0) { if (intIndex >= _itemCnt) { throw new IndexOutOfRangeException("deque index out of range"); } int realIndex = _head + intIndex; if (realIndex >= _data.Length) { realIndex -= _data.Length; } return realIndex; } else { if ((intIndex * -1) > _itemCnt) { throw new IndexOutOfRangeException("deque index out of range"); } int realIndex = _tail + intIndex; if (realIndex < 0) { realIndex += _data.Length; } return realIndex; } } private delegate bool DequeWalker(int curIndex); /// <summary> /// Walks the queue calling back to the specified delegate for /// each populated index in the queue. /// </summary> private void WalkDeque(DequeWalker walker) { if (_itemCnt != 0) { int end; if (_head >= _tail) { end = _data.Length; } else { end = _tail; } for (int i = _head; i < end; i++) { if (!walker(i)) { return; } } if (_head >= _tail) { for (int i = 0; i < _tail; i++) { if (!walker(i)) { return; } } } } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { int i = 0; foreach (object o in this) { array.SetValue(o, index + i++); } } public int Count { get { return this._itemCnt; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session. /// </summary> internal sealed partial class SessionStateInternal { #region Functions /// <summary> /// Add an new SessionState function entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateFunctionEntry entry) { ScriptBlock sb = entry.ScriptBlock.Clone(); FunctionInfo fn = this.SetFunction(entry.Name, sb, null, entry.Options, false, CommandOrigin.Internal, this.ExecutionContext, entry.HelpFile, true); fn.Visibility = entry.Visibility; fn.Module = entry.Module; fn.ScriptBlock.LanguageMode = entry.ScriptBlock.LanguageMode ?? PSLanguageMode.FullLanguage; } /// <summary> /// Gets a flattened view of the functions that are visible using /// the current scope as a reference and filtering the functions in /// the other scopes based on the scoping rules. /// </summary> /// <returns> /// An IDictionary representing the visible functions. /// </returns> internal IDictionary GetFunctionTable() { SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); Dictionary<string, FunctionInfo> result = new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase); foreach (SessionStateScope scope in scopeEnumerator) { foreach (FunctionInfo entry in scope.FunctionTable.Values) { if (!result.ContainsKey(entry.Name)) { result.Add(entry.Name, entry); } } } return result; } /// <summary> /// Gets an IEnumerable for the function table for a given scope. /// </summary> /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> internal IDictionary<string, FunctionInfo> GetFunctionTableAtScope(string scopeID) { Dictionary<string, FunctionInfo> result = new Dictionary<string, FunctionInfo>(StringComparer.OrdinalIgnoreCase); SessionStateScope scope = GetScopeByID(scopeID); foreach (FunctionInfo entry in scope.FunctionTable.Values) { // Make sure the function/filter isn't private or if it is that the current // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || scope == _currentScope) { result.Add(entry.Name, entry); } } return result; } /// <summary> /// List of functions/filters to export from this session state object... /// </summary> internal List<FunctionInfo> ExportedFunctions { get; } = new List<FunctionInfo>(); internal bool UseExportList { get; set; } = false; /// <summary> /// Set to true when module functions are being explicitly exported using Export-ModuleMember. /// </summary> internal bool FunctionsExported { get; set; } /// <summary> /// Set to true when any processed module functions are being explicitly exported using '*' wildcard. /// </summary> internal bool FunctionsExportedWithWildcard { get { return _functionsExportedWithWildcard; } set { Dbg.Assert((value == true), "This property should never be set/reset to false"); if (value == true) { _functionsExportedWithWildcard = value; } } } private bool _functionsExportedWithWildcard; /// <summary> /// Set to true if module loading is performed under a manifest that explicitly exports functions (no wildcards) /// </summary> internal bool ManifestWithExplicitFunctionExport { get; set; } /// <summary> /// Get a functions out of session state. /// </summary> /// <param name="name"> /// name of function to look up /// </param> /// <param name="origin"> /// Origin of the command that called this API... /// </param> /// <returns> /// The value of the specified function. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal FunctionInfo GetFunction(string name, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } FunctionInfo result = null; FunctionLookupPath lookupPath = new FunctionLookupPath(name); FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher(this, lookupPath, origin); if (searcher.MoveNext()) { result = ((IEnumerator<FunctionInfo>)searcher).Current; } return (IsFunctionVisibleInDebugger(result, origin)) ? result : null; } private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin origin) { // Ensure the returned function item is not exposed across language boundaries when in // a debugger breakpoint or nested prompt. // A debugger breakpoint/nested prompt has access to all current scoped functions. // This includes both running commands from the prompt or via a debugger Action scriptblock. // Early out. // Always allow built-in functions needed for command line debugging. if ((this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) || (fnInfo == null) || (fnInfo.Name.Equals("prompt", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("Clear-Host", StringComparison.Ordinal))) { return true; } // Check both InNestedPrompt and Debugger.InBreakpoint to ensure we don't miss a case. // Function is not visible if function and context language modes are different. var runspace = this.ExecutionContext.CurrentRunspace; if ((runspace != null) && (runspace.InNestedPrompt || (runspace.Debugger?.InBreakpoint == true)) && (fnInfo.DefiningLanguageMode.HasValue && (fnInfo.DefiningLanguageMode != this.ExecutionContext.LanguageMode))) { return false; } return true; } /// <summary> /// Get a functions out of session state. /// </summary> /// <param name="name"> /// name of function to look up /// </param> /// <returns> /// The value of the specified function. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal FunctionInfo GetFunction(string name) { return GetFunction(name, CommandOrigin.Internal); } private IEnumerable<string> GetFunctionAliases(IParameterMetadataProvider ipmp) { if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; var attributes = ipmp.Body.ParamBlock.Attributes; foreach (var attributeAst in attributes) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); if (attributeType == typeof(AliasAttribute)) { var cvv = new ConstantValueVisitor { AttributeArgument = true }; for (int i = 0; i < attributeAst.PositionalArguments.Count; i++) { yield return Compiler._attrArgToStringConverter.Target(Compiler._attrArgToStringConverter, attributeAst.PositionalArguments[i].Accept(cvv)); } } } } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunctionRaw( string name, ScriptBlock function, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); var functionInfo = searcher.InitialScope.SetFunction(name, function, null, options, false, origin, ExecutionContext); foreach (var aliasName in GetFunctionAliases(function.Ast as IParameterMetadataProvider)) { searcher.InitialScope.SetAliasValue(aliasName, name, ExecutionContext, false, origin); } return functionInfo; } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin) { return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, null); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, string helpFile) { return SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext, helpFile, false); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, ExecutionContext context, string helpFile) { return SetFunction(name, function, originalFunction, options, force, origin, context, helpFile, false); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="options"> /// The options to set on the function. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// Origin of the caller of this API /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <param name="isPreValidated"> /// Set to true if it is a regular function (meaning, we do not need to check if the script contains JobDefinition Attribute and then process it) /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, ExecutionContext context, string helpFile, bool isPreValidated) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); return searcher.InitialScope.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile); } /// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// The origin of the caller /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); FunctionInfo result = null; SessionStateScope scope = searcher.InitialScope; if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; name = searcher.Name; if (path.IsPrivate) { // Need to add the Private flag FunctionInfo existingFunction = scope.GetFunction(name); options |= existingFunction.Options; result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } else { if (path.IsPrivate) { result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } return result; } /// <summary> /// Set a function in the current scope of session state. /// /// BUGBUG: this overload is preserved because a lot of tests use reflection to /// call it. The tests should be fixed and this API eventually removed. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction(string name, ScriptBlock function, bool force) { return SetFunction(name, function, null, force, CommandOrigin.Internal); } /// <summary> /// Removes a function from the function table. /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="origin"> /// THe origin of the caller of this API /// </param> /// <param name="force"> /// If true, the function is removed even if it is ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } // Use the scope enumerator to find an existing function SessionStateScope scope = _currentScope; FunctionLookupPath path = new FunctionLookupPath(name); FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; } scope.RemoveFunction(name, force); } /// <summary> /// Removes a function from the function table. /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="force"> /// If true, the function is removed even if it is ReadOnly. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, bool force) { RemoveFunction(name, force, CommandOrigin.Internal); } /// <summary> /// Removes a function from the function table /// if the function was imported from the given module. /// /// BUGBUG: This is only used by the implicit remoting functions... /// </summary> /// <param name="name"> /// The name of the function to remove. /// </param> /// <param name="module"> /// Module the function might be imported from. /// </param> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is constant. /// </exception> internal void RemoveFunction(string name, PSModuleInfo module) { Dbg.Assert(module != null, "Caller should verify that module parameter is not null"); FunctionInfo func = GetFunction(name) as FunctionInfo; if (func != null && func.ScriptBlock != null && func.ScriptBlock.File != null && func.ScriptBlock.File.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { RemoveFunction(name, true); } } #endregion Functions } }
// 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.Data.SqlClient; using System.Runtime.InteropServices; namespace System.Data.SqlClient { internal static class SNINativeMethodWrapper { private const string SNI = "sni.dll"; private static int s_sniMaxComposedSpnLength = -1; private const int SniOpenTimeOut = -1; // infinite [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void SqlAsyncCallbackDelegate(IntPtr m_ConsKey, IntPtr pPacket, uint dwError); internal static int SniMaxComposedSpnLength { get { if (s_sniMaxComposedSpnLength == -1) { s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength()); } return s_sniMaxComposedSpnLength; } } #region Structs\Enums [StructLayout(LayoutKind.Sequential)] internal struct ConsumerInfo { internal int defaultBufferSize; internal SqlAsyncCallbackDelegate readDelegate; internal SqlAsyncCallbackDelegate writeDelegate; internal IntPtr key; } internal enum ConsumerNumber { SNI_Consumer_SNI, SNI_Consumer_SSB, SNI_Consumer_PacketIsReleased, SNI_Consumer_Invalid, } internal enum IOType { READ, WRITE, } internal enum PrefixEnum { UNKNOWN_PREFIX, SM_PREFIX, TCP_PREFIX, NP_PREFIX, VIA_PREFIX, INVALID_PREFIX, } internal enum ProviderEnum { HTTP_PROV, NP_PROV, SESSION_PROV, SIGN_PROV, SM_PROV, SMUX_PROV, SSL_PROV, TCP_PROV, VIA_PROV, MAX_PROVS, INVALID_PROV, } internal enum QTypes { SNI_QUERY_CONN_INFO, SNI_QUERY_CONN_BUFSIZE, SNI_QUERY_CONN_KEY, SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, SNI_QUERY_SERVER_ENCRYPT_POSSIBLE, SNI_QUERY_CERTIFICATE, SNI_QUERY_LOCALDB_HMODULE, SNI_QUERY_CONN_ENCRYPT, SNI_QUERY_CONN_PROVIDERNUM, SNI_QUERY_CONN_CONNID, SNI_QUERY_CONN_PARENTCONNID, SNI_QUERY_CONN_SECPKG, SNI_QUERY_CONN_NETPACKETSIZE, SNI_QUERY_CONN_NODENUM, SNI_QUERY_CONN_PACKETSRECD, SNI_QUERY_CONN_PACKETSSENT, SNI_QUERY_CONN_PEERADDR, SNI_QUERY_CONN_PEERPORT, SNI_QUERY_CONN_LASTREADTIME, SNI_QUERY_CONN_LASTWRITETIME, SNI_QUERY_CONN_CONSUMER_ID, SNI_QUERY_CONN_CONNECTTIME, SNI_QUERY_CONN_HTTPENDPOINT, SNI_QUERY_CONN_LOCALADDR, SNI_QUERY_CONN_LOCALPORT, SNI_QUERY_CONN_SSLHANDSHAKESTATE, SNI_QUERY_CONN_SOBUFAUTOTUNING, SNI_QUERY_CONN_SECPKGNAME, SNI_QUERY_CONN_SECPKGMUTUALAUTH, SNI_QUERY_CONN_CONSUMERCONNID, SNI_QUERY_CONN_SNIUCI, SNI_QUERY_CONN_SUPPORTS_EXTENDED_PROTECTION, SNI_QUERY_CONN_CHANNEL_PROVIDES_AUTHENTICATION_CONTEXT, SNI_QUERY_CONN_PEERID, SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, } internal enum TransparentNetworkResolutionMode : byte { DisabledMode = 0, SequentialMode, ParallelMode }; [StructLayout(LayoutKind.Sequential)] private struct Sni_Consumer_Info { public int DefaultUserDataLength; public IntPtr ConsumerKey; public IntPtr fnReadComp; public IntPtr fnWriteComp; public IntPtr fnTrace; public IntPtr fnAcceptComp; public uint dwNumProts; public IntPtr rgListenInfo; public IntPtr NodeAffinity; } [StructLayout(LayoutKind.Sequential)] private unsafe struct SNI_CLIENT_CONSUMER_INFO { public Sni_Consumer_Info ConsumerInfo; [MarshalAs(UnmanagedType.LPWStr)] public string wszConnectionString; public PrefixEnum networkLibrary; public byte* szSPN; public uint cchSPN; public byte* szInstanceName; public uint cchInstanceName; [MarshalAs(UnmanagedType.Bool)] public bool fOverrideLastConnectCache; [MarshalAs(UnmanagedType.Bool)] public bool fSynchronousConnection; public int timeout; [MarshalAs(UnmanagedType.Bool)] public bool fParallel; public TransparentNetworkResolutionMode transparentNetworkResolution; public int totalTimeout; public bool isAzureSqlServerEndpoint; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SNI_Error { internal ProviderEnum provider; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 261)] internal string errorMessage; internal uint nativeError; internal uint sniError; [MarshalAs(UnmanagedType.LPWStr)] internal string fileName; [MarshalAs(UnmanagedType.LPWStr)] internal string function; internal uint lineNumber; } internal enum SniSpecialErrors : uint { LocalDBErrorCode = 50, // multi-subnet-failover specific error codes MultiSubnetFailoverWithMoreThan64IPs = 47, MultiSubnetFailoverWithInstanceSpecified = 48, MultiSubnetFailoverWithNonTcpProtocol = 49, // max error code value MaxErrorValue = 50157 } #endregion #region DLL Imports [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIAddProviderWrapper")] internal static extern uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICheckConnectionWrapper")] internal static extern uint SNICheckConnection([In] SNIHandle pConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICloseWrapper")] internal static extern uint SNIClose(IntPtr pConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern void SNIGetLastError(out SNI_Error pErrorStruct); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern void SNIPacketRelease(IntPtr pPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIPacketResetWrapper")] internal static extern void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIQueryInfo(QTypes QType, ref uint pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIQueryInfo(QTypes QType, ref IntPtr pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIReadAsyncWrapper")] internal static extern uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIRemoveProviderWrapper")] internal static extern uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNISecInitPackage(ref uint pcbMaxToken); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNISetInfoWrapper")] internal static extern uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint SNITerminate(); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIWaitForSSLHandshakeToCompleteWrapper")] internal static extern uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint GetSniMaxComposedSpnLength(); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIInitialize([In] IntPtr pmo); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIOpenSyncExWrapper(ref SNI_CLIENT_CONSUMER_INFO pClientConsumerInfo, out IntPtr ppConn); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIOpenWrapper( [In] ref Sni_Consumer_Info pConsumerInfo, [MarshalAs(UnmanagedType.LPStr)] string szConnect, [In] SNIHandle pConn, out IntPtr ppConn, [MarshalAs(UnmanagedType.Bool)] bool fSync); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IOType IOType); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static unsafe extern uint SNISecGenClientContextWrapper( [In] SNIHandle pConn, [In, Out] byte[] pIn, uint cbIn, [In, Out] byte[] pOut, [In] ref uint pcbOut, [MarshalAsAttribute(UnmanagedType.Bool)] out bool pfDone, byte* szServerInfo, uint cbServerInfo, [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszUserName, [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszPassword); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket); [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket); #endregion internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId); } internal static uint SNIInitialize() { return SNIInitialize(IntPtr.Zero); } internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync) { // initialize consumer info for MARS Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info(); MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync); } internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel) { fixed (byte* pin_instanceName = &instanceName[0]) { SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = new SNI_CLIENT_CONSUMER_INFO(); // initialize client ConsumerInfo part first MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo); clientConsumerInfo.wszConnectionString = constring; clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX; clientConsumerInfo.szInstanceName = pin_instanceName; clientConsumerInfo.cchInstanceName = (uint)instanceName.Length; clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache; clientConsumerInfo.fSynchronousConnection = fSync; clientConsumerInfo.timeout = timeout; clientConsumerInfo.fParallel = fParallel; if (spnBuffer != null) { fixed (byte* pin_spnBuffer = &spnBuffer[0]) { clientConsumerInfo.szSPN = pin_spnBuffer; clientConsumerInfo.cchSPN = (uint)spnBuffer.Length; return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } else { // else leave szSPN null (SQL Auth) return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } } internal static void SNIPacketAllocate(SafeHandle pConn, IOType IOType, ref IntPtr pPacket) { pPacket = SNIPacketAllocateWrapper(pConn, IOType); } internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) { return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize); } internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length) { fixed (byte* pin_data = &data[0]) { SNIPacketSetData(packet, pin_data, (uint)length); } } internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName) { fixed (byte* pin_serverUserName = &serverUserName[0]) { bool local_fDone; return SNISecGenClientContextWrapper( pConnectionObject, inBuff, receivedLength, OutBuff, ref sendLength, out local_fDone, pin_serverUserName, (uint)(serverUserName == null ? 0 : serverUserName.Length), null, null); } } internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) { if (sync) { return SNIWriteSyncOverAsync(pConn, packet); } else { return SNIWriteAsyncWrapper(pConn, packet); } } private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; } } } namespace System.Data { internal static class SafeNativeMethods { [DllImport("api-ms-win-core-libraryloader-l1-1-0.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] internal static extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName); } } namespace System.Data { internal static class Win32NativeMethods { internal static bool IsTokenRestrictedWrapper(IntPtr token) { bool isRestricted; uint result = SNINativeMethodWrapper.UnmanagedIsTokenRestricted(token, out isRestricted); if (result != 0) { Marshal.ThrowExceptionForHR(unchecked((int)result)); } return isRestricted; } } }
// 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; namespace System.Globalization { internal static class TimeSpanFormat { private static unsafe void AppendNonNegativeInt32(StringBuilder sb, int n, int digits) { Debug.Assert(n >= 0); uint value = (uint)n; const int MaxUInt32Digits = 10; char* buffer = stackalloc char[MaxUInt32Digits]; int index = 0; do { uint div = value / 10; buffer[index++] = (char)(value - (div * 10) + '0'); value = div; } while (value != 0); Debug.Assert(index <= MaxUInt32Digits); for (int i = digits - index; i > 0; --i) sb.Append('0'); for (int i = index - 1; i >= 0; --i) sb.Append(buffer[i]); } internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false); internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true); internal enum Pattern { None = 0, Minimum = 1, Full = 2, } /// <summary>Main method called from TimeSpan.ToString.</summary> internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) => StringBuilderCache.GetStringAndRelease(FormatToBuilder(value, format, formatProvider)); /// <summary>Main method called from TimeSpan.TryFormat.</summary> internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider formatProvider) { StringBuilder sb = FormatToBuilder(value, format, formatProvider); if (sb.Length <= destination.Length) { charsWritten = sb.Length; sb.CopyTo(0, destination, sb.Length); StringBuilderCache.Release(sb); return true; } else { StringBuilderCache.Release(sb); charsWritten = 0; return false; } } private static StringBuilder FormatToBuilder(TimeSpan value, ReadOnlySpan<char> format, IFormatProvider formatProvider) { if (format.Length == 0) { format = "c"; } // Standard formats if (format.Length == 1) { char f = format[0]; switch (f) { case 'c': case 't': case 'T': return FormatStandard( value, isInvariant: true, format: format, pattern: Pattern.Minimum); case 'g': case 'G': DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider); return FormatStandard( value, isInvariant: false, format: value.Ticks < 0 ? dtfi.FullTimeSpanNegativePattern : dtfi.FullTimeSpanPositivePattern, pattern: f == 'g' ? Pattern.Minimum : Pattern.Full); default: throw new FormatException(SR.Format_InvalidString); } } // Custom formats return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider), result: null); } /// <summary>Format the TimeSpan instance using the specified format.</summary> private static StringBuilder FormatStandard(TimeSpan value, bool isInvariant, ReadOnlySpan<char> format, Pattern pattern) { StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); int day = (int)(value.Ticks / TimeSpan.TicksPerDay); long time = value.Ticks % TimeSpan.TicksPerDay; if (value.Ticks < 0) { day = -day; time = -time; } int hours = (int)(time / TimeSpan.TicksPerHour % 24); int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); int fraction = (int)(time % TimeSpan.TicksPerSecond); FormatLiterals literal; if (isInvariant) { literal = value.Ticks < 0 ? NegativeInvariantFormatLiterals : PositiveInvariantFormatLiterals; } else { literal = new FormatLiterals(); literal.Init(format, pattern == Pattern.Full); } if (fraction != 0) { // truncate the partial second to the specified length fraction = (int)(fraction / TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - literal.ff)); } // Pattern.Full: [-]dd.hh:mm:ss.fffffff // Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff] sb.Append(literal.Start); // [-] if (pattern == Pattern.Full || day != 0) { sb.Append(day); // [dd] sb.Append(literal.DayHourSep); // [.] } // AppendNonNegativeInt32(sb, hours, literal.hh); // hh sb.Append(literal.HourMinuteSep); // : AppendNonNegativeInt32(sb, minutes, literal.mm); // mm sb.Append(literal.MinuteSecondSep); // : AppendNonNegativeInt32(sb, seconds, literal.ss); // ss if (!isInvariant && pattern == Pattern.Minimum) { int effectiveDigits = literal.ff; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction = fraction / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { sb.Append(literal.SecondFractionSep); // [.FFFFFFF] sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } } else if (pattern == Pattern.Full || fraction != 0) { sb.Append(literal.SecondFractionSep); // [.] AppendNonNegativeInt32(sb, fraction, literal.ff); // [fffffff] } sb.Append(literal.End); return sb; } /// <summary>Format the TimeSpan instance using the specified format.</summary> private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, StringBuilder result) { Debug.Assert(dtfi != null); bool resultBuilderIsPooled = false; if (result == null) { result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); resultBuilderIsPooled = true; } int day = (int)(value.Ticks / TimeSpan.TicksPerDay); long time = value.Ticks % TimeSpan.TicksPerDay; if (value.Ticks < 0) { day = -day; time = -time; } int hours = (int)(time / TimeSpan.TicksPerHour % 24); int minutes = (int)(time / TimeSpan.TicksPerMinute % 60); int seconds = (int)(time / TimeSpan.TicksPerSecond % 60); int fraction = (int)(time % TimeSpan.TicksPerSecond); long tmp = 0; int i = 0; int tokenLen; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'h': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, hours, tokenLen); break; case 'm': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, minutes, tokenLen); break; case 's': tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 2) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, seconds, tokenLen); break; case 'f': // // The fraction of a second in single-digit precision. The remaining digits are truncated. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) { goto default; // to release the builder and throw } tmp = fraction; tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen); result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture)); break; case 'F': // // Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits) { goto default; // to release the builder and throw } tmp = fraction; tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen); int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (tmp % 10 == 0) { tmp = tmp / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } break; case 'd': // // tokenLen == 1 : Day as digits with no leading zero. // tokenLen == 2+: Day as digits with leading zero for single-digit days. // tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch); if (tokenLen > 8) { goto default; // to release the builder and throw } DateTimeFormat.FormatDigits(result, day, tokenLen, true); break; case '\'': case '\"': tokenLen = DateTimeFormat.ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day // Most of the cases, "%" can be ignored. nextChar = DateTimeFormat.ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { char nextCharChar = (char)nextChar; StringBuilder origStringBuilder = FormatCustomized(value, ReadOnlySpan<char>.DangerousCreate(null, ref nextCharChar, 1), dtfi, result); Debug.Assert(ReferenceEquals(origStringBuilder, result)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // goto default; // to release the builder and throw } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For example, "\d" will insert the character 'd' into the string. // nextChar = DateTimeFormat.ParseNextChar(format, i); if (nextChar >= 0) { result.Append(((char)nextChar)); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // goto default; // to release the builder and throw } break; default: // Invalid format string if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } i += tokenLen; } return result; } internal struct FormatLiterals { internal string AppCompatLiteral; internal int dd; internal int hh; internal int mm; internal int ss; internal int ff; private string[] _literals; internal string Start => _literals[0]; internal string DayHourSep => _literals[1]; internal string HourMinuteSep => _literals[2]; internal string MinuteSecondSep => _literals[3]; internal string SecondFractionSep => _literals[4]; internal string End => _literals[5]; /* factory method for static invariant FormatLiterals */ internal static FormatLiterals InitInvariant(bool isNegative) { FormatLiterals x = new FormatLiterals(); x._literals = new string[6]; x._literals[0] = isNegative ? "-" : string.Empty; x._literals[1] = "."; x._literals[2] = ":"; x._literals[3] = ":"; x._literals[4] = "."; x._literals[5] = string.Empty; x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep; x.dd = 2; x.hh = 2; x.mm = 2; x.ss = 2; x.ff = DateTimeFormat.MaxSecondsFractionDigits; return x; } // For the "v1" TimeSpan localized patterns, the data is simply literal field separators with // the constants guaranteed to include DHMSF ordered greatest to least significant. // Once the data becomes more complex than this we will need to write a proper tokenizer for // parsing and formatting internal void Init(ReadOnlySpan<char> format, bool useInvariantFieldLengths) { dd = hh = mm = ss = ff = 0; _literals = new string[6]; for (int i = 0; i < _literals.Length; i++) { _literals[i] = string.Empty; } StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity); bool inQuote = false; char quote = '\''; int field = 0; for (int i = 0; i < format.Length; i++) { switch (format[i]) { case '\'': case '\"': if (inQuote && (quote == format[i])) { /* we were in a quote and found a matching exit quote, so we are outside a quote now */ if (field >= 0 && field <= 5) { _literals[field] = sb.ToString(); sb.Length = 0; inQuote = false; } else { Debug.Fail($"Unexpected field value: {field}"); return; // how did we get here? } } else if (!inQuote) { /* we are at the start of a new quote block */ quote = format[i]; inQuote = true; } else { /* we were in a quote and saw the other type of quote character, so we are still in a quote */ } break; case '%': Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); goto default; case '\\': if (!inQuote) { i++; /* skip next character that is escaped by this backslash or percent sign */ break; } goto default; case 'd': if (!inQuote) { Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 1; // DayHourSep dd++; } break; case 'h': if (!inQuote) { Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 2; // HourMinuteSep hh++; } break; case 'm': if (!inQuote) { Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 3; // MinuteSecondSep mm++; } break; case 's': if (!inQuote) { Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 4; // SecondFractionSep ss++; } break; case 'f': case 'F': if (!inQuote) { Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 5; // End ff++; } break; default: sb.Append(format[i]); break; } } Debug.Assert(field == 5); AppCompatLiteral = MinuteSecondSep + SecondFractionSep; Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); if (useInvariantFieldLengths) { dd = 2; hh = 2; mm = 2; ss = 2; ff = DateTimeFormat.MaxSecondsFractionDigits; } else { if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation. if (hh < 1 || hh > 2) hh = 2; if (mm < 1 || mm > 2) mm = 2; if (ss < 1 || ss > 2) ss = 2; if (ff < 1 || ff > 7) ff = 7; } StringBuilderCache.Release(sb); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcsv = Google.Cloud.ServiceDirectory.V1; using sys = System; namespace Google.Cloud.ServiceDirectory.V1 { /// <summary>Resource name for the <c>Namespace</c> resource.</summary> public sealed partial class NamespaceName : gax::IResourceName, sys::IEquatable<NamespaceName> { /// <summary>The possible contents of <see cref="NamespaceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </summary> ProjectLocationNamespace = 1, } private static gax::PathTemplate s_projectLocationNamespace = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}"); /// <summary>Creates a <see cref="NamespaceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="NamespaceName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static NamespaceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new NamespaceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="NamespaceName"/> with the pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="NamespaceName"/> constructed from the provided ids.</returns> public static NamespaceName FromProjectLocationNamespace(string projectId, string locationId, string namespaceId) => new NamespaceName(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </returns> public static string Format(string projectId, string locationId, string namespaceId) => FormatProjectLocationNamespace(projectId, locationId, namespaceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </returns> public static string FormatProjectLocationNamespace(string projectId, string locationId, string namespaceId) => s_projectLocationNamespace.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))); /// <summary>Parses the given resource name string into a new <see cref="NamespaceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description> /// </item> /// </list> /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="NamespaceName"/> if successful.</returns> public static NamespaceName Parse(string namespaceName) => Parse(namespaceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="NamespaceName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="NamespaceName"/> if successful.</returns> public static NamespaceName Parse(string namespaceName, bool allowUnparsed) => TryParse(namespaceName, allowUnparsed, out NamespaceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NamespaceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description> /// </item> /// </list> /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="NamespaceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string namespaceName, out NamespaceName result) => TryParse(namespaceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NamespaceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/namespaces/{namespace}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="NamespaceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string namespaceName, bool allowUnparsed, out NamespaceName result) { gax::GaxPreconditions.CheckNotNull(namespaceName, nameof(namespaceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationNamespace.TryParseName(namespaceName, out resourceName)) { result = FromProjectLocationNamespace(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(namespaceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private NamespaceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; NamespaceId = namespaceId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="NamespaceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> public NamespaceName(string projectId, string locationId, string namespaceId) : this(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string NamespaceId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationNamespace: return s_projectLocationNamespace.Expand(ProjectId, LocationId, NamespaceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as NamespaceName); /// <inheritdoc/> public bool Equals(NamespaceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(NamespaceName a, NamespaceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(NamespaceName a, NamespaceName b) => !(a == b); } public partial class Namespace { /// <summary> /// <see cref="gcsv::NamespaceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::NamespaceName NamespaceName { get => string.IsNullOrEmpty(Name) ? null : gcsv::NamespaceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//----------------------------------------------------------------------- // <copyright file="Frame.cs" company="Google"> // // 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore { using System; using System.Collections.Generic; using GoogleARCoreInternal; using UnityEngine; /// <summary> /// Provides a snapshot of the state of ARCore at a specific timestamp associated with the current frame. Frame /// holds information about ARCore's state including tracking status, the pose of the camera relative to the world, /// estimated lighting parameters, and information on updates to objects (like Planes or Point Clouds) that ARCore /// is tracking. /// </summary> public class Frame { //// @cond EXCLUDE_FROM_DOXYGEN private static List<TrackableHit> s_TmpTrackableHitList = new List<TrackableHit>(); //// @endcond /// <summary> /// Gets the pose of the ARCore device for the frame in Unity world coordinates. /// </summary> public static Pose Pose { get { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return Pose.identity; } var cameraHandle = nativeSession.FrameApi.AcquireCamera(); Pose result = nativeSession.CameraApi.GetPose(cameraHandle); nativeSession.CameraApi.Release(cameraHandle); return result; } } /// <summary> /// Gets the current light estimate for this frame. /// </summary> public static LightEstimate LightEstimate { get { // TODO (b/73256094): Remove isTracking when fixed. var nativeSession = LifecycleManager.Instance.NativeSession; var isTracking = LifecycleManager.Instance.SessionStatus == SessionStatus.Tracking; if (nativeSession == null || !isTracking) { return new LightEstimate(LightEstimateState.NotValid, 0.0f); } return nativeSession.FrameApi.GetLightEstimate(); } } /// <summary> /// Performs a raycast against physical objects being tracked by ARCore. /// Output the closest hit from the camera. /// Note that the Unity's screen coordinate (0, 0) /// starts from bottom left. /// </summary> /// <param name="x">Horizontal touch position in Unity's screen coordiante.</param> /// <param name="y">Vertical touch position in Unity's screen coordiante.</param> /// <param name="filter">A filter bitmask where each {@link TrackableHitFlag} which is set represents a category /// of raycast hits the method call should consider valid.</param> /// <param name="hitResult">A {@link TrackableHit} that will be set if the raycast is successful.</param> /// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns> public static bool Raycast(float x, float y, TrackableHitFlags filter, out TrackableHit hitResult) { hitResult = new TrackableHit(); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return false; } // Note that the Unity's screen coordinate (0, 0) starts from bottom left. bool foundHit = nativeSession.HitTestApi.Raycast(nativeSession.FrameHandle, x, Screen.height - y, filter, s_TmpTrackableHitList, true); if (foundHit && s_TmpTrackableHitList.Count != 0) { hitResult = s_TmpTrackableHitList[0]; } return foundHit; } /// <summary> /// Performs a raycast against physical objects being tracked by ARCore. /// Output all hits from the camera. /// Note that the Unity's screen coordinate (0, 0) /// starts from bottom left. /// </summary> /// <param name="x">Horizontal touch position in Unity's screen coordiante.</param> /// <param name="y">Vertical touch position in Unity's screen coordiante.</param> /// <param name="filter">A filter bitmask where each {@link TrackableHitFlag} which is set represents a category /// of raycast hits the method call should consider valid.</param> /// <param name="hitResults">A list of {@link TrackableHit} that will be set if the raycast is successful.</param> /// <returns><c>true</c> if the raycast had a hit, otherwise <c>false</c>.</returns> public static bool RaycastAll(float x, float y, TrackableHitFlags filter, List<TrackableHit> hitResults) { hitResults.Clear(); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return false; } return nativeSession.HitTestApi.Raycast(nativeSession.FrameHandle, x, Screen.height - y, filter, hitResults, true); } /// <summary> /// Container for state related to the ARCore camera image metadata for the Frame. /// </summary> public static class CameraMetadata { /// <summary> /// Get camera image metadata value. The querying value type needs to match the returned type. /// The type could be checked in CameraMetadata.cs. /// </summary> /// <param name="metadataTag">Metadata type.</param> /// <param name="outMetadataList">Result list of the requested values.</param> /// <returns><c>true</c> if getting metadata value successfully, otherwise <c>false</c>.</returns> public static bool TryGetValues(CameraMetadataTag metadataTag, List<CameraMetadataValue> outMetadataList) { outMetadataList.Clear(); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return false; } var metadataHandle = nativeSession.FrameApi.AcquireImageMetadata(); var isSuccess = nativeSession.CameraMetadataApi.TryGetValues(metadataHandle, metadataTag, outMetadataList); nativeSession.CameraMetadataApi.Release(metadataHandle); return isSuccess; } /// <summary> /// Get all available tags in the current frame's metadata. /// </summary> /// <param name="outMetadataTags">Result list of the tags.</param> /// <returns><c>true</c> if getting tags successfully, otherwise <c>false</c>.</returns> public static bool GetAllCameraMetadataTags(List<CameraMetadataTag> outMetadataTags) { outMetadataTags.Clear(); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return false; } var metadataHandle = nativeSession.FrameApi.AcquireImageMetadata(); var isSuccess = nativeSession.CameraMetadataApi.GetAllCameraMetadataTags(metadataHandle, outMetadataTags); nativeSession.CameraMetadataApi.Release(metadataHandle); return isSuccess; } } /// <summary> /// Container for state related to the ARCore point cloud for the Frame. /// </summary> public static class PointCloud { /// <summary> /// Gets a value indicating whether new point cloud data became available in the current frame. /// </summary> /// <returns><c>true</c> if new point cloud data became available in the current frame, otherwise /// <c>false</c>.</returns> public static bool IsUpdatedThisFrame { get { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return false; } return nativeSession.IsPointCloudNew; } } /// <summary> /// Gets the count of point cloud points in the frame. /// </summary> public static int PointCount { get { // TODO (b/73256094): Remove isTracking when fixed. var nativeSession = LifecycleManager.Instance.NativeSession; var isTracking = LifecycleManager.Instance.SessionStatus == SessionStatus.Tracking; if (nativeSession == null || !isTracking) { return 0; } return nativeSession.PointCloudApi.GetNumberOfPoints(nativeSession.PointCloudHandle); } } /// <summary> /// Gets a point from the point cloud collection at an index. /// </summary> /// <param name="index">The index of the point cloud point to get.</param> /// <returns>The point from the point cloud at <c>index</c>.</returns> public static Vector3 GetPoint(int index) { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return Vector3.zero; } return nativeSession.PointCloudApi.GetPoint(nativeSession.PointCloudHandle, index); } /// <summary> /// Copies the point cloud for a frame into a supplied list reference. /// </summary> /// <param name="points">A list that will be filled with point cloud points by this method call.</param> public static void CopyPoints(List<Vector4> points) { points.Clear(); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return; } nativeSession.PointCloudApi.CopyPoints(nativeSession.PointCloudHandle, points); } } /// <summary> /// Container for state related to the ARCore camera for the frame. /// </summary> public static class CameraImage { /// <summary> /// Gets a texture used from the device's rear camera. /// </summary> public static Texture Texture { get { return LifecycleManager.Instance.BackgroundTexture; } } /// <summary> /// Gets a ApiDisplayUvCoords to properly display the camera texture. /// </summary> public static ApiDisplayUvCoords DisplayUvCoords { get { ApiDisplayUvCoords displayUvCoords = new ApiDisplayUvCoords(new Vector2(0, 1), new Vector2(1, 1), new Vector2(0, 0), new Vector2(1, 0)); var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null || Texture == null) { return displayUvCoords; } nativeSession.FrameApi.TransformDisplayUvCoords(ref displayUvCoords); return displayUvCoords; } } /// <summary> /// Gets the projection matrix for the frame. /// </summary> /// <param name="nearClipping">The near clipping plane for the projection matrix.</param> /// <param name="farClipping">The far clipping plane for the projection matrix.</param> /// <returns>The projection matrix for the frame.</returns> public static Matrix4x4 GetCameraProjectionMatrix(float nearClipping, float farClipping) { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null || Texture == null) { return Matrix4x4.identity; } var cameraHandle = nativeSession.FrameApi.AcquireCamera(); var result = nativeSession.CameraApi.GetProjectionMatrix(cameraHandle, nearClipping, farClipping); nativeSession.CameraApi.Release(cameraHandle); return result; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ElasticTranscoder.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ElasticTranscoder.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for JobOutput Object /// </summary> public class JobOutputUnmarshaller : IUnmarshaller<JobOutput, XmlUnmarshallerContext>, IUnmarshaller<JobOutput, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> JobOutput IUnmarshaller<JobOutput, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public JobOutput Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; JobOutput unmarshalledObject = new JobOutput(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("AlbumArt", targetDepth)) { var unmarshaller = JobAlbumArtUnmarshaller.Instance; unmarshalledObject.AlbumArt = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AppliedColorSpaceConversion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AppliedColorSpaceConversion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Captions", targetDepth)) { var unmarshaller = CaptionsUnmarshaller.Instance; unmarshalledObject.Captions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Composition", targetDepth)) { var unmarshaller = new ListUnmarshaller<Clip, ClipUnmarshaller>(ClipUnmarshaller.Instance); unmarshalledObject.Composition = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Duration", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.Duration = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DurationMillis", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.DurationMillis = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Encryption", targetDepth)) { var unmarshaller = EncryptionUnmarshaller.Instance; unmarshalledObject.Encryption = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FileSize", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.FileSize = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FrameRate", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.FrameRate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Height", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Height = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Key", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Key = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PresetId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.PresetId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Rotate", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Rotate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SegmentDuration", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SegmentDuration = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StatusDetail", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.StatusDetail = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ThumbnailEncryption", targetDepth)) { var unmarshaller = EncryptionUnmarshaller.Instance; unmarshalledObject.ThumbnailEncryption = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ThumbnailPattern", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ThumbnailPattern = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Watermarks", targetDepth)) { var unmarshaller = new ListUnmarshaller<JobWatermark, JobWatermarkUnmarshaller>(JobWatermarkUnmarshaller.Instance); unmarshalledObject.Watermarks = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Width", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Width = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static JobOutputUnmarshaller _instance = new JobOutputUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static JobOutputUnmarshaller Instance { get { return _instance; } } } }
using Shouldly; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using System; using System.Linq; using Xunit; namespace StructureMap.Testing.Graph { public class PluginFamilyTester { public class TheGateway : IGateway { #region IGateway Members public string WhoAmI { get { throw new NotImplementedException(); } } public void DoSomething() { throw new NotImplementedException(); } #endregion IGateway Members } public class DataTableProvider : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } [Fact] public void throw_exception_if_instance_is_not_compatible_with_PluginType_in_AddInstance() { var family = new PluginFamily(typeof(IGateway)); Exception<ArgumentOutOfRangeException>.ShouldBeThrownBy( () => { family.AddInstance(new SmartInstance<ColorRule>()); }); } [Fact] public void If_PluginFamily_only_has_one_instance_make_that_the_default() { var family = new PluginFamily(typeof(IGateway)); var theInstanceKey = "the default"; var instance = new ConfiguredInstance(typeof(TheGateway)).Named(theInstanceKey); family.AddInstance(instance); family.GetDefaultInstance().ShouldBeTheSameAs(instance); } public class LoggingFamilyAttribute : StructureMapAttribute { public static bool Called { get; set; } public override void Alter(PluginFamily family) { Called = true; } } [LoggingFamily] public class FamilyGateway { } [LoggingFamily] public interface IFamilyInterface { } [Fact] public void PluginFamily_uses_family_attribute_when_present_on_class() { LoggingFamilyAttribute.Called = false; var testFamily = typeof(FamilyGateway); var family = new PluginFamily(testFamily); LoggingFamilyAttribute.Called.ShouldBeTrue(); } [Fact] public void PluginFamily_uses_family_attribute_when_present_on_interface() { LoggingFamilyAttribute.Called = false; var testFamily = typeof(IFamilyInterface); var family = new PluginFamily(testFamily); LoggingFamilyAttribute.Called.ShouldBeTrue(); } [Fact] public void set_the_lifecycle_to_Singleton() { var family = new PluginFamily(typeof(IServiceProvider)); family.SetLifecycleTo(Lifecycles.Singleton); family.Lifecycle.ShouldBeOfType<SingletonLifecycle>(); } [Fact] public void set_the_lifecycle_to_ThreadLocal() { var family = new PluginFamily(typeof(IServiceProvider)); family.SetLifecycleTo(Lifecycles.ThreadLocal); family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>(); } [Fact] public void add_instance_fills_and_is_idempotent() { var instance = new ConstructorInstance(GetType()); var family = new PluginFamily(GetType()); family.AddInstance(instance); family.SetDefault(instance); family.AddInstance(instance); family.SetDefault(instance); family.Instances.Single().ShouldBeTheSameAs(instance); } [Fact] public void add_type_by_name() { var family = new PluginFamily(typeof(IServiceProvider)); family.AddType(typeof(DataTableProvider), "table"); family.Instances.Single() .ShouldBeOfType<ConstructorInstance>() .PluggedType.ShouldBe(typeof(DataTableProvider)); } [Fact] public void add_type_does_not_add_if_the_concrete_type_can_not_be_cast_to_plugintype() { var family = new PluginFamily(typeof(IServiceProvider)); family.AddType(GetType()); family.Instances.Any().ShouldBeFalse(); } public class DataTable : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } public class DataSet : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } [Fact] public void add_type_works_if_the_concrete_type_can_be_cast_to_plugintype() { var family = new PluginFamily(typeof(IServiceProvider)); family.AddType(typeof(DataTableProvider)); family.Instances.Single() .ShouldBeOfType<ConstructorInstance>() .PluggedType.ShouldBe(typeof(DataTableProvider)); family.AddType(typeof(DataTable)); family.AddType(GetType()); family.Instances.Count().ShouldBe(2); } [Fact] public void remove_all_clears_the_defaul_and_removes_all_plugins_instances() { var family = new PluginFamily(typeof(IServiceProvider)); var instance = new SmartInstance<DataSet>(); family.Fallback = new SmartInstance<DataSet>(); family.SetDefault(instance); family.AddInstance(new SmartInstance<FakeServiceProvider>()); family.AddType(typeof(DataSet)); family.RemoveAll(); family.GetDefaultInstance().ShouldBeNull(); family.Instances.Count().ShouldBe(0); } public class FakeServiceProvider : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } [Fact] public void remove_all_clears_the_default() { var instance = new ConstructorInstance(GetType()); var family = new PluginFamily(GetType()); family.SetDefault(instance); family.SetDefault(new ConstructorInstance(GetType())); family.SetDefault(new ConstructorInstance(GetType())); family.RemoveAll(); family.Instances.Any().ShouldBeFalse(); family.GetDefaultInstance().ShouldNotBeTheSameAs(instance); } [Fact] public void removing_the_default_will_change_the_default() { var instance = new ConstructorInstance(GetType()); var family = new PluginFamily(GetType()); family.SetDefault(instance); family.RemoveInstance(instance); family.Instances.Any().ShouldBeFalse(); family.GetDefaultInstance().ShouldNotBeTheSameAs(instance); } [Fact] public void set_default() { var family = new PluginFamily(typeof(IServiceProvider)); var instance = new SmartInstance<DataSet>(); family.SetDefault(instance); family.GetDefaultInstance().ShouldBeTheSameAs(instance); } } /// <summary> /// Specifying the default instance is "Default" and marking the PluginFamily /// as an injected SingletonThing /// </summary> //[PluginFamily("Default", IsSingleton = true)] public interface ISingletonRepository { } //[Pluggable("Default")] public class SingletonRepositoryWithAttribute : ISingletonRepository { private readonly Guid _id = Guid.NewGuid(); public Guid Id { get { return _id; } } } public class SingletonRepositoryWithoutPluginAttribute : ISingletonRepository { } public class RandomClass { } //[PluginFamily(IsSingleton = false)] public interface IDevice { } public class GenericType<T> { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Class: SortedList ** ** Purpose: Represents a collection of key/value pairs ** that are sorted by the keys and are accessible ** by key and by index. ** ===========================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Collections { // The SortedList class implements a sorted list of keys and values. Entries in // a sorted list are sorted by their keys and are accessible both by key and by // index. The keys of a sorted list can be ordered either according to a // specific IComparer implementation given when the sorted list is // instantiated, or according to the IComparable implementation provided // by the keys themselves. In either case, a sorted list does not allow entries // with duplicate keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimToSize or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // [DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SortedList : IDictionary, ICloneable { private Object[] keys; // Do not rename (binary serialization) private Object[] values; // Do not rename (binary serialization) private int _size; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private IComparer comparer; // Do not rename (binary serialization) private KeyList keyList; // Do not rename (binary serialization) private ValueList valueList; // Do not rename (binary serialization) [NonSerialized] private Object _syncRoot; private const int _defaultCapacity = 16; // Copy of Array.MaxArrayLength internal const int MaxArrayLength = 0X7FEFFFFF; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { Init(); } private void Init() { keys = Array.Empty<Object>(); values = Array.Empty<Object>(); _size = 0; comparer = new Comparer(CultureInfo.CurrentCulture); } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); keys = new Object[initialCapacity]; values = new Object[initialCapacity]; comparer = new Comparer(CultureInfo.CurrentCulture); } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList(IComparer comparer) : this() { if (comparer != null) this.comparer = comparer; } // Constructs a new sorted list with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList(IComparer comparer, int capacity) : this(comparer) { Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary d) : this(d, null) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary d, IComparer comparer) : this(comparer, (d != null ? d.Count : 0)) { if (d == null) throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); d.Keys.CopyTo(keys, 0); d.Values.CopyTo(values, 0); // Array.Sort(Array keys, Array values, IComparer comparer) does not exist in System.Runtime contract v4.0.10.0. // This works around that by sorting only on the keys and then assigning values accordingly. Array.Sort(keys, comparer); for (int i = 0; i < keys.Length; i++) { values[i] = d[keys[i]]; } _size = d.Count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public virtual void Add(Object key, Object value) { if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, GetKey(i), key)); Insert(~i, key, value); } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public virtual int Capacity { get { return keys.Length; } set { if (value < Count) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } if (value != keys.Length) { if (value > 0) { Object[] newKeys = new Object[value]; Object[] newValues = new Object[value]; if (_size > 0) { Array.Copy(keys, 0, newKeys, 0, _size); Array.Copy(values, 0, newValues, 0, _size); } keys = newKeys; values = newValues; } else { // size can only be zero here. Debug.Assert(_size == 0, "Size is not zero"); keys = Array.Empty<Object>(); values = Array.Empty<Object>(); } } } } // Returns the number of entries in this sorted list. // public virtual int Count { get { return _size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. // public virtual ICollection Keys { get { return GetKeyList(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public virtual ICollection Values { get { return GetValueList(); } } // Is this SortedList read-only? public virtual bool IsReadOnly { get { return false; } } public virtual bool IsFixedSize { get { return false; } } // Is this SortedList synchronized (thread-safe)? public virtual bool IsSynchronized { get { return false; } } // Synchronization root for this object. public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all entries from this sorted list. public virtual void Clear() { // clear does not change the capacity version++; Array.Clear(keys, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. Array.Clear(values, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } // Makes a virtually identical copy of this SortedList. This is a shallow // copy. IE, the Objects in the SortedList are not cloned - we copy the // references to those objects. public virtual Object Clone() { SortedList sl = new SortedList(_size); Array.Copy(keys, 0, sl.keys, 0, _size); Array.Copy(values, 0, sl.values, 0, _size); sl._size = _size; sl.version = version; sl.comparer = comparer; // Don't copy keyList nor valueList. return sl; } // Checks if this sorted list contains an entry with the given key. // public virtual bool Contains(Object key) { return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given key. // public virtual bool ContainsKey(Object key) { // Yes, this is a SPEC'ed duplicate of Contains(). return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. // public virtual bool ContainsValue(Object value) { return IndexOfValue(value) >= 0; } // Copies the values in this SortedList to an array. public virtual void CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - arrayIndex < Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); for (int i = 0; i < Count; i++) { DictionaryEntry entry = new DictionaryEntry(keys[i], values[i]); array.SetValue(entry, i + arrayIndex); } } // Copies the values in this SortedList to an KeyValuePairs array. // KeyValuePairs is different from Dictionary Entry in that it has special // debugger attributes on its fields. internal virtual KeyValuePairs[] ToKeyValuePairsArray() { KeyValuePairs[] array = new KeyValuePairs[Count]; for (int i = 0; i < Count; i++) { array[i] = new KeyValuePairs(keys[i], values[i]); } return array; } // Ensures that the capacity of this sorted list is at least the given // minimum value. If the current capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity(int min) { int newCapacity = keys.Length == 0 ? 16 : keys.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } // Returns the value of the entry at the given index. // public virtual Object GetByIndex(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); return values[index]; } // Returns an IEnumerator for this sorted list. If modifications // made to the sorted list while an enumeration is in progress, // the MoveNext and Remove methods // of the enumerator will throw an exception. // IEnumerator IEnumerable.GetEnumerator() { return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry); } // Returns an IDictionaryEnumerator for this sorted list. If modifications // made to the sorted list while an enumeration is in progress, // the MoveNext and Remove methods // of the enumerator will throw an exception. // public virtual IDictionaryEnumerator GetEnumerator() { return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry); } // Returns the key of the entry at the given index. // public virtual Object GetKey(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); return keys[index]; } // Returns an IList representing the keys of this sorted list. The // returned list is an alias for the keys of this sorted list, so // modifications made to the returned list are directly reflected in the // underlying sorted list, and vice versa. The elements of the returned // list are ordered in the same way as the elements of the sorted list. The // returned list does not support adding, inserting, or modifying elements // (the Add, AddRange, Insert, InsertRange, // Reverse, Set, SetRange, and Sort methods // throw exceptions), but it does allow removal of elements (through the // Remove and RemoveRange methods or through an enumerator). // Null is an invalid key value. // public virtual IList GetKeyList() { if (keyList == null) keyList = new KeyList(this); return keyList; } // Returns an IList representing the values of this sorted list. The // returned list is an alias for the values of this sorted list, so // modifications made to the returned list are directly reflected in the // underlying sorted list, and vice versa. The elements of the returned // list are ordered in the same way as the elements of the sorted list. The // returned list does not support adding or inserting elements (the // Add, AddRange, Insert and InsertRange // methods throw exceptions), but it does allow modification and removal of // elements (through the Remove, RemoveRange, Set and // SetRange methods or through an enumerator). // public virtual IList GetValueList() { if (valueList == null) valueList = new ValueList(this); return valueList; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // public virtual Object this[Object key] { get { int i = IndexOfKey(key); if (i >= 0) return values[i]; return null; } set { if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) { values[i] = value; version++; return; } Insert(~i, key, value); } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. // public virtual int IndexOfKey(Object key) { if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. // public virtual int IndexOfValue(Object value) { return Array.IndexOf(values, value, 0, _size); } // Inserts an entry with a given key and value at a given index. private void Insert(int index, Object key, Object value) { if (_size == keys.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(keys, index, keys, index + 1, _size - index); Array.Copy(values, index, values, index + 1, _size - index); } keys[index] = key; values[index] = value; _size++; version++; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. // public virtual void RemoveAt(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); _size--; if (index < _size) { Array.Copy(keys, index + 1, keys, index, _size - index); Array.Copy(values, index + 1, values, index, _size - index); } keys[_size] = null; values[_size] = null; version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. // public virtual void Remove(Object key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); } // Sets the value at an index to a given value. The previous value of // the given entry is overwritten. // public virtual void SetByIndex(int index, Object value) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); values[index] = value; version++; } // Returns a thread-safe SortedList. // public static SortedList Synchronized(SortedList list) { if (list == null) throw new ArgumentNullException(nameof(list)); return new SyncSortedList(list); } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // sortedList.Clear(); // sortedList.TrimToSize(); // public virtual void TrimToSize() { Capacity = _size; } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] private class SyncSortedList : SortedList { private SortedList _list; // Do not rename (binary serialization) private Object _root; // Do not rename (binary serialization) internal SyncSortedList(SortedList list) { _list = list; _root = list.SyncRoot; } public override int Count { get { lock (_root) { return _list.Count; } } } public override Object SyncRoot { get { return _root; } } public override bool IsReadOnly { get { return _list.IsReadOnly; } } public override bool IsFixedSize { get { return _list.IsFixedSize; } } public override bool IsSynchronized { get { return true; } } public override Object this[Object key] { get { lock (_root) { return _list[key]; } } set { lock (_root) { _list[key] = value; } } } public override void Add(Object key, Object value) { lock (_root) { _list.Add(key, value); } } public override int Capacity { get { lock (_root) { return _list.Capacity; } } } public override void Clear() { lock (_root) { _list.Clear(); } } public override Object Clone() { lock (_root) { return _list.Clone(); } } public override bool Contains(Object key) { lock (_root) { return _list.Contains(key); } } public override bool ContainsKey(Object key) { lock (_root) { return _list.ContainsKey(key); } } public override bool ContainsValue(Object key) { lock (_root) { return _list.ContainsValue(key); } } public override void CopyTo(Array array, int index) { lock (_root) { _list.CopyTo(array, index); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override Object GetByIndex(int index) { lock (_root) { return _list.GetByIndex(index); } } public override IDictionaryEnumerator GetEnumerator() { lock (_root) { return _list.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override Object GetKey(int index) { lock (_root) { return _list.GetKey(index); } } public override IList GetKeyList() { lock (_root) { return _list.GetKeyList(); } } public override IList GetValueList() { lock (_root) { return _list.GetValueList(); } } public override int IndexOfKey(Object key) { if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); lock (_root) { return _list.IndexOfKey(key); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int IndexOfValue(Object value) { lock (_root) { return _list.IndexOfValue(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } public override void Remove(Object key) { lock (_root) { _list.Remove(key); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void SetByIndex(int index, Object value) { lock (_root) { _list.SetByIndex(index, value); } } internal override KeyValuePairs[] ToKeyValuePairsArray() { return _list.ToKeyValuePairsArray(); } public override void TrimToSize() { lock (_root) { _list.TrimToSize(); } } } private class SortedListEnumerator : IDictionaryEnumerator, ICloneable { private SortedList _sortedList; private Object _key; private Object _value; private int _index; private int _startIndex; // Store for Reset. private int _endIndex; private int _version; private bool _current; // Is the current element valid? private int _getObjectRetType; // What should GetObject return? internal const int Keys = 1; internal const int Values = 2; internal const int DictEntry = 3; internal SortedListEnumerator(SortedList sortedList, int index, int count, int getObjRetType) { _sortedList = sortedList; _index = index; _startIndex = index; _endIndex = index + count; _version = sortedList.version; _getObjectRetType = getObjRetType; _current = false; } public object Clone() => MemberwiseClone(); public virtual Object Key { get { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); return _key; } } public virtual bool MoveNext() { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < _endIndex) { _key = _sortedList.keys[_index]; _value = _sortedList.values[_index]; _index++; _current = true; return true; } _key = null; _value = null; _current = false; return false; } public virtual DictionaryEntry Entry { get { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); return new DictionaryEntry(_key, _value); } } public virtual Object Current { get { if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); if (_getObjectRetType == Keys) return _key; else if (_getObjectRetType == Values) return _value; else return new DictionaryEntry(_key, _value); } } public virtual Object Value { get { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); return _value; } } public virtual void Reset() { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = _startIndex; _current = false; _key = null; _value = null; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] private class KeyList : IList { private SortedList sortedList; // Do not rename (binary serialization) internal KeyList(SortedList sortedList) { this.sortedList = sortedList; } public virtual int Count { get { return sortedList._size; } } public virtual bool IsReadOnly { get { return true; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsSynchronized { get { return sortedList.IsSynchronized; } } public virtual Object SyncRoot { get { return sortedList.SyncRoot; } } public virtual int Add(Object key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return 0; // suppress compiler warning } public virtual void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual bool Contains(Object key) { return sortedList.Contains(key); } public virtual void CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // defer error checking to Array.Copy Array.Copy(sortedList.keys, 0, array, arrayIndex, sortedList.Count); } public virtual void Insert(int index, Object value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual Object this[int index] { get { return sortedList.GetKey(index); } set { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } } public virtual IEnumerator GetEnumerator() { return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Keys); } public virtual int IndexOf(Object key) { if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int i = Array.BinarySearch(sortedList.keys, 0, sortedList.Count, key, sortedList.comparer); if (i >= 0) return i; return -1; } public virtual void Remove(Object key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] private class ValueList : IList { private SortedList sortedList; // Do not rename (binary serialization) internal ValueList(SortedList sortedList) { this.sortedList = sortedList; } public virtual int Count { get { return sortedList._size; } } public virtual bool IsReadOnly { get { return true; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsSynchronized { get { return sortedList.IsSynchronized; } } public virtual Object SyncRoot { get { return sortedList.SyncRoot; } } public virtual int Add(Object key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual bool Contains(Object value) { return sortedList.ContainsValue(value); } public virtual void CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // defer error checking to Array.Copy Array.Copy(sortedList.values, 0, array, arrayIndex, sortedList.Count); } public virtual void Insert(int index, Object value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual Object this[int index] { get { return sortedList.GetByIndex(index); } set { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } public virtual IEnumerator GetEnumerator() { return new SortedListEnumerator(sortedList, 0, sortedList.Count, SortedListEnumerator.Values); } public virtual int IndexOf(Object value) { return Array.IndexOf(sortedList.values, value, 0, sortedList.Count); } public virtual void Remove(Object value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public virtual void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } // internal debug view class for sorted list internal class SortedListDebugView { private SortedList _sortedList; public SortedListDebugView(SortedList sortedList) { if (sortedList == null) { throw new ArgumentNullException(nameof(sortedList)); } _sortedList = sortedList; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePairs[] Items { get { return _sortedList.ToKeyValuePairsArray(); } } } } }
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2013-2015 CoreTweet Development Team // // 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 Newtonsoft.Json; namespace CoreTweet.Core { /// <summary> /// Provides the <see cref="System.Uri"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>. /// </summary> public class UriConverter : JsonConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type. /// </summary> /// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param> /// <returns> /// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType.Equals(typeof(Uri)); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">The <see cref="System.Type"/> of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch(reader.TokenType) { case JsonToken.String: return new Uri(reader.Value as String); case JsonToken.Null: return null; } throw new InvalidOperationException("This object is not a Uri"); } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if(null == value) writer.WriteNull(); else if(value is Uri) writer.WriteValue(((Uri)value).OriginalString); else throw new InvalidOperationException("This object is not a Uri"); } } /// <summary> /// Provides the <see cref="System.DateTimeOffset"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>. /// </summary> public class DateTimeOffsetConverter : JsonConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the type you want to convert to.</param> /// <returns> /// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type type) { return type.Equals(typeof(DateTimeOffset)); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">The <see cref="System.Type"/> of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch(reader.TokenType) { case JsonToken.String: return DateTimeOffset.ParseExact(reader.Value as string, "ddd MMM dd HH:mm:ss K yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AllowWhiteSpaces); case JsonToken.Date: if (reader.Value is DateTimeOffset) return (DateTimeOffset)reader.Value; else return new DateTimeOffset(((DateTime)reader.Value).ToUniversalTime(), TimeSpan.Zero); case JsonToken.Integer: return InternalUtils.GetUnixTime((long)reader.Value); case JsonToken.Null: return DateTimeOffset.Now; } throw new InvalidOperationException("This object is not a DateTimeOffset"); } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if(value is DateTimeOffset) writer.WriteValue((DateTimeOffset)value); else throw new InvalidOperationException("This object is not a DateTimeOffset"); } } /// <summary> /// Provides the <see cref="CoreTweet.Contributors"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>. /// </summary> public class ContributorsConverter : JsonConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type. /// </summary> /// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param> /// <returns> /// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType.Equals(typeof(Contributors)); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">The <see cref="System.Type"/> of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch(reader.TokenType) { case JsonToken.Integer: return new Contributors { Id = (long)reader.Value }; case JsonToken.StartObject: reader.Read(); var value = new Contributors(); while(reader.TokenType != JsonToken.EndObject) { if(reader.TokenType != JsonToken.PropertyName) throw new FormatException("The format of this object is wrong"); switch((string)reader.Value) { case "id": value.Id = (long)reader.ReadAsDecimal(); break; case "screen_name": value.ScreenName = reader.ReadAsString(); break; default: reader.Read(); break; } reader.Read(); } return value; } throw new InvalidOperationException("This object is not a Contributors"); } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } /// <summary> /// Provides the <see cref="System.DateTimeOffset"/> converter of the <see cref="Newtonsoft.Json.JsonSerializer"/>. /// </summary> public class TimestampConverter : JsonConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type. /// </summary> /// <param name="objectType">A <see cref="System.Type"/> that represents the type you want to convert to.</param> /// <returns> /// <c>true</c> if this converter can perform the conversion; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType.Equals(typeof(DateTimeOffset)); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">The <see cref="System.Type"/> of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { long ms; switch(reader.TokenType) { case JsonToken.String: ms = long.Parse(reader.Value.ToString()); break; case JsonToken.Integer: ms = (long)reader.Value; break; default: throw new InvalidOperationException("This object is not a timestamp"); } return InternalUtils.GetUnixTimeMs(ms); } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if(value is DateTimeOffset) writer.WriteValue(((((DateTimeOffset)value).Ticks - InternalUtils.unixEpoch.Ticks) / 10000).ToString("D")); else throw new InvalidOperationException("This object is not a DateTimeOffset"); } } }
#region License /* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.IO; using System.Text; using System.Collections.Generic; #if SILVERLIGHT using Spring.Collections.Specialized; #else using System.Collections.Specialized; #endif using Spring.IO; namespace Spring.Http.Converters { /// <summary> /// Implementation of <see cref="IHttpMessageConverter"/> that can handle form data, /// including multipart form data (i.e. file uploads). /// </summary> /// <remarks> /// <para> /// This converter supports the 'application/x-www-form-urlencoded' and 'multipart/form-data' media /// types, and read the 'application/x-www-form-urlencoded' media type (but not 'multipart/form-data'). /// </para> /// <para> /// This converter uses UTF-8 to write form data as recommended by the W3C. /// </para> /// <para> /// In other words, this converter can read and write 'normal' HTML forms (as <see cref="NameValueCollection"/>), /// and it can write multipart form (as <see cref="IDictionary{String,Object}"/>). /// When writing multipart, this converter uses other <see cref="IHttpMessageConverter"/> to write the respective MIME parts. /// By default, basic converters are registered (supporting <see cref="String"/>, <see cref="FileInfo"/> /// and <see cref="IResource"/>, for instance); these can be overridden by setting <see cref="P:PartConverters"/> property. /// </para> /// <para> /// For example, the following snippet shows how to submit an HTML form: /// <code> /// RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default /// NameValueCollection form = new NameValueCollection(); /// form.Add("field 1", "value 1"); /// form.Add("field 2", "value 2"); /// form.Add("field 2", "value 3"); /// template.PostForLocation("http://example.com/myForm", form); /// </code> /// </para> /// <para> /// The following snippet shows how to do a file upload: /// <code> /// RestTemplate template = new RestTemplate(); /// IDictionary&lt;string, object> parts = new Dictionary&lt;string, object>(); /// parts.Add("field 1", "value 1"); /// parts.Add("file", new FileResource(@"C:\myDir\myFile.jpg")); /// template.PostForLocation("http://example.com/myFileUpload", parts); /// </code> /// </para> /// </remarks> /// <author>Arjen Poutsma</author> /// <author>Bruno Baia (.NET)</author> public class FormHttpMessageConverter : IHttpMessageConverter { /// <summary> /// Default encoding for forms. /// </summary> protected static readonly Encoding DEFAULT_CHARSET = new UTF8Encoding(false); // Remove byte Order Mask (BOM) private static char[] BOUNDARY_CHARS = new char[]{'-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private Random random; private IList<MediaType> _supportedMediaTypes; private IList<IHttpMessageConverter> _partConverters; /// <summary> /// Gets or sets the message body converters to use. /// These converters are used to convert objects to MIME parts. /// </summary> public IList<IHttpMessageConverter> PartConverters { get { return _partConverters; } set { _partConverters = value; } } /// <summary> /// Creates a new instance of the <see cref="FormHttpMessageConverter"/>. /// </summary> public FormHttpMessageConverter() { this.random = new Random(); this._supportedMediaTypes = new List<MediaType>(2); this._supportedMediaTypes.Add(MediaType.APPLICATION_FORM_URLENCODED); this._supportedMediaTypes.Add(MediaType.MULTIPART_FORM_DATA); this._partConverters = new List<IHttpMessageConverter>(3); this._partConverters.Add(new ByteArrayHttpMessageConverter()); this._partConverters.Add(new StringHttpMessageConverter()); #pragma warning disable 618 this._partConverters.Add(new FileInfoHttpMessageConverter()); #pragma warning restore 618 this._partConverters.Add(new ResourceHttpMessageConverter()); } #region IHttpMessageConverter Members /// <summary> /// Indicates whether the given class can be read by this converter. /// </summary> /// <param name="type">The class to test for readability</param> /// <param name="mediaType"> /// The media type to read, can be null if not specified. Typically the value of a 'Content-Type' header. /// </param> /// <returns><see langword="true"/> if readable; otherwise <see langword="false"/></returns> public bool CanRead(Type type, MediaType mediaType) { if (typeof(NameValueCollection).IsAssignableFrom(type)) { if (mediaType == null) { return true; } foreach (MediaType supportedMediaType in this._supportedMediaTypes) { if (supportedMediaType != MediaType.MULTIPART_FORM_DATA && supportedMediaType.Includes(mediaType)) { return true; } } } return false; } /// <summary> /// Indicates whether the given class can be written by this converter. /// </summary> /// <param name="type">The class to test for writability</param> /// <param name="mediaType"> /// The media type to write, can be null if not specified. Typically the value of an 'Accept' header. /// </param> /// <returns><see langword="true"/> if writable; otherwise <see langword="false"/></returns> public bool CanWrite(Type type, MediaType mediaType) { if (typeof(NameValueCollection).IsAssignableFrom(type) || typeof(IDictionary<string, object>).IsAssignableFrom(type)) { if (mediaType == null) { return true; } foreach (MediaType supportedMediaType in this._supportedMediaTypes) { if (supportedMediaType.IsCompatibleWith(mediaType)) { return true; } } } return false; } /// <summary> /// Gets the list of <see cref="MediaType"/> objects supported by this converter. /// </summary> public IList<MediaType> SupportedMediaTypes { get { return _supportedMediaTypes; } } /// <summary> /// Read an object of the given type form the given HTTP message, and returns it. /// </summary> /// <typeparam name="T"> /// The type of object to return. This type must have previously been passed to the /// <see cref="M:CanRead"/> method of this interface, which must have returned <see langword="true"/>. /// </typeparam> /// <param name="message">The HTTP message to read from.</param> /// <returns>The converted object.</returns> /// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception> public T Read<T>(IHttpInputMessage message) where T : class { // Get the message encoding MediaType contentType = message.Headers.ContentType; Encoding encoding = (contentType != null && contentType.CharSet != null) ? contentType.CharSet : DEFAULT_CHARSET; // Read from the message stream string body; using (StreamReader reader = new StreamReader(message.Body, encoding)) { body = reader.ReadToEnd(); } string[] pairs = body.Split('&'); NameValueCollection result = new NameValueCollection(pairs.Length); foreach (string pair in pairs) { int idx = pair.IndexOf('='); if (idx == -1) { result.Add(HttpUtils.FormDecode(pair), null); } else { string name = HttpUtils.FormDecode(pair.Substring(0, idx)); string value = HttpUtils.FormDecode(pair.Substring(idx + 1)); result.Add(name, value); } } return result as T; } /// <summary> /// Write an given object to the given HTTP message. /// </summary> /// <param name="content"> /// The object to write to the HTTP message. The type of this object must have previously been /// passed to the <see cref="M:CanWrite"/> method of this interface, which must have returned <see langword="true"/>. /// </param> /// <param name="contentType"> /// The content type to use when writing. May be null to indicate that the default content type of the converter must be used. /// If not null, this media type must have previously been passed to the <see cref="M:CanWrite"/> method of this interface, /// which must have returned <see langword="true"/>. /// </param> /// <param name="message">The HTTP message to write to.</param> /// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception> public void Write(object content, MediaType contentType, IHttpOutputMessage message) { if (content is NameValueCollection) { this.WriteForm((NameValueCollection) content, message); } else if (content is IDictionary<string, object>) { this.WriteMultipart((IDictionary<string, object>) content, message); } } #endregion #region Write Form private void WriteForm(NameValueCollection form, IHttpOutputMessage message) { message.Headers.ContentType = MediaType.APPLICATION_FORM_URLENCODED; StringBuilder builder = new StringBuilder(); for (int i = 0; i < form.AllKeys.Length; i++) { string name = form.AllKeys[i]; string[] values = form.GetValues(name); if (values == null) { builder.Append(HttpUtils.FormEncode(name)); } else { for (int j = 0; j < values.Length; j++) { string value = values[j]; builder.Append(HttpUtils.FormEncode(name)); builder.Append('='); builder.Append(HttpUtils.FormEncode(value)); if (j != (values.Length - 1)) { builder.Append('&'); } } } if (i != (form.AllKeys.Length - 1)) { builder.Append('&'); } } // Create a byte array of the data we want to send byte[] byteData = DEFAULT_CHARSET.GetBytes(builder.ToString()); //#if !SILVERLIGHT // // Set the content length in the message headers // message.Headers.ContentLength = byteData.Length; //#endif // Write to the message stream message.Body = delegate(Stream stream) { stream.Write(byteData, 0, byteData.Length); }; } #endregion #region Write Multipart private void WriteMultipart(IDictionary<string, object> parts, IHttpOutputMessage message) { string boundary = this.GenerateMultipartBoundary(); IDictionary<string, string> parameters = new Dictionary<string, string>(1); parameters.Add("boundary", boundary); MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters); message.Headers.ContentType = contentType; message.Body = delegate(Stream stream) { using (StreamWriter streamWriter = new StreamWriter(stream)) { streamWriter.NewLine = "\r\n"; this.WriteParts(boundary, parts, streamWriter); this.WriteEnd(boundary, streamWriter); } }; } /// <summary> /// Generates a multipart boundary. /// </summary> /// <remarks> /// Default implementation returns a random boundary. Can be overridden in subclasses. /// </remarks> /// <returns>A multipart boundary</returns> protected virtual string GenerateMultipartBoundary() { char[] boundary = new char[random.Next(11) + 30]; for (int i = 0; i < boundary.Length; i++) { boundary[i] = BOUNDARY_CHARS[random.Next(BOUNDARY_CHARS.Length)]; } return new String(boundary); } /// <summary> /// Return the filename of the given multipart part to be used for the 'Content-Disposition' header. /// </summary> /// <remarks> /// Default implementation returns <see cref="P:FileInfo.Name"/> if the part is a <see cref="FileInfo"/>, /// extracts the file name from the URI if the part is a <see cref="IResource"/> /// and <see langword="null"/> in other cases. Can be overridden in subclasses. /// </remarks> /// <param name="part">The part to determine the file name for</param> /// <returns>The filename, or <see langword="null"/> if not known</returns> protected virtual string GetMultipartFilename(object part) { if (part is FileInfo) { return ((FileInfo)part).Name; } else if (part is IResource) { Uri resourceUri = ((IResource)part).Uri; if (resourceUri != null) { return Path.GetFileName(resourceUri.ToString()); } } return null; } private void WriteParts(string boundary, IDictionary<string, object> parts, StreamWriter streamWriter) { foreach(KeyValuePair<string, object> entry in parts) { this.WriteBoundary(boundary, streamWriter); HttpEntity entity = this.GetEntity(entry.Value); this.WritePart(entry.Key, entity, streamWriter); streamWriter.WriteLine(); } } private void WriteBoundary(string boundary, StreamWriter streamWriter) { streamWriter.Write("--"); streamWriter.Write(boundary); streamWriter.WriteLine(); } private void WritePart(String name, HttpEntity partEntity, StreamWriter streamWriter) { object partBody = partEntity.Body; Type partType = partBody.GetType(); HttpHeaders partHeaders = partEntity.Headers; MediaType partContentType = partHeaders.ContentType; foreach (IHttpMessageConverter messageConverter in this._partConverters) { if (messageConverter.CanWrite(partType, partContentType)) { IHttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(streamWriter); multipartMessage.Headers["Content-Disposition"] = this.GetContentDispositionFormData(name, this.GetMultipartFilename(partBody)); foreach (string header in partHeaders) { multipartMessage.Headers[header] = partHeaders[header]; } messageConverter.Write(partBody, partContentType, multipartMessage); return; } } throw new HttpMessageNotWritableException(String.Format( "Could not write request: no suitable HttpMessageConverter found for part type [{0}]", partType)); } private void WriteEnd(string boundary, StreamWriter streamWriter) { streamWriter.Write("--"); streamWriter.Write(boundary); streamWriter.Write("--"); streamWriter.WriteLine(); } private HttpEntity GetEntity(object part) { if (part is HttpEntity) { return (HttpEntity)part; } return new HttpEntity(part); } /// <summary> /// Return the value of the 'Content-Disposition' header for 'form-data'. /// </summary> /// <param name="name">The field name</param> /// <param name="filename">The filename, may be <see langwrod="null"/></param> /// <returns>The value of the 'Content-Disposition' header</returns> private string GetContentDispositionFormData(string name, string filename) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("form-data; name=\"{0}\"", name); if (filename != null) { builder.AppendFormat("; filename=\"{0}\"", filename); } return builder.ToString(); } /// <summary> /// Implementation of <see cref="IHttpOutputMessage"/> used for writing multipart data. /// </summary> private sealed class MultipartHttpOutputMessage : IHttpOutputMessage { private HttpHeaders headers; private StreamWriter bodyWriter; public MultipartHttpOutputMessage(StreamWriter bodyWriter) { this.headers = new HttpHeaders(); this.bodyWriter = bodyWriter; } #region IHttpMessage Members public HttpHeaders Headers { get { return this.headers; } } public Action<Stream> Body { get { throw new InvalidOperationException(); } set { this.WritePartBody(value); } } #endregion private void WritePartBody(Action<Stream> body) { foreach (string header in this.headers) { bodyWriter.Write(header); bodyWriter.Write(": "); bodyWriter.Write(this.headers[header]); bodyWriter.WriteLine(); } bodyWriter.WriteLine(); bodyWriter.Flush(); Stream stream = bodyWriter.BaseStream; stream.Flush(); body(stream); stream.Flush(); } } #endregion } }
// <copyright file="ResourceTest.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace OpenTelemetry.Resources.Tests { public class ResourceTest : IDisposable { private const string KeyName = "key"; private const string ValueName = "value"; public ResourceTest() { ClearEnvVars(); } public void Dispose() { ClearEnvVars(); } [Fact] public void CreateResource_NullAttributeCollection() { // Act and Assert var resource = new Resource(null); Assert.Empty(resource.Attributes); } [Fact] public void CreateResource_NullAttributeValue() { // Arrange var attributes = new Dictionary<string, object> { { "NullValue", null } }; // Act and Assert Assert.Throws<ArgumentException>(() => new Resource(attributes)); } [Fact] public void CreateResource_EmptyAttributeKey() { // Arrange var attributes = new Dictionary<string, object> { { string.Empty, "value" } }; // Act var resource = new Resource(attributes); // Assert Assert.Single(resource.Attributes); var attribute = resource.Attributes.Single(); Assert.Empty(attribute.Key); Assert.Equal("value", attribute.Value); } [Fact] public void CreateResource_EmptyAttributeValue() { // Arrange var attributes = new Dictionary<string, object> { { "EmptyValue", string.Empty } }; // does not throw var resource = new Resource(attributes); // Assert Assert.Single(resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("EmptyValue", string.Empty), resource.Attributes); } [Fact] public void CreateResource_EmptyArray() { // Arrange var attributes = new Dictionary<string, object> { { "EmptyArray", new string[0] } }; // does not throw var resource = new Resource(attributes); // Assert Assert.Single(resource.Attributes); Assert.Equal(new string[0], resource.Attributes.Where(x => x.Key == "EmptyArray").FirstOrDefault().Value); } [Fact] public void CreateResource_EmptyAttribute() { // Arrange var attributeCount = 0; var attributes = this.CreateAttributes(attributeCount); // Act var resource = new Resource(attributes); // Assert ValidateResource(resource, attributeCount); } [Fact] public void CreateResource_SingleAttribute() { // Arrange var attributeCount = 1; var attributes = this.CreateAttributes(attributeCount); // Act var resource = new Resource(attributes); // Assert ValidateResource(resource, attributeCount); } [Fact] public void CreateResource_MultipleAttribute() { // Arrange var attributeCount = 5; var attributes = this.CreateAttributes(attributeCount); // Act var resource = new Resource(attributes); // Assert ValidateResource(resource, attributeCount); } [Fact] public void CreateResource_SupportedAttributeTypes() { // Arrange var attributes = new Dictionary<string, object> { { "string", "stringValue" }, { "bool", true }, { "double", 0.1d }, { "long", 1L }, // int and float supported by conversion to long and double { "int", 1 }, { "short", (short)1 }, { "float", 0.1f }, }; // Act var resource = new Resource(attributes); // Assert Assert.Equal(7, resource.Attributes.Count()); Assert.Contains(new KeyValuePair<string, object>("string", "stringValue"), resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("bool", true), resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("double", 0.1d), resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("long", 1L), resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("int", 1L), resource.Attributes); Assert.Contains(new KeyValuePair<string, object>("short", 1L), resource.Attributes); double convertedFloat = Convert.ToDouble(0.1f, System.Globalization.CultureInfo.InvariantCulture); Assert.Contains(new KeyValuePair<string, object>("float", convertedFloat), resource.Attributes); } [Fact] public void CreateResource_SupportedAttributeArrayTypes() { // Arrange var attributes = new Dictionary<string, object> { // natively supported array types { "string arr", new string[] { "stringValue" } }, { "bool arr", new bool[] { true } }, { "double arr", new double[] { 0.1d } }, { "long arr", new long[] { 1L } }, // have to convert to other primitive array types { "int arr", new int[] { 1 } }, { "short arr", new short[] { (short)1 } }, { "float arr", new float[] { 0.1f } }, }; // Act var resource = new Resource(attributes); // Assert Assert.Equal(7, resource.Attributes.Count()); Assert.Equal(new string[] { "stringValue" }, resource.Attributes.Where(x => x.Key == "string arr").FirstOrDefault().Value); Assert.Equal(new bool[] { true }, resource.Attributes.Where(x => x.Key == "bool arr").FirstOrDefault().Value); Assert.Equal(new double[] { 0.1d }, resource.Attributes.Where(x => x.Key == "double arr").FirstOrDefault().Value); Assert.Equal(new long[] { 1L }, resource.Attributes.Where(x => x.Key == "long arr").FirstOrDefault().Value); var longArr = new long[] { 1 }; var doubleArr = new double[] { Convert.ToDouble(0.1f, System.Globalization.CultureInfo.InvariantCulture) }; Assert.Equal(longArr, resource.Attributes.Where(x => x.Key == "int arr").FirstOrDefault().Value); Assert.Equal(longArr, resource.Attributes.Where(x => x.Key == "short arr").FirstOrDefault().Value); Assert.Equal(doubleArr, resource.Attributes.Where(x => x.Key == "float arr").FirstOrDefault().Value); } [Fact] public void CreateResource_NotSupportedAttributeTypes() { var attributes = new Dictionary<string, object> { { "dynamic", new { } }, { "array", new int[1] }, { "complex", this }, }; Assert.Throws<ArgumentException>(() => new Resource(attributes)); } [Fact] public void MergeResource_EmptyAttributeSource_MultiAttributeTarget() { // Arrange var sourceAttributeCount = 0; var sourceAttributes = this.CreateAttributes(sourceAttributeCount); var sourceResource = new Resource(sourceAttributes); var otherAttributeCount = 3; var otherAttributes = this.CreateAttributes(otherAttributeCount); var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); ValidateResource(newResource, sourceAttributeCount + otherAttributeCount); } [Fact] public void MergeResource_MultiAttributeSource_EmptyAttributeTarget() { // Arrange var sourceAttributeCount = 3; var sourceAttributes = this.CreateAttributes(sourceAttributeCount); var sourceResource = new Resource(sourceAttributes); var otherAttributeCount = 0; var otherAttributes = this.CreateAttributes(otherAttributeCount); var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); ValidateResource(newResource, sourceAttributeCount + otherAttributeCount); } [Fact] public void MergeResource_MultiAttributeSource_MultiAttributeTarget_NoOverlap() { // Arrange var sourceAttributeCount = 3; var sourceAttributes = this.CreateAttributes(sourceAttributeCount); var sourceResource = new Resource(sourceAttributes); var otherAttributeCount = 3; var otherAttributes = this.CreateAttributes(otherAttributeCount, sourceAttributeCount); var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); ValidateResource(newResource, sourceAttributeCount + otherAttributeCount); } [Fact] public void MergeResource_MultiAttributeSource_MultiAttributeTarget_SingleOverlap() { // Arrange var sourceAttributeCount = 3; var sourceAttributes = this.CreateAttributes(sourceAttributeCount); var sourceResource = new Resource(sourceAttributes); var otherAttributeCount = 3; var otherAttributes = this.CreateAttributes(otherAttributeCount, sourceAttributeCount - 1); var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); ValidateResource(newResource, sourceAttributeCount + otherAttributeCount - 1); // Also verify target attributes were not overwritten foreach (var otherAttribute in otherAttributes) { Assert.Contains(otherAttribute, otherResource.Attributes); } } [Fact] public void MergeResource_MultiAttributeSource_MultiAttributeTarget_FullOverlap() { // Arrange var sourceAttributeCount = 3; var sourceAttributes = this.CreateAttributes(sourceAttributeCount); var sourceResource = new Resource(sourceAttributes); var otherAttributeCount = 3; var otherAttributes = this.CreateAttributes(otherAttributeCount); var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); ValidateResource(newResource, otherAttributeCount); // Also verify target attributes were not overwritten foreach (var otherAttribute in otherAttributes) { Assert.Contains(otherAttribute, otherResource.Attributes); } } [Fact] public void MergeResource_MultiAttributeSource_DuplicatedKeysInPrimary() { // Arrange var sourceAttributes = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("key1", "value1"), new KeyValuePair<string, object>("key1", "value1.1"), }; var sourceResource = new Resource(sourceAttributes); var otherAttributes = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("key2", "value2"), }; var otherResource = new Resource(otherAttributes); // Act var newResource = sourceResource.Merge(otherResource); // Assert Assert.NotSame(otherResource, newResource); Assert.NotSame(sourceResource, newResource); Assert.Equal(2, newResource.Attributes.Count()); Assert.Contains(new KeyValuePair<string, object>("key1", "value1"), newResource.Attributes); Assert.Contains(new KeyValuePair<string, object>("key2", "value2"), newResource.Attributes); } [Fact] public void MergeResource_UpdatingResourceOverridesCurrentResource() { // Arrange var currentAttributes = new Dictionary<string, object> { { "value", "currentValue" } }; var updatingAttributes = new Dictionary<string, object> { { "value", "updatedValue" } }; var currentResource = new Resource(currentAttributes); var updatingResource = new Resource(updatingAttributes); var newResource = currentResource.Merge(updatingResource); // Assert Assert.Single(newResource.Attributes); Assert.Contains(new KeyValuePair<string, object>("value", "updatedValue"), newResource.Attributes); } [Fact] public void GetResourceWithTelemetrySDKAttributes() { // Arrange var resource = ResourceBuilder.CreateDefault().AddTelemetrySdk().Build(); // Assert var attributes = resource.Attributes; Assert.Equal(4, attributes.Count()); ValidateTelemetrySdkAttributes(attributes); } [Fact] public void GetResourceWithDefaultAttributes_EmptyResource() { // Arrange var resource = ResourceBuilder.CreateDefault().Build(); // Assert var attributes = resource.Attributes; Assert.Single(attributes); ValidateDefaultAttributes(attributes); } [Fact] public void GetResourceWithDefaultAttributes_ResourceWithAttrs() { // Arrange var resource = ResourceBuilder.CreateDefault().AddAttributes(this.CreateAttributes(2)).Build(); // Assert var attributes = resource.Attributes; Assert.Equal(3, attributes.Count()); ValidateAttributes(attributes, 0, 1); ValidateDefaultAttributes(attributes); } [Fact] public void GetResourceWithDefaultAttributes_WithResourceEnvVar() { // Arrange Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "EVKey1=EVVal1,EVKey2=EVVal2"); var resource = ResourceBuilder.CreateDefault().AddAttributes(this.CreateAttributes(2)).Build(); // Assert var attributes = resource.Attributes; Assert.Equal(5, attributes.Count()); ValidateAttributes(attributes, 0, 1); ValidateDefaultAttributes(attributes); Assert.Contains(new KeyValuePair<string, object>("EVKey1", "EVVal1"), attributes); Assert.Contains(new KeyValuePair<string, object>("EVKey2", "EVVal2"), attributes); } [Fact] public void EnvironmentVariableDetectors_DoNotDuplicateAttributes() { // Arrange Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "EVKey1=EVVal1,EVKey2=EVVal2"); var resource = ResourceBuilder.CreateDefault().AddEnvironmentVariableDetector().AddEnvironmentVariableDetector().Build(); // Assert var attributes = resource.Attributes; Assert.Equal(3, attributes.Count()); Assert.Contains(new KeyValuePair<string, object>("EVKey1", "EVVal1"), attributes); Assert.Contains(new KeyValuePair<string, object>("EVKey2", "EVVal2"), attributes); } [Fact] public void GetResource_WithServiceEnvVar() { // Arrange Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "some-service"); var resource = ResourceBuilder.CreateDefault().AddAttributes(this.CreateAttributes(2)).Build(); // Assert var attributes = resource.Attributes; Assert.Equal(3, attributes.Count()); ValidateAttributes(attributes, 0, 1); Assert.Contains(new KeyValuePair<string, object>("service.name", "some-service"), attributes); } [Fact] public void GetResource_WithServiceNameSetWithTwoEnvVars() { // Arrange Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "service.name=from-resource-attr"); Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "from-service-name"); var resource = ResourceBuilder.CreateDefault().AddAttributes(this.CreateAttributes(2)).Build(); // Assert var attributes = resource.Attributes; Assert.Equal(3, attributes.Count()); ValidateAttributes(attributes, 0, 1); Assert.Contains(new KeyValuePair<string, object>("service.name", "from-service-name"), attributes); } [Fact] public void GetResource_WithServiceNameSetWithTwoEnvVarsAndCode() { // Arrange Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, "service.name=from-resource-attr"); Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, "from-service-name"); var resource = ResourceBuilder.CreateDefault().AddService("from-code").AddAttributes(this.CreateAttributes(2)).Build(); // Assert var attributes = resource.Attributes; Assert.Equal(4, attributes.Count()); ValidateAttributes(attributes, 0, 1); Assert.Contains(new KeyValuePair<string, object>("service.name", "from-code"), attributes); } private static void ClearEnvVars() { Environment.SetEnvironmentVariable(OtelEnvResourceDetector.EnvVarKey, null); Environment.SetEnvironmentVariable(OtelServiceNameEnvVarDetector.EnvVarKey, null); } private static void AddAttributes(Dictionary<string, object> attributes, int attributeCount, int startIndex = 0) { for (var i = startIndex; i < attributeCount + startIndex; ++i) { attributes.Add($"{KeyName}{i}", $"{ValueName}{i}"); } } private static void ValidateAttributes(IEnumerable<KeyValuePair<string, object>> attributes, int startIndex = 0, int endIndex = 0) { var keyValuePairs = attributes as KeyValuePair<string, object>[] ?? attributes.ToArray(); var endInd = endIndex == 0 ? keyValuePairs.Length - 1 : endIndex; for (var i = startIndex; i <= endInd; ++i) { Assert.Contains(new KeyValuePair<string, object>($"{KeyName}{i}", $"{ValueName}{i}"), keyValuePairs); } } private static void ValidateResource(Resource resource, int attributeCount) { Assert.NotNull(resource); Assert.NotNull(resource.Attributes); Assert.Equal(attributeCount, resource.Attributes.Count()); ValidateAttributes(resource.Attributes); } private static void ValidateTelemetrySdkAttributes(IEnumerable<KeyValuePair<string, object>> attributes) { Assert.Contains(new KeyValuePair<string, object>("telemetry.sdk.name", "opentelemetry"), attributes); Assert.Contains(new KeyValuePair<string, object>("telemetry.sdk.language", "dotnet"), attributes); var versionAttribute = attributes.Where(pair => pair.Key.Equals("telemetry.sdk.version")); Assert.Single(versionAttribute); } private static void ValidateDefaultAttributes(IEnumerable<KeyValuePair<string, object>> attributes) { var serviceName = attributes.Where(pair => pair.Key.Equals("service.name")); Assert.Single(serviceName); Assert.Contains("unknown_service", serviceName.FirstOrDefault().Value as string); } private Dictionary<string, object> CreateAttributes(int attributeCount, int startIndex = 0) { var attributes = new Dictionary<string, object>(); AddAttributes(attributes, attributeCount, startIndex); return attributes; } } }
using Saga.Enumarations; using Saga.Map.Librairies; using Saga.Map.Utils.Definitions.Misc; using Saga.Packets; using Saga.PrimaryTypes; using Saga.Structures; using Saga.Tasks; using System; using System.Collections.Generic; using System.Diagnostics; namespace Saga.Map.Client { partial class Client { /// <summary> /// Occurs when casting a skill /// </summary> /// <param name="cpkt"></param> private void CM_SKILLCAST(CMSG_SKILLCAST cpkt) { lock (this.character.cooldowncollection) { try { MapObject target; uint skill = cpkt.SkillID; byte skilltype = cpkt.SkillType; Factory.Spells.Info info = null; bool cancast = Regiontree.TryFind(cpkt.TargetActor, this.character, out target) && Singleton.SpellManager.TryGetSpell(skill, out info) && this.character._lastcastedskill == 0 && ((long)((uint)Environment.TickCount) - this.character._lastcastedtick) > 0 && (info.delay == 0 || !this.character.cooldowncollection.IsCoolDown(skill)) && (info.maximumrange == 0 || info.IsInRangeOf((int)(Vector.GetDistance2D(this.character.Position, target.Position)))) && info.requiredWeapons[this.character.weapons.GetCurrentWeaponType()] == 1 && this.character.jlvl >= info.requiredJobs[this.character.job - 1] && this.character.Status.CurrentLp >= (info.requiredlp == 6 ? 1 : info.requiredlp) && info.IsTarget(this.character, target); if (cancast) { //Set anti-hack variables this.character._lastcastedskill = skill; this.character._lastcastedtick = (Environment.TickCount + (int)info.casttime); this.character.cooldowncollection.Update(); //Notify all actors that cast is in progress Regiontree tree = this.character.currentzone.Regiontree; foreach (Character regionObject in tree.SearchActors(this.character, SearchFlags.Characters)) { if (!Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position) || regionObject.client.isloaded == false) continue; SMSG_SKILLCAST spkt = new SMSG_SKILLCAST(); spkt.SourceActor = this.character.id; spkt.TargetActor = target.id; spkt.SkillID = skill; spkt.SkillType = skilltype; spkt.SessionId = regionObject.id; regionObject.client.Send((byte[])spkt); } } else { /*SMSG_SKILLCASTCANCEL spkt = new SMSG_SKILLCASTCANCEL(); spkt.SkillID = cpkt.SkillID; spkt.SourceActor = this.character.id; spkt.SkillType = cpkt.SkillType; this.Send((byte[])spkt);*/ //Skill failed SMSG_OFFENSIVESKILLFAILED spkt = new SMSG_OFFENSIVESKILLFAILED(); spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.SourceActor = this.character.id; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } catch (Exception) { Trace.TraceError("Exception processing the skill cast"); } } } /// <summary> /// Occurs when canceling a casted skill /// </summary> /// <param name="cpkt"></param> private void CM_SKILLCASTCANCEL(CMSG_SKILLCASTCANCEL cpkt) { lock (this.character.cooldowncollection) { try { uint skill = cpkt.SkillID; byte skilltype = cpkt.SkillType; Factory.Spells.Info info = null; if (Singleton.SpellManager.TryGetSpell(skill, out info)) { this.character._lastcastedskill = 0; this.character._lastcastedtick = Environment.TickCount; this.character.cooldowncollection.Add(skill, (int)info.delay); this.character.cooldowncollection.Update(); } //Notify all actors that cast is in progress Regiontree tree = this.character.currentzone.Regiontree; foreach (Character regionObject in tree.SearchActors(this.character, SearchFlags.Characters)) { if (!Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position) || regionObject.client.isloaded == false) continue; SMSG_SKILLCASTCANCEL spkt = new SMSG_SKILLCASTCANCEL(); spkt.SkillID = skill; spkt.SourceActor = this.character.id; spkt.SkillType = skilltype; spkt.SessionId = this.character.id; regionObject.client.Send((byte[])spkt); } } catch (Exception) { Trace.TraceError("Exception processing the skill cancel"); } } } /// <summary> /// Occurs when using an offensive skill /// </summary> /// <param name="cpkt"></param> private void CM_USEOFFENSIVESKILL(CMSG_OFFENSIVESKILL cpkt) { lock (this.character.cooldowncollection) { try { MapObject target; uint skillid = cpkt.SkillID; byte skilltype = cpkt.SkillType; SkillUsageEventArgs argument = null; bool cancast = Regiontree.TryFind(cpkt.TargetActor, this.character, out target) && SkillUsageEventArgs.Create(skillid, this.character, target, out argument) && argument.SpellInfo.casttime > -1 && (argument.SpellInfo.casttime == 0 || this.character._lastcastedskill == skillid) && ((long)((uint)Environment.TickCount) - this.character._lastcastedtick) > 0 && (argument.SpellInfo.delay == 0 || !this.character.cooldowncollection.IsCoolDown(skillid)) && (argument.SpellInfo.maximumrange == 0 || argument.SpellInfo.IsInRangeOf((int)(Vector.GetDistance2D(this.character.Position, target.Position)))) && argument.SpellInfo.requiredWeapons[this.character.weapons.GetCurrentWeaponType()] == 1 && this.character.jlvl >= argument.SpellInfo.requiredJobs[this.character.job - 1] && this.character.Status.CurrentLp >= (argument.SpellInfo.requiredlp == 6 ? 1 : argument.SpellInfo.requiredlp) && argument.SpellInfo.IsTarget(this.character, target); if (cancast && argument.Use()) { //Clear casted skill this.character._lastcastedskill = 0; this.character._lastcastedtick = Environment.TickCount; //Set cooldown timer int delay = (int)(argument.SpellInfo.delay - ((character.stats.Dexterity * 2) + (character.stats.Concentration * 2))); if (delay > 0) this.character.cooldowncollection.Add(skillid, delay); this.character.cooldowncollection.Update(); //Use required sp points if (argument.SpellInfo.SP > -1) { this.character.LASTSP_TICK = Environment.TickCount; this.character.SP = (ushort)(this.character.SP - argument.SpellInfo.SP); } //Set sp to 0 else if (argument.SpellInfo.SP == -1) { this.character.LASTSP_TICK = Environment.TickCount; this.character.SP = 0; } //Use required lp points if (argument.SpellInfo.requiredlp == 6) { this.character._status.CurrentLp = 0; this.character._status.Updates |= 1; } else if (argument.SpellInfo.requiredlp > 0) { this.character._status.CurrentLp -= argument.SpellInfo.requiredlp; this.character._status.Updates |= 1; } //Add intergrated durabillity checks if (argument.CanCheckWeaponDurabillity) Common.Durabillity.DoWeapon(this.character); //Skill sucess Predicate<Character> SendToCharacter = delegate(Character forwardTarget) { //Skill sucess SMSG_OFFENSIVESKILL spkt = new SMSG_OFFENSIVESKILL(); spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.TargetActor = cpkt.TargetActor; spkt.SourceActor = this.character.id; spkt.IsCritical = (forwardTarget.id == this.character.id || forwardTarget.id == target.id) ? (byte)argument.Result : (byte)7; spkt.Damage = argument.Damage; spkt.SessionId = forwardTarget.id; forwardTarget.client.Send((byte[])spkt); //Process some general updates if (forwardTarget._targetid == target.id) Common.Actions.SelectActor(forwardTarget, target as Actor); if (argument.TargetHasDied) Common.Actions.UpdateStance(forwardTarget, target as Actor); if (argument.TargetHasDied && MapObject.IsNpc(target)) Common.Actions.UpdateIcon(forwardTarget, target as BaseMob); return true; }; SendToCharacter(this.character); Regiontree tree = this.character.currentzone.Regiontree; foreach (Character forwardTarget in tree.SearchActors(this.character, SearchFlags.Characters)) { if (forwardTarget.id == this.character.id) continue; SendToCharacter(forwardTarget); } //Always update myself and oponent if it's character LifeCycle.Update(this.character); if (MapObject.IsPlayer(target)) { LifeCycle.Update(target as Character); } } else { //Skill failed SMSG_OFFENSIVESKILLFAILED spkt = new SMSG_OFFENSIVESKILLFAILED(); spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.SourceActor = this.character.id; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } catch (Exception e) { Trace.TraceError("Exception processing the skill {0}", e.ToString()); //Skill failed SMSG_OFFENSIVESKILLFAILED spkt = new SMSG_OFFENSIVESKILLFAILED(); spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.SourceActor = this.character.id; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } } /// <summary> /// Occurs when toggling between skills (aka stances) /// </summary> /// <param name="cpkt"></param> private void CM_SKILLTOGGLE(CMSG_SKILLTOGLE cpkt) { lock (this.character.cooldowncollection) { try { uint skillid = cpkt.SkillID; byte skilltype = cpkt.SkillType; SkillToggleEventArgs argument = null; bool cancast = SkillToggleEventArgs.Create(skillid, this.character, this.character, out argument) && argument.SpellInfo.casttime > -1 && (argument.SpellInfo.casttime == 0 || this.character._lastcastedskill == skillid) && Environment.TickCount - this.character._lastcastedtick > 0 && (argument.SpellInfo.delay == 0 || !this.character.cooldowncollection.IsCoolDown(skillid)) && (argument.SpellInfo.maximumrange == 0 || argument.SpellInfo.IsInRangeOf((int)(Vector.GetDistance2D(this.character.Position, this.character.Position)))) && argument.SpellInfo.requiredWeapons[this.character.weapons.GetCurrentWeaponType()] == 1 && this.character.jlvl >= argument.SpellInfo.requiredJobs[this.character.job - 1] && argument.SpellInfo.IsTarget(this.character, this.character); if (cancast && argument.Use()) { int delay = (int)(argument.SpellInfo.delay - ((character.stats.Dexterity * 2) + (character.stats.Concentration * 2))); if (delay > 0) this.character.cooldowncollection.Add(skillid, delay); this.character.cooldowncollection.Update(); SMSG_SKILLTOGLE spkt2 = new SMSG_SKILLTOGLE(); spkt2.SkillID = cpkt.SkillID; spkt2.SkillType = cpkt.SkillType; spkt2.SessionId = this.character.id; spkt2.Toggle = argument.Failed; this.Send((byte[])spkt2); if (character._status.Updates > 0) { LifeCycle.Update(character); character._status.Updates = 0; } Regiontree tree = this.character.currentzone.Regiontree; foreach (Character regionObject in tree.SearchActors(this.character, SearchFlags.Characters)) { SMSG_OFFENSIVESKILL spkt = new SMSG_OFFENSIVESKILL(); spkt.Damage = argument.Damage; spkt.SourceActor = this.character.id; spkt.TargetActor = this.character.id; spkt.SessionId = regionObject.id; spkt.SkillID = cpkt.SkillID; regionObject.client.Send((byte[])spkt); } } else { Console.WriteLine("Stance failed"); SMSG_SKILLTOGLE spkt2 = new SMSG_SKILLTOGLE(); spkt2.SkillID = cpkt.SkillID; spkt2.SkillType = cpkt.SkillType; spkt2.SessionId = this.character.id; spkt2.Toggle = true; this.Send((byte[])spkt2); } } catch (Exception e) { Trace.TraceError("Exception processing the skill {0}", e.ToString()); //Skill failed SMSG_OFFENSIVESKILLFAILED spkt = new SMSG_OFFENSIVESKILLFAILED(); spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.SourceActor = this.character.id; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } } /// <summary> /// Occurs when using a item that uses a skill /// </summary> /// <param name="cpkt"></param> private void CM_ITEMTOGGLE(CMSG_ITEMTOGLE cpkt) { lock (this.character.cooldowncollection) { try { Rag2Item item = this.character.container[cpkt.Index]; MapObject target; uint skillid = cpkt.SkillID; byte skilltype = cpkt.SkillType; ItemSkillUsageEventArgs argument = null; bool cancast = Regiontree.TryFind(cpkt.TargetActor, this.character, out target) && ItemSkillUsageEventArgs.Create(item, this.character, target, out argument) && argument.SpellInfo.casttime > -1 && (argument.SpellInfo.casttime == 0 || this.character._lastcastedskill == skillid) && ((long)((uint)Environment.TickCount) - this.character._lastcastedtick) > 0 && (argument.SpellInfo.delay == 0 || !this.character.cooldowncollection.IsCoolDown(skillid)) && (argument.SpellInfo.maximumrange == 0 || argument.SpellInfo.IsInRangeOf((int)(Vector.GetDistance2D(this.character.Position, target.Position)))) && argument.SpellInfo.requiredWeapons[this.character.weapons.GetCurrentWeaponType()] == 1 && this.character.jlvl > argument.SpellInfo.requiredJobs[this.character.job - 1] && argument.SpellInfo.IsTarget(this.character, target) && item.count > 0; if (cancast && argument.Use()) { int delay = (int)(argument.SpellInfo.delay - ((character.stats.Dexterity * 2) + (character.stats.Concentration * 2))); if (delay > 0) this.character.cooldowncollection.Add(skillid, delay); this.character.cooldowncollection.Update(); int newLength = this.character.container[cpkt.Index].count - 1; if (newLength > 0) { this.character.container[cpkt.Index].count = newLength; SMSG_UPDATEITEM spkt2 = new SMSG_UPDATEITEM(); spkt2.Amount = (byte)newLength; spkt2.UpdateReason = 8; spkt2.UpdateType = 4; spkt2.Container = 2; spkt2.SessionId = this.character.id; spkt2.Index = cpkt.Index; this.Send((byte[])spkt2); } else { this.character.container.RemoveAt(cpkt.Index); SMSG_DELETEITEM spkt3 = new SMSG_DELETEITEM(); spkt3.UpdateReason = 8; spkt3.Container = 2; spkt3.Index = cpkt.Index; spkt3.SessionId = this.character.id; this.Send((byte[])spkt3); } //Preprocess packet SMSG_ITEMTOGGLE spkt = new SMSG_ITEMTOGGLE(); spkt.Container = cpkt.Container; spkt.SkillMessage = (byte)argument.Result; spkt.Index = cpkt.Index; spkt.SkillID = cpkt.SkillID; spkt.SkillType = cpkt.SkillType; spkt.SourceActor = this.character.id; spkt.TargetActor = cpkt.TargetActor; spkt.Value = argument.Damage; //Send packets in one-mighty blow Regiontree tree = this.character.currentzone.Regiontree; foreach (Character regionObject in tree.SearchActors(this.character, SearchFlags.Characters)) { if (character.client.isloaded == false || !Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position)) continue; spkt.SessionId = target.id; regionObject.client.Send((byte[])spkt); } } } catch (Exception) { Trace.TraceError("Error processing item skill"); } } } /// <summary> /// Learns a new skill from a skillbook /// </summary> /// <param name="cpkt"></param> private void CM_SKILLS_LEARNFROMSKILLBOOK(CMSG_SKILLLEARN cpkt) { byte result = 1; try { Saga.Factory.Spells.Info spellinfo; Rag2Item item = character.container[cpkt.Index]; if (item != null) { //Helpers predicates Predicate<Skill> FindSkill = delegate(Skill skill) { return skill.Id == item.info.skill; }; Predicate<Skill> FindPreviousSkill = delegate(Skill skill) { return skill.Id == item.info.skill - 1; }; //HELPER VARIABLES uint baseskill = (item.info.skill / 100) * 100 + 1; int newLength = character.container[cpkt.Index].count - 1; List<Skill> learnedSpells = this.character.learnedskills; Singleton.SpellManager.TryGetSpell(item.info.skill, out spellinfo); Skill CurrentSkill = learnedSpells.FindLast(FindSkill); Skill PreviousSkill = learnedSpells.FindLast(FindPreviousSkill); bool IsBaseSkill = item.info.skill == baseskill; //CHECK IF THE CURRENT JOB CAN LEARN THE SPELL if (item.info.JobRequirement[this.character.job - 1] > this.character.jlvl) { result = (byte)Generalerror.ConditionsNotMet; } //CHECK IF WE ALREADY LEARNED THE SPELL else if (CurrentSkill != null) { result = (byte)Generalerror.AlreadyLearntSkill; } //CHECK IF A PREVIOUS SKILL WAS FOUND else if (!IsBaseSkill && PreviousSkill == null) { result = (byte)Generalerror.PreviousSkillNotFound; } //CHECK SKILL EXP else if (PreviousSkill != null && PreviousSkill.Experience < PreviousSkill.info.maximumexperience) { result = (byte)Generalerror.NotEnoughSkillExperience; } else { //ADD A NEW SKILL if (IsBaseSkill) { //Passive skill bool canUse = Singleton.SpellManager.CanUse(this.character, spellinfo); if (spellinfo.skilltype == 2 && canUse) { Singleton.Additions.ApplyAddition(spellinfo.addition, this.character); int ActiveWeaponIndex = (this.character.weapons.ActiveWeaponIndex == 1) ? this.character.weapons.SeconairyWeaponIndex : this.character.weapons.PrimaryWeaponIndex; if (ActiveWeaponIndex < this.character.weapons.UnlockedWeaponSlots) { Weapon weapon = this.character.weapons[ActiveWeaponIndex]; if ((baseskill - 1) == weapon.Info.weapon_skill) { BattleStatus status = character._status; status.MaxWMAttack += (ushort)weapon.Info.max_magic_attack; status.MinWMAttack += (ushort)weapon.Info.min_magic_attack; status.MaxWPAttack += (ushort)weapon.Info.max_short_attack; status.MinWPAttack += (ushort)weapon.Info.min_short_attack; status.MaxWRAttack += (ushort)weapon.Info.max_range_attack; status.MinWRAttack += (ushort)weapon.Info.min_range_attack; status.Updates |= 2; } } } Singleton.Database.InsertNewSkill(this.character, item.info.skill, spellinfo.maximumexperience); CurrentSkill = new Skill(); CurrentSkill.info = spellinfo; CurrentSkill.Id = item.info.skill; CurrentSkill.Experience = spellinfo.maximumexperience; learnedSpells.Add(CurrentSkill); } //UPDATE A OLD SKILL else { //Passive skill if (spellinfo.skilltype == 2) { Saga.Factory.Spells.Info oldSpellinfo; Singleton.SpellManager.TryGetSpell(PreviousSkill.info.skillid, out oldSpellinfo); bool canUseOld = Singleton.SpellManager.CanUse(this.character, oldSpellinfo); bool canUseNew = Singleton.SpellManager.CanUse(this.character, spellinfo); if (canUseOld) { Singleton.Additions.DeapplyAddition(oldSpellinfo.addition, this.character); } if (canUseNew) { Singleton.Additions.ApplyAddition(spellinfo.addition, this.character); } } Singleton.Database.UpgradeSkill(this.character, PreviousSkill.info.skillid, item.info.skill, spellinfo.maximumexperience); PreviousSkill.info = spellinfo; PreviousSkill.Id = item.info.skill; PreviousSkill.Experience = spellinfo.maximumexperience; } SMSG_SKILLADD spkt2 = new SMSG_SKILLADD(); spkt2.Slot = 0; spkt2.SkillId = item.info.skill; spkt2.SessionId = this.character.id; this.Send((byte[])spkt2); if (newLength > 0) { this.character.container[cpkt.Index].count = newLength; SMSG_UPDATEITEM spkt = new SMSG_UPDATEITEM(); spkt.Amount = (byte)newLength; spkt.UpdateReason = 8; spkt.UpdateType = 4; spkt.Container = 2; spkt.SessionId = this.character.id; spkt.Index = cpkt.Index; this.Send((byte[])spkt); } else { this.character.container.RemoveAt(cpkt.Index); SMSG_DELETEITEM spkt = new SMSG_DELETEITEM(); spkt.UpdateReason = 8; spkt.Container = 2; spkt.Index = cpkt.Index; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } Common.Internal.CheckWeaponary(this.character); Tasks.LifeCycle.Update(this.character); result = 0; } } } finally { //OUTPUT THE RESULT SMSG_SKILLLEARN spkt = new SMSG_SKILLLEARN(); spkt.Result = result; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } /// <summary> /// Tries to add the selected skill /// </summary> /// <param name="cpkt"></param> private void CM_SKILLS_ADDSPECIAL(CMSG_SETSPECIALSKILL cpkt) { byte result = 1; try { byte slot = cpkt.Slot; byte NearestSlot = (byte)((slot - (slot % 4)) + 4); Saga.Factory.Spells.Info info; if (Singleton.SpellManager.TryGetSpell(cpkt.SkillID, out info)) { //Generate skill Skill skill = new Skill(); skill.info = info; skill.Id = cpkt.SkillID; //Skill must be a special skill if (info.special == 0) return; //Check if slots don't overlap if (slot + info.special > NearestSlot) return; //Check if slot isn't taken yet for (int i = 0; i < info.special; i++) if (this.character.SpecialSkills[slot + i] != null) return; //Set the bytes for (int i = 0; i < info.special; i++) this.character.SpecialSkills[slot + i] = skill; //Set the result to okay Common.Internal.CheckWeaponary(this.character); result = 0; } } finally { SMSG_SETSPECIALSKILL spkt = new SMSG_SETSPECIALSKILL(); spkt.Result = result; spkt.SkillID = cpkt.SkillID; spkt.Slot = cpkt.Slot; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } /// <summary> /// Tries to remove the selected skill /// </summary> /// <param name="cpkt"></param> private void CM_SKILLS_REMOVESPECIAL(CMSG_REMOVESPECIALSKILL cpkt) { byte result = 1; try { Skill skill = this.character.SpecialSkills[cpkt.Slot]; if (skill == null) return; if (skill.Id != cpkt.SkillID) return; for (int i = 0; i < skill.info.special; i++) { this.character.SpecialSkills[cpkt.Slot + i] = null; } Common.Internal.CheckWeaponary(this.character); result = 0; } catch (Exception e) { Console.WriteLine(e); } finally { SMSG_REMOVESPECIALSKILL spkt = new SMSG_REMOVESPECIALSKILL(); spkt.Result = result; spkt.SkillID = cpkt.SkillID; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } /// <summary> /// Checks if the user has enought money /// </summary> /// <param name="cpkt"></param> private void CM_SKILLS_REQUESTSPECIALSET(CMSG_WANTSETSPECIALLITY cpkt) { byte result = 0; uint req_zeny = 250; if (req_zeny > this.character.ZENY) { result = 1; } else { this.character.ZENY -= req_zeny; CommonFunctions.UpdateZeny(this.character); } SMSG_ADDSPECIALSKILLREPLY spkt = new SMSG_ADDSPECIALSKILLREPLY(); spkt.result = result; spkt.SessionId = this.character.id; this.Send((byte[])spkt); } } }
using System; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Events; using Marten.Testing.Events.Projections; using Marten.Testing.Harness; using Shouldly; using Weasel.Postgresql; using Xunit; namespace Marten.Testing.Events { [Collection("projections")] public class end_to_end_event_capture_and_fetching_the_stream_with_non_typed_streams_Tests : OneOffConfigurationsContext { public static TheoryData<DocumentTracking> SessionTypes = new TheoryData<DocumentTracking> { DocumentTracking.IdentityOnly, DocumentTracking.DirtyTracking }; public end_to_end_event_capture_and_fetching_the_stream_with_non_typed_streams_Tests() : base("projections") { } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); #endregion var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, e => ShouldBeTestExtensions.ShouldNotBe(e.Timestamp, default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public async Task capture_events_to_a_new_stream_and_fetch_the_events_back_async(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; await session.SaveChangesAsync(); #endregion var streamEvents = await session.Events.FetchStreamAsync(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, e => ShouldBeTestExtensions.ShouldNotBe(e.Timestamp, default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public async Task capture_events_to_a_new_stream_and_fetch_the_events_back_async_with_linq(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; await session.SaveChangesAsync(); #endregion var streamEvents = await Queryable.Where<IEvent>(session.Events.QueryAllRawEvents(), x => x.StreamId == id).OrderBy(x => x.Version).ToListAsync(); streamEvents.Count().ShouldBe(2); streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt(0).Version.ShouldBe(1); streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt(1).Version.ShouldBe(2); streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset))); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_sync_with_linq(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-aggregate-type var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); #endregion var streamEvents = Queryable.Where<IEvent>(session.Events.QueryAllRawEvents(), x => x.StreamId == id).OrderBy(x => x.Version).ToList(); streamEvents.Count().ShouldBe(2); streamEvents.ElementAt(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt(0).Version.ShouldBe(1); streamEvents.ElementAt(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt(1).Version.ShouldBe(2); streamEvents.Each(e => e.Timestamp.ShouldNotBe(default(DateTimeOffset))); } } [Fact] public void live_aggregate_equals_inlined_aggregate_without_hidden_contracts() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { //Note Id = questId, is we remove it from first message then AggregateStream will return party.Id=default(Guid) that is not equals to Load<QuestParty> result var started = new QuestStarted { /*Id = questId,*/ Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); } using (var session = store.OpenSession()) { var liveAggregate = session.Events.AggregateStream<QuestParty>(questId); var inlinedAggregate = session.Load<QuestParty>(questId); liveAggregate.Id.ShouldBe(inlinedAggregate.Id); inlinedAggregate.ToString().ShouldBe(liveAggregate.ToString()); } } [Fact] public void open_persisted_stream_in_new_store_with_same_settings() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { //Note "Id = questId" @see live_aggregate_equals_inlined_aggregate... var started = new QuestStarted { Id = questId, Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); } // events-aggregate-on-the-fly - works with same store using (var session = store.OpenSession()) { // questId is the id of the stream var party = session.Events.AggregateStream<QuestParty>(questId); party.Id.ShouldBe(questId); SpecificationExtensions.ShouldNotBeNull(party); var party_at_version_3 = session.Events .AggregateStream<QuestParty>(questId, 3); SpecificationExtensions.ShouldNotBeNull(party_at_version_3); var party_yesterday = session.Events .AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1)); party_yesterday.ShouldBeNull(); } using (var session = store.OpenSession()) { var party = session.Load<QuestParty>(questId); party.Id.ShouldBe(questId); } var newStore = InitStore("event_store", false); //Inline is working using (var session = store.OpenSession()) { var party = session.Load<QuestParty>(questId); SpecificationExtensions.ShouldNotBeNull(party); } //GetAll using (var session = store.OpenSession()) { var parties = session.Events.QueryRawEventDataOnly<QuestParty>().ToArray<QuestParty>(); foreach (var party in parties) { SpecificationExtensions.ShouldNotBeNull(party); } } //This AggregateStream fail with NPE using (var session = newStore.OpenSession()) { // questId is the id of the stream var party = session.Events.AggregateStream<QuestParty>(questId);//Here we get NPE party.Id.ShouldBe(questId); var party_at_version_3 = session.Events .AggregateStream<QuestParty>(questId, 3); party_at_version_3.Id.ShouldBe(questId); var party_yesterday = session.Events .AggregateStream<QuestParty>(questId, timestamp: DateTime.UtcNow.AddDays(-1)); party_yesterday.ShouldBeNull(); } } [Fact] public void query_before_saving() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { var parties = session.Query<QuestParty>().ToArray<QuestParty>(); parties.Length.ShouldBeLessThanOrEqualTo(0); } //This SaveChanges will fail with missing method (ro collection configured?) using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); session.SaveChanges(); var party = session.Events.AggregateStream<QuestParty>(questId); ShouldBeTestExtensions.ShouldBe(party.Id, questId); } } [Fact] public async Task aggregate_stream_async_has_the_id() { var store = InitStore("event_store"); var questId = Guid.NewGuid(); using (var session = store.OpenSession()) { var parties = await QueryableExtensions.ToListAsync<QuestParty>(session.Query<QuestParty>()); parties.Count.ShouldBeLessThanOrEqualTo(0); } //This SaveChanges will fail with missing method (ro collection configured?) using (var session = store.OpenSession()) { var started = new QuestStarted { Name = "Destroy the One Ring" }; var joined1 = new MembersJoined(1, "Hobbiton", "Frodo", "Merry"); session.Events.StartStream(questId, started, joined1); await session.SaveChangesAsync(); var party = await session.Events.AggregateStreamAsync<QuestParty>(questId); party.Id.ShouldBe(questId); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided( DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { #region sample_start-stream-with-existing-guid var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined, departed); session.SaveChanges(); #endregion var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); streamEvents.Count<IEvent>().ShouldBe(2); streamEvents.ElementAt<IEvent>(0).Data.ShouldBeOfType<MembersJoined>(); streamEvents.ElementAt<IEvent>(0).Version.ShouldBe(1); streamEvents.ElementAt<IEvent>(1).Data.ShouldBeOfType<MembersDeparted>(); streamEvents.ElementAt<IEvent>(1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_an_existing_stream_and_fetch_the_events_back(DocumentTracking sessionType) { var store = InitStore(); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { session.Events.StartStream(id, started); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; session.Events.Append(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(3); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<QuestStarted>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 2).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 2).Version.ShouldBe(3); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = session.Events.StartStream(joined, departed).Id; session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_new_stream_and_fetch_the_events_back_with_stream_id_provided_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); GenericEnumerableExtensions.Each<IEvent>(streamEvents, x => SpecificationExtensions.ShouldBeGreaterThan(x.Sequence, 0L)); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_a_non_existing_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); using (var session = store.OpenSession(sessionType)) { var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var id = Guid.NewGuid(); session.Events.StartStream(id, joined); session.Events.Append(id, departed); session.SaveChanges(); var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_events_to_an_existing_stream_and_fetch_the_events_back_in_another_database_schema( DocumentTracking sessionType) { var store = InitStore("event_store"); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { session.Events.StartStream(id, started); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { #region sample_append-events var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; session.Events.Append(id, joined, departed); session.SaveChanges(); #endregion var streamEvents = session.Events.FetchStream(id); Enumerable.Count<IEvent>(streamEvents).ShouldBe(3); Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<QuestStarted>(); Enumerable.ElementAt<IEvent>(streamEvents, 0).Version.ShouldBe(1); Enumerable.ElementAt<IEvent>(streamEvents, 1).Data.ShouldBeOfType<MembersJoined>(); Enumerable.ElementAt<IEvent>(streamEvents, 1).Version.ShouldBe(2); Enumerable.ElementAt<IEvent>(streamEvents, 2).Data.ShouldBeOfType<MembersDeparted>(); Enumerable.ElementAt<IEvent>(streamEvents, 2).Version.ShouldBe(3); } } [Theory] [MemberData(nameof(SessionTypes))] public void assert_on_max_event_id_on_event_stream_append( DocumentTracking sessionType) { var store = InitStore("event_store"); var id = Guid.NewGuid(); var started = new QuestStarted(); using (var session = store.OpenSession(sessionType)) { #region sample_append-events-assert-on-eventid session.Events.StartStream(id, started); session.SaveChanges(); var joined = new MembersJoined { Members = new[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; // Events are appended into the stream only if the maximum event id for the stream // would be 3 after the append operation. session.Events.Append(id, 3, joined, departed); session.SaveChanges(); #endregion } } [Theory] [MemberData(nameof(SessionTypes))] public void capture_immutable_events(DocumentTracking sessionType) { var store = InitStore(); var id = Guid.NewGuid(); var immutableEvent = new ImmutableEvent(id, "some-name"); using (var session = store.OpenSession(sessionType)) { session.Events.Append(id, immutableEvent); session.SaveChanges(); } using (var session = store.OpenSession(sessionType)) { var streamEvents = session.Events.FetchStream(id); ShouldBeTestExtensions.ShouldBe(streamEvents.Count, 1); var @event = Enumerable.ElementAt<IEvent>(streamEvents, 0).Data.ShouldBeOfType<ImmutableEvent>(); @event.Id.ShouldBe(id); @event.Name.ShouldBe("some-name"); } } private DocumentStore InitStore(string databaseSchema = null, bool cleanSchema = true) { var store = StoreOptions(_ => { if (databaseSchema != null) { _.Events.DatabaseSchemaName = databaseSchema; } _.AutoCreateSchemaObjects = AutoCreate.All; _.Connection(ConnectionSource.ConnectionString); _.Projections.SelfAggregate<QuestParty>(); _.Events.AddEventType(typeof(MembersJoined)); _.Events.AddEventType(typeof(MembersDeparted)); _.Events.AddEventType(typeof(QuestStarted)); }, cleanSchema); return store; } } }
// 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 is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Char : IComparable, IComparable<Char>, IEquatable<Char>, IConvertible { // // Member Variables // private char m_value; // Do not rename (binary serialization) // // Public Constants // // The maximum character value. public const char MaxValue = (char)0xFFFF; // The minimum character value. public const char MinValue = (char)0x00; // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. private static readonly byte[] s_categoryForLatin1 = { (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1(char ch) { return (ch <= '\x00ff'); } // Return true for all characters below or equal U+007f, which is ASCII. private static bool IsAscii(char ch) { return (ch <= '\x007f'); } // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(s_categoryForLatin1[(int)ch]); } // // Private Constants // // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals(Object obj) { if (!(obj is Char)) { return false; } return (m_value == ((Char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(Char obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // [Pure] public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Char)) { throw new ArgumentException(SR.Arg_MustBeChar); } return (m_value - ((Char)value).m_value); } [Pure] public int CompareTo(Char value) { return (m_value - value); } // Overrides System.Object.ToString. [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. [Pure] public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(String s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } public static bool TryParse(String s, out Char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } // // Static Methods // /*=================================ISDIGIT====================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. [Pure] public static bool IsDigit(char c) { if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); } /*=================================CheckLetter===================================== ** Check if the specified UnicodeCategory belongs to the letter categories. ==============================================================================*/ internal static bool CheckLetter(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.UppercaseLetter): case (UnicodeCategory.LowercaseLetter): case (UnicodeCategory.TitlecaseLetter): case (UnicodeCategory.ModifierLetter): case (UnicodeCategory.OtherLetter): return (true); } return (false); } /*=================================ISLETTER===================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. [Pure] public static bool IsLetter(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c))); } private static bool IsWhiteSpaceLatin1(char c) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <contorl> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE return c == ' ' || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085'; } /*===============================ISWHITESPACE=================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. [Pure] public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return (IsWhiteSpaceLatin1(c)); } return CharUnicodeInfo.IsWhiteSpace(c); } /*===================================IsUpper==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an uppercase character. ==============================================================================*/ // Determines whether a character is upper-case. [Pure] public static bool IsUpper(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } /*===================================IsLower==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an lowercase character. ==============================================================================*/ // Determines whether a character is lower-case. [Pure] public static bool IsLower(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } internal static bool CheckPunctuation(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: return (true); } return (false); } /*================================IsPunctuation================================= **Arguments: c -- the characater to be checked. **Returns: True if c is an punctuation mark ==============================================================================*/ // Determines whether a character is a punctuation mark. [Pure] public static bool IsPunctuation(char c) { if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c))); } /*=================================CheckLetterOrDigit===================================== ** Check if the specified UnicodeCategory belongs to the letter or digit categories. ==============================================================================*/ internal static bool CheckLetterOrDigit(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.DecimalDigitNumber: return (true); } return (false); } // Determines whether a character is a letter or a digit. [Pure] public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); } return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c))); } /*===================================ToUpper==================================== ** ==============================================================================*/ // Converts a character to upper-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToUpper(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); return culture.TextInfo.ToUpper(c); } /*=================================TOUPPER====================================== **A wrapper for Char.toUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to upper-case for the default culture. // public static char ToUpper(char c) { return ToUpper(c, CultureInfo.CurrentCulture); } // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { return ToUpper(c, CultureInfo.InvariantCulture); } /*===================================ToLower==================================== ** ==============================================================================*/ // Converts a character to lower-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToLower(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); return culture.TextInfo.ToLower(c); } /*=================================TOLOWER====================================== **A wrapper for Char.toLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to lower-case for the default culture. public static char ToLower(char c) { return ToLower(c, CultureInfo.CurrentCulture); } // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { return ToLower(c, CultureInfo.InvariantCulture); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Char; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); } char IConvertible.ToChar(IFormatProvider provider) { return m_value; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Single")); } double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } public static bool IsControl(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } public static bool IsControl(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control); } public static bool IsDigit(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } public static bool IsLetter(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { c |= (char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsLetterOrDigit(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } public static bool IsLower(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter); } /*=================================CheckNumber===================================== ** Check if the specified UnicodeCategory belongs to the number categories. ==============================================================================*/ internal static bool CheckNumber(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.DecimalDigitNumber): case (UnicodeCategory.LetterNumber): case (UnicodeCategory.OtherNumber): return (true); } return (false); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsNumber(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index))); } //////////////////////////////////////////////////////////////////////// // // IsPunctuation // // Determines if the given character is a punctuation character. // //////////////////////////////////////////////////////////////////////// public static bool IsPunctuation(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index))); } /*================================= CheckSeparator ============================ ** Check if the specified UnicodeCategory belongs to the seprator categories. ==============================================================================*/ internal static bool CheckSeparator(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: return (true); } return (false); } private static bool IsSeparatorLatin1(char c) { // U+00a0 = NO-BREAK SPACE // There is no LineSeparator or ParagraphSeparator in Latin 1 range. return (c == '\x0020' || c == '\x00a0'); } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSeparator(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index))); } [Pure] public static bool IsSurrogate(char c) { return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } [Pure] public static bool IsSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsSurrogate(s[index])); } /*================================= CheckSymbol ============================ ** Check if the specified UnicodeCategory belongs to the symbol categories. ==============================================================================*/ internal static bool CheckSymbol(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.MathSymbol): case (UnicodeCategory.CurrencySymbol): case (UnicodeCategory.ModifierSymbol): case (UnicodeCategory.OtherSymbol): return (true); } return (false); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSymbol(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsUpper(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } public static bool IsWhiteSpace(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return IsWhiteSpaceLatin1(s[index]); } return CharUnicodeInfo.IsWhiteSpace(s, index); } public static UnicodeCategory GetUnicodeCategory(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c)); } return CharUnicodeInfo.InternalGetUnicodeCategory(c); } public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return (GetLatin1UnicodeCategory(s[index])); } return CharUnicodeInfo.InternalGetUnicodeCategory(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(String s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return CharUnicodeInfo.GetNumericValue(s, index); } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ [Pure] public static bool IsHighSurrogate(char c) { return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } [Pure] public static bool IsHighSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsHighSurrogate(s[index])); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ [Pure] public static bool IsLowSurrogate(char c) { return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } [Pure] public static bool IsLowSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsLowSurrogate(s[index])); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ [Pure] public static bool IsSurrogatePair(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index + 1])); } return (false); } [Pure] public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) && (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END)); } internal const int UNICODE_PLANE00_END = 0x00ffff; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode. // Plane 16 contains 0x100000 ~ 0x10ffff. internal const int UNICODE_PLANE16_END = 0x10ffff; internal const int HIGH_SURROGATE_START = 0x00d800; internal const int LOW_SURROGATE_END = 0x00dfff; /*================================= ConvertFromUtf32 ============================ ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ public static String ConvertFromUtf32(int utf32) { // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They // are considered as irregular code unit sequence, but they are not illegal. if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) { throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32); } Contract.EndContractBlock(); if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. return (Char.ToString((char)utf32)); } unsafe { // This is a supplementary character. Convert it to a surrogate pair in UTF-16. utf32 -= UNICODE_PLANE01_START; uint surrogate = 0; // allocate 2 chars worth of stack space char* address = (char*)&surrogate; address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START); address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START); return new string(address, 0, 2); } } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { if (!IsHighSurrogate(highSurrogate)) { throw new ArgumentOutOfRangeException(nameof(highSurrogate), SR.ArgumentOutOfRange_InvalidHighSurrogate); } if (!IsLowSurrogate(lowSurrogate)) { throw new ArgumentOutOfRangeException(nameof(lowSurrogate), SR.ArgumentOutOfRange_InvalidLowSurrogate); } Contract.EndContractBlock(); return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START); } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if (temp1 <= 0x3ff) { // Found a high surrogate. if (index < s.Length - 1) { int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Found a high surrogate at the end of the string. throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s)); } } else { // Find a low surrogate at the character pointed by index. throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), nameof(s)); } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } }
// // ClassicTrackInfoDisplay.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-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 Gdk; using Gtk; using Cairo; using Hyena.Gui; using Banshee.Collection; using Banshee.Collection.Gui; namespace Banshee.Gui.Widgets { public class ClassicTrackInfoDisplay : TrackInfoDisplay { private Gdk.Window event_window; private ArtworkPopup popup; private uint popup_timeout_id; private bool in_popup; private bool in_thumbnail_region; private Pango.Layout first_line_layout; private Pango.Layout second_line_layout; public ClassicTrackInfoDisplay () : base () { ArtworkSpacing = 10; } protected ClassicTrackInfoDisplay (IntPtr native) : base (native) { } protected override void Dispose (bool disposing) { if (disposing) { HidePopup (); } base.Dispose (disposing); } protected override int ArtworkSizeRequest { get { return artwork_size ?? base.ArtworkSizeRequest; } } private int? artwork_size; public int ArtworkSize { get { return ArtworkSizeRequest; } set { artwork_size = value; } } public int ArtworkSpacing { get; set; } #region Widget Window Management protected override void OnRealized () { base.OnRealized (); WindowAttr attributes = new WindowAttr (); attributes.WindowType = Gdk.WindowType.Child; attributes.X = Allocation.X; attributes.Y = Allocation.Y; attributes.Width = Allocation.Width; attributes.Height = Allocation.Height; attributes.Wclass = WindowWindowClass.InputOnly; attributes.EventMask = (int)( EventMask.PointerMotionMask | EventMask.EnterNotifyMask | EventMask.LeaveNotifyMask | EventMask.ExposureMask); WindowAttributesType attributes_mask = WindowAttributesType.X | WindowAttributesType.Y | WindowAttributesType.Wmclass; event_window = new Gdk.Window (Window, attributes, attributes_mask); event_window.UserData = Handle; } protected override void OnUnrealized () { IsRealized = false; event_window.UserData = IntPtr.Zero; event_window.Destroy (); event_window = null; base.OnUnrealized (); } protected override void OnMapped () { event_window.Show (); base.OnMapped (); } protected override void OnUnmapped () { event_window.Hide (); base.OnUnmapped (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); if (IsRealized) { event_window.MoveResize (allocation); } } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { minimum_height = ComputeWidgetHeight (); natural_height = minimum_height; } private int ComputeWidgetHeight () { int width, height; Pango.Layout layout = new Pango.Layout (PangoContext); layout.SetText ("W"); layout.GetPixelSize (out width, out height); layout.Dispose (); return 2 * height; } protected override void OnThemeChanged () { if (first_line_layout != null) { first_line_layout.FontDescription.Dispose (); first_line_layout.Dispose (); first_line_layout = null; } if (second_line_layout != null) { second_line_layout.FontDescription.Dispose (); second_line_layout.Dispose (); second_line_layout = null; } } #endregion #region Drawing protected override void RenderTrackInfo (Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum) { if (track == null) { return; } double offset = ArtworkSizeRequest + ArtworkSpacing, y = 0; double x = offset; double width = Allocation.Width - offset; int fl_width, fl_height, sl_width, sl_height; int pango_width = (int)(width * Pango.Scale.PangoScale); if (first_line_layout == null) { first_line_layout = CairoExtensions.CreateLayout (this, cr); first_line_layout.Ellipsize = Pango.EllipsizeMode.End; } if (second_line_layout == null) { second_line_layout = CairoExtensions.CreateLayout (this, cr); second_line_layout.Ellipsize = Pango.EllipsizeMode.End; } // Set up the text layouts first_line_layout.Width = pango_width; second_line_layout.Width = pango_width; // Compute the layout coordinates first_line_layout.SetMarkup (GetFirstLineText (track)); first_line_layout.GetPixelSize (out fl_width, out fl_height); second_line_layout.SetMarkup (GetSecondLineText (track)); second_line_layout.GetPixelSize (out sl_width, out sl_height); if (fl_height + sl_height > Allocation.Height) { SetSizeRequest (-1, fl_height + sl_height); } y = (Allocation.Height - (fl_height + sl_height)) / 2; // Render the layouts cr.Antialias = Cairo.Antialias.Default; if (renderTrack) { cr.MoveTo (x, y); cr.SetSourceColor (TextColor); PangoCairoHelper.ShowLayout (cr, first_line_layout); } if (!renderArtistAlbum) { return; } cr.MoveTo (x, y + fl_height); PangoCairoHelper.ShowLayout (cr, second_line_layout); } #endregion #region Interaction Events protected override bool OnEnterNotifyEvent (EventCrossing evnt) { in_thumbnail_region = evnt.X <= Allocation.Height; return ShowHideCoverArt (); } protected override bool OnLeaveNotifyEvent (EventCrossing evnt) { in_thumbnail_region = false; return ShowHideCoverArt (); } protected override bool OnMotionNotifyEvent (EventMotion evnt) { in_thumbnail_region = evnt.X <= Allocation.Height; return ShowHideCoverArt (); } private void OnPopupEnterNotifyEvent (object o, EnterNotifyEventArgs args) { in_popup = true; } private void OnPopupLeaveNotifyEvent (object o, LeaveNotifyEventArgs args) { in_popup = false; HidePopup (); } private bool ShowHideCoverArt () { if (!in_thumbnail_region) { if (popup_timeout_id > 0) { GLib.Source.Remove (popup_timeout_id); popup_timeout_id = 0; } GLib.Timeout.Add (100, delegate { if (!in_popup) { HidePopup (); } return false; }); } else { if (popup_timeout_id > 0) { return false; } popup_timeout_id = GLib.Timeout.Add (500, delegate { if (in_thumbnail_region) { UpdatePopup (); } popup_timeout_id = 0; return false; }); } return true; } #endregion #region Popup Window protected override void OnArtworkChanged () { UpdatePopup (); } private bool UpdatePopup () { if (CurrentTrack == null || ArtworkManager == null || !in_thumbnail_region) { HidePopup (); return false; } Gdk.Pixbuf pixbuf = ArtworkManager.LookupPixbuf (CurrentTrack.ArtworkId); if (pixbuf == null) { HidePopup (); return false; } if (popup == null) { popup = new ArtworkPopup (); popup.EnterNotifyEvent += OnPopupEnterNotifyEvent; popup.LeaveNotifyEvent += OnPopupLeaveNotifyEvent; } popup.Label = String.Format ("{0} - {1}", CurrentTrack.DisplayArtistName, CurrentTrack.DisplayAlbumTitle); if (popup.Image != null) { ArtworkManager.DisposePixbuf (popup.Image); } popup.Image = pixbuf; if (in_thumbnail_region) { popup.Show (); } return true; } private void HidePopup () { if (popup != null) { ArtworkManager.DisposePixbuf (popup.Image); popup.Destroy (); popup.EnterNotifyEvent -= OnPopupEnterNotifyEvent; popup.LeaveNotifyEvent -= OnPopupLeaveNotifyEvent; popup = null; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; //using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// An immutable queue. /// </summary> /// <typeparam name="T">The type of elements stored in the queue.</typeparam> [DebuggerDisplay("IsEmpty = {IsEmpty}")] [DebuggerTypeProxy(typeof(ImmutableQueueDebuggerProxy<>))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")] public sealed class ImmutableQueue<T> : IImmutableQueue<T> { /// <summary> /// The singleton empty queue. /// </summary> /// <remarks> /// Additional instances representing the empty queue may exist on deserialized instances. /// Actually since this queue is a struct, instances don't even apply and there are no singletons. /// </remarks> private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty); /// <summary> /// The end of the queue that enqueued elements are pushed onto. /// </summary> private readonly ImmutableStack<T> _backwards; /// <summary> /// The end of the queue from which elements are dequeued. /// </summary> private readonly ImmutableStack<T> _forwards; /// <summary> /// Backing field for the <see cref="BackwardsReversed"/> property. /// </summary> private ImmutableStack<T> _backwardsReversed; /// <summary> /// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class. /// </summary> /// <param name="forward">The forward stack.</param> /// <param name="backward">The backward stack.</param> private ImmutableQueue(ImmutableStack<T> forward, ImmutableStack<T> backward) { Requires.NotNull(forward, "forward"); Requires.NotNull(backward, "backward"); _forwards = forward; _backwards = backward; _backwardsReversed = null; } /// <summary> /// Gets the empty queue. /// </summary> public ImmutableQueue<T> Clear() { Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty); Contract.Assume(s_EmptyField.IsEmpty); return Empty; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _forwards.IsEmpty && _backwards.IsEmpty; } } /// <summary> /// Gets the empty queue. /// </summary> public static ImmutableQueue<T> Empty { get { Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty); Contract.Assume(s_EmptyField.IsEmpty); return s_EmptyField; } } /// <summary> /// Gets an empty queue. /// </summary> IImmutableQueue<T> IImmutableQueue<T>.Clear() { Contract.Assume(s_EmptyField.IsEmpty); return this.Clear(); } /// <summary> /// Gets the reversed <see cref="_backwards"/> stack. /// </summary> private ImmutableStack<T> BackwardsReversed { get { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); // Although this is a lazy-init pattern, no lock is required because // this instance is immutable otherwise, and a double-assignment from multiple // threads is harmless. if (_backwardsReversed == null) { _backwardsReversed = _backwards.Reverse(); } return _backwardsReversed; } } /// <summary> /// Gets the element at the front of the queue. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] public T Peek() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } return _forwards.Peek(); } /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] public ImmutableQueue<T> Enqueue(T value) { Contract.Ensures(!Contract.Result<ImmutableQueue<T>>().IsEmpty); if (this.IsEmpty) { return new ImmutableQueue<T>(ImmutableStack<T>.Empty.Push(value), ImmutableStack<T>.Empty); } else { return new ImmutableQueue<T>(_forwards, _backwards.Push(value)); } } /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value) { return this.Enqueue(value); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] public ImmutableQueue<T> Dequeue() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } ImmutableStack<T> f = _forwards.Pop(); if (!f.IsEmpty) { return new ImmutableQueue<T>(f, _backwards); } else if (_backwards.IsEmpty) { return ImmutableQueue<T>.Empty; } else { return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty); } } /// <summary> /// Retrieves the item at the head of the queue, and returns a queue with the head element removed. /// </summary> /// <param name="value">Receives the value from the head of the queue.</param> /// <returns>The new queue with the head element removed.</returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] [Pure] public ImmutableQueue<T> Dequeue(out T value) { value = this.Peek(); return this.Dequeue(); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Dequeue() { return this.Dequeue(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An <see cref="Enumerator"/> that can be used to iterate through the collection. /// </returns> [Pure] public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new EnumeratorObject(this); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator IEnumerable.GetEnumerator() { return new EnumeratorObject(this); } /// <summary> /// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>. /// </summary> //[EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator { /// <summary> /// The original queue being enumerated. /// </summary> private readonly ImmutableQueue<T> _originalQueue; /// <summary> /// The remaining forwards stack of the queue being enumerated. /// </summary> private ImmutableStack<T> _remainingForwardsStack; /// <summary> /// The remaining backwards stack of the queue being enumerated. /// Its order is reversed when the field is first initialized. /// </summary> private ImmutableStack<T> _remainingBackwardsStack; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="queue">The queue to enumerate.</param> internal Enumerator(ImmutableQueue<T> queue) { _originalQueue = queue; // The first call to MoveNext will initialize these. _remainingForwardsStack = null; _remainingBackwardsStack = null; } /// <summary> /// The current element. /// </summary> public T Current { get { if (_remainingForwardsStack == null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); } if (!_remainingForwardsStack.IsEmpty) { return _remainingForwardsStack.Peek(); } else if (!_remainingBackwardsStack.IsEmpty) { return _remainingBackwardsStack.Peek(); } else { // We've advanced beyond the end of the queue. throw new InvalidOperationException(); } } } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { if (_remainingForwardsStack == null) { // This is the initial step. // Empty queues have no forwards or backwards _remainingForwardsStack = _originalQueue._forwards; _remainingBackwardsStack = _originalQueue.BackwardsReversed; } else if (!_remainingForwardsStack.IsEmpty) { _remainingForwardsStack = _remainingForwardsStack.Pop(); } else if (!_remainingBackwardsStack.IsEmpty) { _remainingBackwardsStack = _remainingBackwardsStack.Pop(); } return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty; } } /// <summary> /// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>. /// </summary> private class EnumeratorObject : IEnumerator<T> { /// <summary> /// The original queue being enumerated. /// </summary> private readonly ImmutableQueue<T> _originalQueue; /// <summary> /// The remaining forwards stack of the queue being enumerated. /// </summary> private ImmutableStack<T> _remainingForwardsStack; /// <summary> /// The remaining backwards stack of the queue being enumerated. /// Its order is reversed when the field is first initialized. /// </summary> private ImmutableStack<T> _remainingBackwardsStack; /// <summary> /// A value indicating whether this enumerator has been disposed. /// </summary> private bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="queue">The queue to enumerate.</param> internal EnumeratorObject(ImmutableQueue<T> queue) { _originalQueue = queue; } /// <summary> /// The current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); if (_remainingForwardsStack == null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); } if (!_remainingForwardsStack.IsEmpty) { return _remainingForwardsStack.Peek(); } else if (!_remainingBackwardsStack.IsEmpty) { return _remainingBackwardsStack.Peek(); } else { // We've advanced beyond the end of the queue. throw new InvalidOperationException(); } } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_remainingForwardsStack == null) { // This is the initial step. // Empty queues have no forwards or backwards _remainingForwardsStack = _originalQueue._forwards; _remainingBackwardsStack = _originalQueue.BackwardsReversed; } else if (!_remainingForwardsStack.IsEmpty) { _remainingForwardsStack = _remainingForwardsStack.Pop(); } else if (!_remainingBackwardsStack.IsEmpty) { _remainingBackwardsStack = _remainingBackwardsStack.Pop(); } return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _remainingBackwardsStack = null; _remainingForwardsStack = null; } /// <summary> /// Disposes this instance. /// </summary> public void Dispose() { _disposed = true; } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this /// enumerator has already been disposed. /// </summary> private void ThrowIfDisposed() { if (_disposed) { Validation.Requires.FailObjectDisposed(this); } } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableQueueDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableQueue<T> _queue; /// <summary> /// The simple view of the collection. /// </summary> private T[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableQueueDebuggerProxy{T}"/> class. /// </summary> /// <param name="queue">The collection to display in the debugger</param> public ImmutableQueueDebuggerProxy(ImmutableQueue<T> queue) { _queue = queue; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (_contents == null) { _contents = _queue.ToArray(); } return _contents; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpOverrideEqualsAndOperatorEqualsOnValueTypesFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicOverrideEqualsAndOperatorEqualsOnValueTypesFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class OverrideEqualsAndOperatorEqualsOnValueTypesFixerTests { [Fact] public async Task CSharpCodeFixNoEqualsOverrideOrEqualityOperators() { await VerifyCS.VerifyCodeFixAsync(@" public struct A { public int X; } ", new[] { VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule).WithSpan(2, 15, 2, 16).WithArguments("A"), VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 15, 2, 16).WithArguments("A"), }, @" public struct A { public int X; public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public static bool operator ==(A left, A right) { return left.Equals(right); } public static bool operator !=(A left, A right) { return !(left == right); } } "); } [Fact] public async Task CSharpCodeFixNoEqualsOverride() { await VerifyCS.VerifyCodeFixAsync(@" public struct A { public static bool operator ==(A left, A right) { throw new System.NotImplementedException(); } public static bool operator !=(A left, A right) { throw new System.NotImplementedException(); } } ", VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule).WithSpan(2, 15, 2, 16).WithArguments("A"), @" public struct A { public static bool operator ==(A left, A right) { throw new System.NotImplementedException(); } public static bool operator !=(A left, A right) { throw new System.NotImplementedException(); } public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } } "); } [Fact] public async Task CSharpCodeFixNoEqualityOperator() { await VerifyCS.VerifyCodeFixAsync(@" public struct A { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public static bool operator {|CS0216:!=|}(A left, A right) // error CS0216: The operator requires a matching operator '==' to also be defined { throw new System.NotImplementedException(); } } ", VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 15, 2, 16).WithArguments("A"), @" public struct A { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public static bool operator !=(A left, A right) // error CS0216: The operator requires a matching operator '==' to also be defined { throw new System.NotImplementedException(); } public static bool operator ==(A left, A right) { return left.Equals(right); } } "); } [Fact] public async Task CSharpCodeFixNoInequalityOperator() { await VerifyCS.VerifyCodeFixAsync(@" public struct A { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public static bool operator {|CS0216:==|}(A left, A right) // error CS0216: The operator requires a matching operator '!=' to also be defined { throw new System.NotImplementedException(); } } ", VerifyCS.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 15, 2, 16).WithArguments("A"), @" public struct A { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public static bool operator ==(A left, A right) // error CS0216: The operator requires a matching operator '!=' to also be defined { throw new System.NotImplementedException(); } public static bool operator !=(A left, A right) { return !(left == right); } } "); } [Fact] public async Task BasicCodeFixNoEqualsOverrideOrEqualityOperators() { await VerifyVB.VerifyCodeFixAsync(@" Public Structure A Public X As Integer End Structure ", new[] { VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule).WithSpan(2, 18, 2, 19).WithArguments("A"), VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 18, 2, 19).WithArguments("A"), }, @" Public Structure A Public X As Integer Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function Public Shared Operator =(left As A, right As A) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As A, right As A) As Boolean Return Not left = right End Operator End Structure "); } [Fact] public async Task BasicCodeFixNoEqualsOverride() { await VerifyVB.VerifyCodeFixAsync(@" Public Structure A Public Shared Operator =(left As A, right As A) As Boolean Throw New System.NotImplementedException() End Operator Public Shared Operator <>(left As A, right As A) As Boolean Throw New System.NotImplementedException() End Operator End Structure ", VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.EqualsRule).WithSpan(2, 18, 2, 19).WithArguments("A"), @" Public Structure A Public Shared Operator =(left As A, right As A) As Boolean Throw New System.NotImplementedException() End Operator Public Shared Operator <>(left As A, right As A) As Boolean Throw New System.NotImplementedException() End Operator Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function End Structure "); } [Fact] public async Task BasicCodeFixNoEqualityOperator() { await VerifyVB.VerifyCodeFixAsync(@" Public Structure A Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function Public Shared Operator {|BC33033:<>|}(left As A, right As A) As Boolean ' error BC33033: Matching '=' operator is required Throw New System.NotImplementedException() End Operator End Structure ", VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 18, 2, 19).WithArguments("A"), @" Public Structure A Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function Public Shared Operator <>(left As A, right As A) As Boolean ' error BC33033: Matching '=' operator is required Throw New System.NotImplementedException() End Operator Public Shared Operator =(left As A, right As A) As Boolean Return left.Equals(right) End Operator End Structure "); } [Fact] public async Task BasicCodeFixNoInequalityOperator() { await VerifyVB.VerifyCodeFixAsync(@" Public Structure A Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function Public Shared Operator {|BC33033:=|}(left As A, right As A) As Boolean ' error BC33033: Matching '<>' operator is required Throw New System.NotImplementedException() End Operator End Structure ", VerifyVB.Diagnostic(OverrideEqualsAndOperatorEqualsOnValueTypesAnalyzer.OpEqualityRule).WithSpan(2, 18, 2, 19).WithArguments("A"), @" Public Structure A Public Overrides Function Equals(obj As Object) As Boolean Throw New System.NotImplementedException() End Function Public Overrides Function GetHashCode() As Integer Throw New System.NotImplementedException() End Function Public Shared Operator =(left As A, right As A) As Boolean ' error BC33033: Matching '<>' operator is required Throw New System.NotImplementedException() End Operator Public Shared Operator <>(left As A, right As A) As Boolean Return Not left = right End Operator End Structure "); } } }
// // Copyright 2012, Xamarin 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 EmployeeDirectory.Data; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace EmployeeDirectory.ViewModels { public class PersonViewModel : ViewModelBase { readonly IFavoritesRepository favoritesRepository; public PersonViewModel (Person person, IFavoritesRepository favoritesRepository) { if (person == null) { throw new ArgumentNullException ("person"); } if (favoritesRepository == null) { throw new ArgumentNullException ("favoritesRepository"); } Person = person; this.favoritesRepository = favoritesRepository; PropertyGroups = new ObservableCollection<PropertyGroup> (); var general = new PropertyGroup ("General"); general.Add ("Title", person.Title, PropertyType.Generic); general.Add ("Department", person.Department, PropertyType.Generic); general.Add ("Company", person.Company, PropertyType.Generic); general.Add ("Manager", person.Manager, PropertyType.Generic); general.Add ("Description", person.Description, PropertyType.Generic); if (general.Properties.Count > 0) { PropertyGroups.Add (general); } var phone = new PropertyGroup ("Phone"); foreach (var p in person.TelephoneNumbers) { phone.Add ("Phone", p, PropertyType.Phone); } foreach (var p in person.HomeNumbers) { phone.Add ("Home", p, PropertyType.Phone); } foreach (var p in person.MobileNumbers) { phone.Add ("Mobile", p, PropertyType.Phone); } if (phone.Properties.Count > 0) { PropertyGroups.Add (phone); } var online = new PropertyGroup ("Online"); online.Add ("Email", person.Email, PropertyType.Email); online.Add ("WebPage", CleanUrl (person.WebPage), PropertyType.Url); online.Add ("Twitter", CleanTwitter (person.Twitter), PropertyType.Twitter); if (online.Properties.Count > 0) { PropertyGroups.Add (online); } var address = new PropertyGroup ("Address"); address.Add ("Office", person.Office, PropertyType.Generic); address.Add ("Address", AddressString, PropertyType.Address); if (address.Properties.Count > 0) { PropertyGroups.Add (address); } } static string CleanUrl (string url) { var trimmed = (url ?? "").Trim (); if (trimmed.Length == 0) return ""; var upper = trimmed.ToUpperInvariant (); if (!upper.StartsWith ("HTTP")) { return "http://" + trimmed; } else { return trimmed; } } static string CleanTwitter (string username) { var trimmed = (username ?? "").Trim (); if (trimmed.Length == 0) return ""; if (!trimmed.StartsWith ("@")) { return "@" + trimmed; } else { return trimmed; } } #region View Data public Person Person { get; private set; } public ObservableCollection<PropertyGroup> PropertyGroups { get; private set; } public bool IsFavorite { get { return favoritesRepository.IsFavorite (Person); } } public bool IsNotFavorite { get { return !favoritesRepository.IsFavorite (Person); } } string AddressString { get { var sb = new StringBuilder (); if (!string.IsNullOrWhiteSpace (Person.Street)) { sb.AppendLine (Person.Street.Trim ()); } if (!string.IsNullOrWhiteSpace (Person.POBox)) { sb.AppendLine (Person.POBox.Trim ()); } if (!string.IsNullOrWhiteSpace (Person.City)) { sb.AppendLine (Person.City.Trim ()); } if (!string.IsNullOrWhiteSpace (Person.State)) { sb.AppendLine (Person.State.Trim ()); } if (!string.IsNullOrWhiteSpace (Person.PostalCode)) { sb.AppendLine (Person.PostalCode.Trim ()); } if (!string.IsNullOrWhiteSpace (Person.Country)) { sb.AppendLine (Person.Country.Trim ()); } return sb.ToString (); } } public class PropertyGroup : IEnumerable<Property> { public string Title { get; private set; } public ObservableCollection<Property> Properties { get; private set; } public PropertyGroup (string title) { Title = title; Properties = new ObservableCollection<Property> (); } public void Add (string name, string value, PropertyType type) { if (!string.IsNullOrWhiteSpace (value)) { Properties.Add (new Property (name, value, type)); } } IEnumerator<Property> IEnumerable<Property>.GetEnumerator () { return Properties.GetEnumerator (); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return Properties.GetEnumerator (); } } public class Property { public string Name { get; private set; } public string Value { get; private set; } public PropertyType Type { get; private set; } public Property (string name, string value, PropertyType type) { Name = name; Value = value.Trim (); Type = type; } public override string ToString () { return string.Format ("{0} = {1}", Name, Value); } } public enum PropertyType { Generic, Phone, Email, Url, Twitter, Address, } #endregion #region Commands public void ToggleFavorite () { if (favoritesRepository.IsFavorite (Person)) { favoritesRepository.Delete (Person); } else { favoritesRepository.InsertOrUpdate (Person); } OnPropertyChanged ("IsFavorite"); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerDouble() { var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToNearestIntegerDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerDouble testClass) { var result = Avx.RoundToNearestInteger(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector256<Double> _clsVar1; private Vector256<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearestIntegerDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleUnaryOpTest__RoundToNearestIntegerDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.RoundToNearestInteger( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.RoundToNearestInteger( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.RoundToNearestInteger( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble(); var result = Avx.RoundToNearestInteger(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.RoundToNearestInteger(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.RoundToNearestInteger(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[i], MidpointRounding.AwayFromZero))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.RoundToNearestInteger)}<Double>(Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; public class Pathfinder : MonoBehaviour { //Singleton private static Pathfinder instance; public static Pathfinder Instance { get { return instance; } private set {} } //Variables private Node[,] Map = null; public float Tilesize = 1; public float MaxFalldownHeight; public float ClimbLimit; public int HeuristicAggression; public float HighestPoint = 100F; public float LowestPoint = -50F; public Vector2 MapStartPosition; public Vector2 MapEndPosition; public List<string> DisallowedTags; public List<string> IgnoreTags; public bool MoveDiagonal = true; public bool DrawMapInEditor = false; public bool CheckFullTileSize = false; //FPS private float updateinterval = 1F; private int frames = 0; private float timeleft = 1F; private int FPS = 60; private int times = 0; private int averageFPS = 0; int maxSearchRounds = 0; //Queue path finding to not bottleneck it private List<QueuePath> queue = new List<QueuePath>(); //Set singleton! void Awake() { instance = this; } void Start () { if (Tilesize <= 0) { Tilesize = 1; } Pathfinder.Instance.CreateMap(); } float overalltimer = 0; int iterations = 0; //Go through one void Update () { timeleft -= Time.deltaTime; frames++; if (timeleft <= 0F) { FPS = frames; averageFPS += frames; times++; timeleft = updateinterval; frames = 0; } float timer = 0F; float maxtime = 1000/FPS; //Bottleneck prevention while(queue.Count > 0 && timer < maxtime) { Stopwatch sw = new Stopwatch(); sw.Start(); StartCoroutine(PathHandler(queue[0].startPos, queue[0].endPos, queue[0].storeRef)); //queue[0].storeRef.Invoke(FindPath(queue[0].startPos, queue[0].endPos)); queue.RemoveAt(0); sw.Stop(); //print("Timer: " + sw.ElapsedMilliseconds); timer += sw.ElapsedMilliseconds; overalltimer += sw.ElapsedMilliseconds; iterations++; } DrawMapLines(); } #region map //-------------------------------------------------INSTANIATE MAP-----------------------------------------------// private void CreateMap() { //Find positions for start and end of map int startX = (int)MapStartPosition.x; int startZ = (int)MapStartPosition.y; int endX = (int)MapEndPosition.x; int endZ = (int)MapEndPosition.y; //Find tile width and height int width = (int)((endX - startX) / Tilesize); int height = (int)((endZ - startZ) / Tilesize); //Set map up Map = new Node[width, height]; int size = width* height; SetListsSize(size); //Fill up Map for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float x = startX + (j * Tilesize) + (Tilesize / 2); //Position from where we raycast - X float y = startZ + (i * Tilesize) + (Tilesize / 2); //Position from where we raycast - Z int ID = (i * width) + j; //ID we give to our Node! float dist = Mathf.Abs(HighestPoint) + Mathf.Abs(LowestPoint); RaycastHit[] hit; if (CheckFullTileSize) { hit = Physics.SphereCastAll(new Vector3(x, HighestPoint, y), Tilesize / 2, Vector3.down, dist); } else { hit = Physics.SphereCastAll(new Vector3(x, HighestPoint, y), Tilesize / 16, Vector3.down, dist); } bool free = true; float maxY = -Mathf.Infinity; foreach(RaycastHit h in hit) { if (DisallowedTags.Contains(h.transform.tag)) { if (h.point.y > maxY) { //It is a disallowed walking tile, make it false Map[j, i] = new Node(j, i, 0, ID, x, y, false); //Non walkable tile! free = false; maxY = h.point.y; } } else if(IgnoreTags.Contains(h.transform.tag)) { //Do nothing we ignore these tags } else { if (h.point.y > maxY) { //It is allowed to walk on this tile, make it walkable! Map[j, i] = new Node(j, i, h.point.y, ID, x, y, true); //walkable tile! free = false; maxY = h.point.y; } } } //We hit nothing set tile to false if (free == true) { Map[j, i] = new Node(j, i, 0 ,ID, x, y, false);//Non walkable tile! } } } } #endregion //End map //---------------------------------------SETUP PATH QUEUE---------------------------------------// public void InsertInQueue(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod) { QueuePath q = new QueuePath(startPos, endPos, listMethod); queue.Add(q); } #region astar //---------------------------------------FIND PATH: A*------------------------------------------// private Node[] openList; private Node[] closedList; private Node startNode; private Node endNode; private Node currentNode; //Use it with KEY: F-value, VALUE: ID. ID's might be looked up in open and closed list then private List<NodeSearch> sortedOpenList = new List<NodeSearch>(); private void SetListsSize(int size) { openList = new Node[size]; closedList = new Node[size]; } IEnumerator PathHandler(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod) { yield return StartCoroutine(SinglePath(startPos, endPos, listMethod)); } IEnumerator SinglePath(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod) { FindPath(startPos, endPos, listMethod); yield return null; } public void FindPath(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod) { //The list we returns when path is found List<Vector3> returnPath = new List<Vector3>(); bool endPosValid = true; //Find start and end nodes, if we cant return null and stop! SetStartAndEndNode(startPos, endPos); if (startNode != null) { if (endNode == null) { endPosValid = false; FindEndNode(endPos); if (endNode == null) { //still no end node - we leave and sends an empty list maxSearchRounds = 0; listMethod.Invoke(new List<Vector3>()); return; } } //Clear lists if they are filled Array.Clear(openList, 0, openList.Length); Array.Clear(closedList, 0, openList.Length); if (sortedOpenList.Count > 0) { sortedOpenList.Clear(); } //Insert start node openList[startNode.ID] = startNode; //sortedOpenList.Add(new NodeSearch(startNode.ID, startNode.F)); BHInsertNode(new NodeSearch(startNode.ID, startNode.F)); bool endLoop = false; while (!endLoop) { //If we have no nodes on the open list AND we are not at the end, then we got stucked! return empty list then. if (sortedOpenList.Count == 0) { print("[Pathfind] Empty Openlist, closedList"); listMethod.Invoke(new List<Vector3>()); return; } //Get lowest node and insert it into the closed list int id = BHGetLowest(); //sortedOpenList.Sort(sort); //int id = sortedOpenList[0].ID; currentNode = openList[id]; closedList[currentNode.ID] = currentNode; openList[id] = null; //sortedOpenList.RemoveAt(0); if (currentNode.ID == endNode.ID) { endLoop = true; continue; } //Now look at neighbours, check for unwalkable tiles, bounderies, open and closed listed nodes. if (MoveDiagonal) { NeighbourCheck(); } else { NonDiagonalNeighborCheck(); } } while (currentNode.parent != null) { returnPath.Add(new Vector3(currentNode.xCoord, currentNode.yCoord, currentNode.zCoord)); currentNode = currentNode.parent; } //returnPath.Add(startPos); returnPath.Reverse(); if (endPosValid) { //returnPath.Add(endPos); } if (returnPath.Count > 2 && endPosValid) { //Now make sure we do not go backwards or go to long if (Vector3.Distance(returnPath[returnPath.Count - 1], returnPath[returnPath.Count - 3]) < Vector3.Distance(returnPath[returnPath.Count - 3], returnPath[returnPath.Count - 2])) { returnPath.RemoveAt(returnPath.Count - 2); } if (Vector3.Distance(returnPath[1], startPos) < Vector3.Distance(returnPath[0], returnPath[1])) { returnPath.RemoveAt(0); } } maxSearchRounds = 0; listMethod.Invoke(returnPath); } else { maxSearchRounds = 0; listMethod.Invoke(new List<Vector3>()); } } // Find start and end Node private void SetStartAndEndNode(Vector3 start, Vector3 end) { startNode = FindClosestNode(start); endNode = FindClosestNode(end); } public bool IsTheClosestNodeWalkable(Vector3 pos) { int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize); int z = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.z + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.z - MapStartPosition.y) / Tilesize); if (x < 0 || z < 0 || x > Map.GetLength(0) || z > Map.GetLength(1)) return false; Node n = Map[x, z]; return n.walkable; } private Node FindClosestNode(Vector3 pos) { int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize); int z = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.z + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.z - MapStartPosition.y) / Tilesize); if (x < 0 || z < 0 || x > Map.GetLength(0) || z > Map.GetLength(1)) return null; Node n = Map[x, z]; if (n.walkable) { return new Node(x, z, n.yCoord, n.ID, n.xCoord, n.zCoord, n.walkable); } else { //If we get a non walkable tile, then look around its neightbours for (int i = z - 1; i < z + 2; i++) { for (int j = x - 1; j < x + 2; j++) { //Check they are within bounderies if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0)) { if (Map[j, i].walkable) { return new Node(j, i, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable); } } } } return null; } } private void FindEndNode(Vector3 pos) { int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize); int z = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.z + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.z - MapStartPosition.y) / Tilesize); Node closestNode = Map[x, z]; List<Node> walkableNodes = new List<Node>(); int turns = 1; while(walkableNodes.Count < 1 && maxSearchRounds < (int)10/Tilesize) { walkableNodes = EndNodeNeighbourCheck(x, z, turns); turns++; maxSearchRounds++; } if (walkableNodes.Count > 0) //If we found some walkable tiles we will then return the nearest { int lowestDist = 99999999; Node n = null; foreach (Node node in walkableNodes) { int i = GetHeuristics(closestNode, node); if (i < lowestDist) { lowestDist = i; n = node; } } endNode = new Node(n.x, n.y, n.yCoord, n.ID, n.xCoord, n.zCoord, n.walkable); } } private List<Node> EndNodeNeighbourCheck(int x, int z, int r) { List<Node> nodes = new List<Node>(); for (int i = z - r; i < z + r + 1; i++) { for (int j = x - r; j < x + r + 1; j++) { //Check that we are within bounderis, and goes in ring around our end pos if (i > -1 && j > -1 && i < Map.GetLength(0) && j < Map.GetLength(1) && ((i < z - r + 1 || i > z + r - 1) || (j < x - r + 1 || j > x + r - 1))) { //if it is walkable put it on the right list if (Map[j, i].walkable) { nodes.Add(Map[j, i]); } } } } return nodes; } private void NeighbourCheck() { int x = currentNode.x; int y = currentNode.y; for (int i = y - 1; i < y + 2; i++) { for (int j = x - 1; j < x + 2; j++) { //Check it is within the bounderies if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0)) { //Dont check for the current node. if (i != y || j != x) { //Check the node is walkable if (Map[j, i].walkable) { //We do not recheck anything on the closed list if (!OnClosedList(Map[j, i].ID)) { //Check if we can move up or jump down! if ((Map[j, i].yCoord - currentNode.yCoord < ClimbLimit && Map[j, i].yCoord - currentNode.yCoord >= 0) || (currentNode.yCoord - Map[j, i].yCoord < MaxFalldownHeight && currentNode.yCoord >= Map[j, i].yCoord)) { //If it is not on the open list then add it to if (!OnOpenList(Map[j, i].ID)) { Node addNode = new Node(Map[j, i].x, Map[j, i].y, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable, currentNode); addNode.H = GetHeuristics(Map[j, i].x, Map[j, i].y); addNode.G = GetMovementCost(x, y, j, i) + currentNode.G; addNode.F = addNode.H + addNode.G; //Insert on open list openList[addNode.ID] = addNode; //Insert on sorted list BHInsertNode(new NodeSearch(addNode.ID, addNode.F)); //sortedOpenList.Add(new NodeSearch(addNode.ID, addNode.F)); } else { ///If it is on openlist then check if the new paths movement cost is lower Node n = GetNodeFromOpenList(Map[j, i].ID); if (currentNode.G + GetMovementCost(x, y, j, i) < openList[Map[j, i].ID].G) { n.parent = currentNode; n.G = currentNode.G + GetMovementCost(x, y, j, i); n.F = n.G + n.H; BHSortNode(n.ID, n.F); //ChangeFValue(n.ID, n.F); } } } } } } } } } } private void NonDiagonalNeighborCheck() { int x = currentNode.x; int y = currentNode.y; for (int i = y - 1; i < y + 2; i++) { for (int j = x - 1; j < x + 2; j++) { //Check it is within the bounderies if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0)) { //Dont check for the current node. if (i != y || j != x) { //Check that we are not moving diagonal if(GetMovementCost(x, y, j, i) < 14) { //Check the node is walkable if (Map[j, i].walkable) { //We do not recheck anything on the closed list if (!OnClosedList(Map[j, i].ID)) { //Check if we can move up or jump down! if ((Map[j, i].yCoord - currentNode.yCoord < ClimbLimit && Map[j, i].yCoord - currentNode.yCoord >= 0) || (currentNode.yCoord - Map[j, i].yCoord < MaxFalldownHeight && currentNode.yCoord >= Map[j, i].yCoord)) { //If it is not on the open list then add it to if (!OnOpenList(Map[j, i].ID)) { Node addNode = new Node(Map[j, i].x, Map[j, i].y, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable, currentNode); addNode.H = GetHeuristics(Map[j, i].x, Map[j, i].y); addNode.G = GetMovementCost(x, y, j, i) + currentNode.G; addNode.F = addNode.H + addNode.G; //Insert on open list openList[addNode.ID] = addNode; //Insert on sorted list BHInsertNode(new NodeSearch(addNode.ID, addNode.F)); //sortedOpenList.Add(new NodeSearch(addNode.ID, addNode.F)); } else { ///If it is on openlist then check if the new paths movement cost is lower Node n = GetNodeFromOpenList(Map[j, i].ID); if (currentNode.G + GetMovementCost(x, y, j, i) < openList[Map[j, i].ID].G) { n.parent = currentNode; n.G = currentNode.G + GetMovementCost(x, y, j, i); n.F = n.G + n.H; BHSortNode(n.ID, n.F); //ChangeFValue(n.ID, n.F); } } } } } } } } } } } private void ChangeFValue(int id, int F) { foreach (NodeSearch ns in sortedOpenList) { if (ns.ID == id) { ns.F = F; } } } //Check if a Node is already on the openList private bool OnOpenList(int id) { return (openList[id] != null) ? true : false; } //Check if a Node is already on the closedList private bool OnClosedList(int id) { return (closedList[id] != null) ? true : false; } private int GetHeuristics(int x, int y) { //Make sure heuristic aggression is not less then 0! int HA = (HeuristicAggression < 0) ? 0 : HeuristicAggression; return (int)(Mathf.Abs(x - endNode.x) * (10F + (10F * HA))) + (int)(Mathf.Abs(y - endNode.y) * (10F + (10F * HA))); } private int GetHeuristics(Node a, Node b) { //Make sure heuristic aggression is not less then 0! int HA = (HeuristicAggression < 0) ? 0 : HeuristicAggression; return (int)(Mathf.Abs(a.x - b.x) * (10F + (10F * HA))) + (int)(Mathf.Abs(a.y - b.y) * (10F + (10F * HA))); } private int GetMovementCost(int x, int y, int j, int i) { //Moving straight or diagonal? return (x != j && y != i) ? 14 : 10; } private Node GetNodeFromOpenList(int id) { return (openList[id] != null) ? openList[id] : null; } #region Binary_Heap (min) private void BHInsertNode(NodeSearch ns) { //We use index 0 as the root! if (sortedOpenList.Count == 0) { sortedOpenList.Add(ns); openList[ns.ID].sortedIndex = 0; return; } sortedOpenList.Add(ns); bool canMoveFurther = true; int index = sortedOpenList.Count - 1; openList[ns.ID].sortedIndex = index; while (canMoveFurther) { int parent = Mathf.FloorToInt((index - 1) / 2); if (index == 0) //We are the root { canMoveFurther = false; openList[sortedOpenList[index].ID].sortedIndex = 0; } else { if (sortedOpenList[index].F < sortedOpenList[parent].F) { NodeSearch s = sortedOpenList[parent]; sortedOpenList[parent] = sortedOpenList[index]; sortedOpenList[index] = s; //Save sortedlist index's for faster look up openList[sortedOpenList[index].ID].sortedIndex = index; openList[sortedOpenList[parent].ID].sortedIndex = parent; //Reset index to parent ID index = parent; } else { canMoveFurther = false; } } } } private void BHSortNode(int id, int F) { bool canMoveFurther = true; int index = openList[id].sortedIndex; sortedOpenList[index].F = F; while (canMoveFurther) { int parent = Mathf.FloorToInt((index - 1) / 2); if (index == 0) //We are the root { canMoveFurther = false; openList[sortedOpenList[index].ID].sortedIndex = 0; } else { if (sortedOpenList[index].F < sortedOpenList[parent].F) { NodeSearch s = sortedOpenList[parent]; sortedOpenList[parent] = sortedOpenList[index]; sortedOpenList[index] = s; //Save sortedlist index's for faster look up openList[sortedOpenList[index].ID].sortedIndex = index; openList[sortedOpenList[parent].ID].sortedIndex = parent; //Reset index to parent ID index = parent; } else { canMoveFurther = false; } } } } private int BHGetLowest() { if (sortedOpenList.Count == 1) //Remember 0 is our root { int ID = sortedOpenList[0].ID; sortedOpenList.RemoveAt(0); return ID; } else if (sortedOpenList.Count > 1) { //save lowest not, take our leaf as root, and remove it! Then switch through children to find right place. int ID = sortedOpenList[0].ID; sortedOpenList[0] = sortedOpenList[sortedOpenList.Count - 1]; sortedOpenList.RemoveAt(sortedOpenList.Count - 1); openList[sortedOpenList[0].ID].sortedIndex = 0; int index = 0; bool canMoveFurther = true; //Sort the list before returning the ID while (canMoveFurther) { int child1 = (index * 2) + 1; int child2 = (index * 2) + 2; int switchIndex = -1; if (child1 < sortedOpenList.Count) { switchIndex = child1; } else { break; } if (child2 < sortedOpenList.Count) { if (sortedOpenList[child2].F < sortedOpenList[child1].F) { switchIndex = child2; } } if (sortedOpenList[index].F > sortedOpenList[switchIndex].F) { NodeSearch ns = sortedOpenList[index]; sortedOpenList[index] = sortedOpenList[switchIndex]; sortedOpenList[switchIndex] = ns; //Save sortedlist index's for faster look up openList[sortedOpenList[index].ID].sortedIndex = index; openList[sortedOpenList[switchIndex].ID].sortedIndex = switchIndex; //Switch around idnex index = switchIndex; } else { break; } } return ID; } else { return -1; } } #endregion #endregion //End astar region! //---------------------------------------DRAW MAP IN EDITOR-------------------------------------// void OnDrawGizmosSelected() { //if (DrawMapInEditor == true && Map != null) // { // for (int i = 0; i < Map.GetLength(1); i++) // { // for (int j = 0; j < Map.GetLength(0); j++) // { // Gizmos.color = (Map[j, i].walkable) ? new Color(0, 0.8F, 0, 0.5F) : new Color(0.8F, 0, 0, 0.5F); // Gizmos.DrawCube(new Vector3(Map[j, i].xCoord, Map[j, i].yCoord + 0.1F, Map[j, i].zCoord), new Vector3(Tilesize, 0.5F, Tilesize)); // } // } // } } void DrawMapLines() { if (DrawMapInEditor == true && Map != null) { for (int i = 0; i < Map.GetLength(1); i++) { for (int j = 0; j < Map.GetLength(0); j++) { if (!Map[j, i].walkable) continue; for (int y = i - 1; y < i + 2; y++) { for (int x = j - 1; x < j + 2; x++) { if (y < 0 || x < 0 || y >= Map.GetLength(1) || x >= Map.GetLength(0)) continue; if(!Map[x, y].walkable) continue; if (Map[j, i].yCoord > Map[x, y].yCoord && Mathf.Abs(Map[j, i].yCoord - Map[x, y].yCoord) > MaxFalldownHeight) continue; if (Map[j, i].yCoord < Map[x, y].yCoord && Mathf.Abs(Map[x, y].yCoord - Map[j, i].yCoord) > ClimbLimit) continue; Vector3 start = new Vector3(Map[j, i].xCoord, Map[j, i].yCoord + 0.1f, Map[j, i].zCoord); Vector3 end = new Vector3(Map[x, y].xCoord, Map[x, y].yCoord + 0.1f, Map[x, y].zCoord); UnityEngine.Debug.DrawLine(start, end, Color.green); } } } } } } #region DynamicSupport public void DynamicMapEdit(List<Vector3> checkList, Action<List<Vector2>> listMethod) { listMethod.Invoke(DynamicFindClosestNodes(checkList)); } public void DynamicRedoMapEdit(List<Vector2> ids) { foreach (Vector2 v in ids) { Map[(int)v.x, (int)v.y].walkable = true; } } public void DynamicRaycastUpdate(Bounds b) { Vector3 startPos = new Vector3(b.min.x, 0, b.min.z); UnityEngine.Debug.Log("Startpos dyn: " + startPos); Node startNode = FindClosestNode(startPos); if (startNode == null) return; int xIterations = Mathf.CeilToInt(Mathf.Abs((b.max.x - b.min.x) / Tilesize)) + 2; int zIterations = Mathf.CeilToInt(Mathf.Abs((b.max.z - b.min.z) / Tilesize)) + 2; for (int i = startNode.x - 2; i < startNode.x + xIterations; i++) { for (int j = startNode.y - 2; j < startNode.y + zIterations; j++) { if (i >= 0 && j >= 0 && i < Map.GetLength(0) && j < Map.GetLength(1)) { float dist = Mathf.Abs(HighestPoint) + Mathf.Abs(LowestPoint); RaycastHit[] hit; if (CheckFullTileSize) { hit = Physics.SphereCastAll(new Vector3(Map[i, j].xCoord, HighestPoint, Map[i, j].zCoord), Tilesize / 2, Vector3.down, dist); } else { hit = Physics.SphereCastAll(new Vector3(Map[i, j].xCoord, HighestPoint, Map[i, j].zCoord), Tilesize / 16, Vector3.down, dist); } float maxY = -Mathf.Infinity; foreach (RaycastHit h in hit) { if (DisallowedTags.Contains(h.transform.tag)) { if (h.point.y > maxY) { //It is a disallowed walking tile, make it false Map[i, j].walkable = false; Map[i, j].yCoord = h.point.y; maxY = h.point.y; } } else if (IgnoreTags.Contains(h.transform.tag)) { //Do nothing we ignore these tags } else { if (h.point.y > maxY) { //It is allowed to walk on this tile, make it walkable! Map[i, j].walkable = true; Map[i, j].yCoord = h.point.y; maxY = h.point.y; } } } } } } } private List<Vector2> DynamicFindClosestNodes(List<Vector3> vList) { List<Vector2> returnList = new List<Vector2>(); foreach (Vector3 pos in vList) { int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize); int z = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.z + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.z - MapStartPosition.y) / Tilesize); if (x >= 0 && x < Map.GetLength(0) && z >= 0 && z < Map.GetLength(1)) { if (Map[x, z].walkable) { Map[x, z].walkable = false; returnList.Add(new Vector2(x, z)); } } } return returnList; } #endregion }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneTextures : FrameworkTestScene { private BlockingStoreProvidingContainer spriteContainer; [SetUp] public void Setup() => Schedule(() => { Child = spriteContainer = new BlockingStoreProvidingContainer { RelativeSizeAxes = Axes.Both }; }); [TearDownSteps] public void TearDownSteps() { AddStep("reset", () => spriteContainer.BlockingOnlineStore.Reset()); } /// <summary> /// Tests that a ref-counted texture is disposed when all references are lost. /// </summary> [Test] public void TestRefCountTextureDisposal() { Avatar avatar1 = null; Avatar avatar2 = null; Texture texture = null; AddStep("add disposable sprite", () => avatar1 = addSprite("1")); AddStep("add disposable sprite", () => avatar2 = addSprite("1")); AddUntilStep("wait for texture load", () => avatar1.Texture != null && avatar2.Texture != null); AddAssert("both textures are RefCount", () => avatar1.Texture is TextureWithRefCount && avatar2.Texture is TextureWithRefCount); AddAssert("textures share gl texture", () => avatar1.Texture.TextureGL == avatar2.Texture.TextureGL); AddAssert("textures have different refcount textures", () => avatar1.Texture != avatar2.Texture); AddStep("dispose children", () => { texture = avatar1.Texture; Clear(); avatar1.Dispose(); avatar2.Dispose(); }); assertAvailability(() => texture, false); } /// <summary> /// Tests the case where multiple lookups occur for different textures, which shouldn't block each other. /// </summary> [Test] public void TestFetchContentionDifferentLookup() { Avatar avatar1 = null; Avatar avatar2 = null; AddStep("begin blocking load", () => spriteContainer.BlockingOnlineStore.StartBlocking("1")); AddStep("get first", () => avatar1 = addSprite("1")); AddUntilStep("wait for first to begin loading", () => spriteContainer.BlockingOnlineStore.TotalInitiatedLookups == 1); AddStep("get second", () => avatar2 = addSprite("2")); AddUntilStep("wait for avatar2 load", () => avatar2.Texture != null); AddAssert("avatar1 not loaded", () => avatar1.Texture == null); AddAssert("only one lookup occurred", () => spriteContainer.BlockingOnlineStore.TotalCompletedLookups == 1); AddStep("unblock load", () => spriteContainer.BlockingOnlineStore.AllowLoad()); AddUntilStep("wait for texture load", () => avatar1.Texture != null); AddAssert("two lookups occurred", () => spriteContainer.BlockingOnlineStore.TotalCompletedLookups == 2); } /// <summary> /// Tests the case where multiple lookups occur which overlap each other, for the same texture. /// </summary> [Test] public void TestFetchContentionSameLookup() { Avatar avatar1 = null; Avatar avatar2 = null; AddStep("begin blocking load", () => spriteContainer.BlockingOnlineStore.StartBlocking()); AddStep("get first", () => avatar1 = addSprite("1")); AddStep("get second", () => avatar2 = addSprite("1")); AddAssert("neither are loaded", () => avatar1.Texture == null && avatar2.Texture == null); AddStep("unblock load", () => spriteContainer.BlockingOnlineStore.AllowLoad()); AddUntilStep("wait for texture load", () => avatar1.Texture != null && avatar2.Texture != null); AddAssert("only one lookup occurred", () => spriteContainer.BlockingOnlineStore.TotalInitiatedLookups == 1); } /// <summary> /// Tests that a ref-counted texture gets put in a non-available state when disposed. /// </summary> [Test] public void TestRefCountTextureAvailability() { Texture texture = null; AddStep("get texture", () => texture = spriteContainer.LargeStore.Get("1")); AddStep("dispose texture", () => texture.Dispose()); assertAvailability(() => texture, false); } /// <summary> /// Tests that a non-ref-counted texture remains in an available state when disposed. /// </summary> [Test] public void TestTextureAvailability() { Texture texture = null; AddStep("get texture", () => texture = spriteContainer.NormalStore.Get("1")); AddStep("dispose texture", () => texture.Dispose()); AddAssert("texture is still available", () => texture.Available); } private void assertAvailability(Func<Texture> textureFunc, bool available) => AddAssert($"texture available = {available}", () => ((TextureWithRefCount)textureFunc()).IsDisposed == !available); private Avatar addSprite(string url) { var avatar = new Avatar(url); spriteContainer.Add(new DelayedLoadWrapper(avatar)); return avatar; } [LongRunningLoad] private class Avatar : Sprite { private readonly string url; public Avatar(string url) { this.url = url; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { Texture = textures.Get(url); } } private class BlockingResourceStore : IResourceStore<byte[]> { /// <summary> /// The total number of lookups requested on this store (including blocked lookups). /// </summary> public int TotalInitiatedLookups { get; private set; } /// <summary> /// The total number of completed lookups. /// </summary> public int TotalCompletedLookups { get; private set; } private readonly IResourceStore<byte[]> baseStore; private readonly ManualResetEventSlim resetEvent = new ManualResetEventSlim(true); private string blockingName; private bool blocking; public BlockingResourceStore(IResourceStore<byte[]> baseStore) { this.baseStore = baseStore; } /// <summary> /// Block load until <see cref="AllowLoad"/> is called. /// </summary> /// <param name="blockingName">If not <c>null</c> or empty, only lookups for this particular name will be blocked.</param> public void StartBlocking(string blockingName = null) { this.blockingName = blockingName; blocking = true; resetEvent.Reset(); } public void AllowLoad() { blocking = false; resetEvent.Set(); } public byte[] Get(string name) => getWithBlocking(name, baseStore.Get); public Task<byte[]> GetAsync(string name) => getWithBlocking(name, baseStore.GetAsync); public Stream GetStream(string name) => getWithBlocking(name, baseStore.GetStream); private T getWithBlocking<T>(string name, Func<string, T> getFunc) { TotalInitiatedLookups++; if (blocking && name == blockingName) resetEvent.Wait(); TotalCompletedLookups++; return getFunc("sample-texture"); } public void Reset() { AllowLoad(); TotalInitiatedLookups = 0; TotalCompletedLookups = 0; } public IEnumerable<string> GetAvailableResources() => Enumerable.Empty<string>(); public void Dispose() { } } private class BlockingStoreProvidingContainer : Container { [Cached] public TextureStore NormalStore { get; private set; } [Cached] public LargeTextureStore LargeStore { get; private set; } public BlockingResourceStore BlockingOnlineStore { get; private set; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var game = parent.Get<Game>(); var host = parent.Get<GameHost>(); BlockingOnlineStore = new BlockingResourceStore(new NamespacedResourceStore<byte[]>(game.Resources, "Textures")); NormalStore = new TextureStore(host.CreateTextureLoaderStore(BlockingOnlineStore)); LargeStore = new LargeTextureStore(host.CreateTextureLoaderStore(BlockingOnlineStore)); return base.CreateChildDependencies(parent); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); BlockingOnlineStore?.Reset(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Internal.IL; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { public class ILCodeStream { private struct LabelAndOffset { public readonly ILCodeLabel Label; public readonly int Offset; public LabelAndOffset(ILCodeLabel label, int offset) { Label = label; Offset = offset; } } internal byte[] _instructions; internal int _length; internal int _startOffsetForLinking; internal ArrayBuilder<ILSequencePoint> _sequencePoints; private ArrayBuilder<LabelAndOffset> _offsetsNeedingPatching; private ILEmitter _emitter; internal ILCodeStream(ILEmitter emitter) { _instructions = Array.Empty<byte>(); _startOffsetForLinking = -1; _emitter = emitter; } private void EmitByte(byte b) { if (_instructions.Length == _length) Array.Resize<byte>(ref _instructions, 2 * _instructions.Length + 10); _instructions[_length++] = b; } private void EmitUInt16(ushort value) { EmitByte((byte)value); EmitByte((byte)(value >> 8)); } private void EmitUInt32(int value) { EmitByte((byte)value); EmitByte((byte)(value >> 8)); EmitByte((byte)(value >> 16)); EmitByte((byte)(value >> 24)); } public void Emit(ILOpcode opcode) { if ((int)opcode > 0x100) EmitByte((byte)ILOpcode.prefix1); EmitByte((byte)opcode); } public void Emit(ILOpcode opcode, ILToken token) { Emit(opcode); EmitUInt32((int)token); } public void EmitLdc(int value) { if (-1 <= value && value <= 8) { Emit((ILOpcode)(ILOpcode.ldc_i4_0 + value)); } else if (value == (sbyte)value) { Emit(ILOpcode.ldc_i4_s); EmitByte((byte)value); } else { Emit(ILOpcode.ldc_i4); EmitUInt32(value); } } public void EmitLdArg(int index) { if (index < 4) { Emit((ILOpcode)(ILOpcode.ldarg_0 + index)); } else { Emit(ILOpcode.ldarg); EmitUInt16((ushort)index); } } public void EmitLdArga(int index) { if (index < 0x100) { Emit(ILOpcode.ldarga_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldarga); EmitUInt16((ushort)index); } } public void EmitLdLoc(ILLocalVariable variable) { int index = (int)variable; if (index < 4) { Emit((ILOpcode)(ILOpcode.ldloc_0 + index)); } else if (index < 0x100) { Emit(ILOpcode.ldloc_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldloc); EmitUInt16((ushort)index); } } public void EmitLdLoca(ILLocalVariable variable) { int index = (int)variable; if (index < 0x100) { Emit(ILOpcode.ldloca_s); EmitByte((byte)index); } else { Emit(ILOpcode.ldloca); EmitUInt16((ushort)index); } } public void EmitStLoc(ILLocalVariable variable) { int index = (int)variable; if (index < 4) { Emit((ILOpcode)(ILOpcode.stloc_0 + index)); } else if (index < 0x100) { Emit(ILOpcode.stloc_s); EmitByte((byte)index); } else { Emit(ILOpcode.stloc); EmitUInt16((ushort)index); } } public void Emit(ILOpcode opcode, ILCodeLabel label) { Debug.Assert(opcode == ILOpcode.br || opcode == ILOpcode.brfalse || opcode == ILOpcode.brtrue || opcode == ILOpcode.beq || opcode == ILOpcode.bge || opcode == ILOpcode.bgt || opcode == ILOpcode.ble || opcode == ILOpcode.blt || opcode == ILOpcode.bne_un || opcode == ILOpcode.bge_un || opcode == ILOpcode.bgt_un || opcode == ILOpcode.ble_un || opcode == ILOpcode.blt_un || opcode == ILOpcode.leave); Emit(opcode); _offsetsNeedingPatching.Add(new LabelAndOffset(label, _length)); EmitUInt32(4); } public void EmitSwitch(ILCodeLabel[] labels) { Emit(ILOpcode.switch_); EmitUInt32(labels.Length); int remainingBytes = labels.Length * 4; foreach (var label in labels) { _offsetsNeedingPatching.Add(new LabelAndOffset(label, _length)); EmitUInt32(remainingBytes); remainingBytes -= 4; } } public void EmitUnaligned() { Emit(ILOpcode.unaligned); EmitByte(1); } public void EmitLdInd(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.ldind_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.ldind_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.ldind_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.ldind_i8); break; case TypeFlags.Single: Emit(ILOpcode.ldind_r4); break; case TypeFlags.Double: Emit(ILOpcode.ldind_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.ldind_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.ldind_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: case TypeFlags.SignatureMethodVariable: case TypeFlags.SignatureTypeVariable: Emit(ILOpcode.ldobj, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitStInd(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.stind_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.stind_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.stind_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.stind_i8); break; case TypeFlags.Single: Emit(ILOpcode.stind_r4); break; case TypeFlags.Double: Emit(ILOpcode.stind_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.stind_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.stind_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.stobj, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitStElem(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.stelem_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.stelem_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.stelem_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.stelem_i8); break; case TypeFlags.Single: Emit(ILOpcode.stelem_r4); break; case TypeFlags.Double: Emit(ILOpcode.stelem_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.stelem_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.stelem_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.stelem, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitLdElem(TypeDesc type) { switch (type.UnderlyingType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Boolean: Emit(ILOpcode.ldelem_i1); break; case TypeFlags.Char: case TypeFlags.UInt16: case TypeFlags.Int16: Emit(ILOpcode.ldelem_i2); break; case TypeFlags.UInt32: case TypeFlags.Int32: Emit(ILOpcode.ldelem_i4); break; case TypeFlags.UInt64: case TypeFlags.Int64: Emit(ILOpcode.ldelem_i8); break; case TypeFlags.Single: Emit(ILOpcode.ldelem_r4); break; case TypeFlags.Double: Emit(ILOpcode.ldelem_r8); break; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: case TypeFlags.Pointer: case TypeFlags.FunctionPointer: Emit(ILOpcode.ldelem_i); break; case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.Class: case TypeFlags.Interface: Emit(ILOpcode.ldelem_ref); break; case TypeFlags.ValueType: case TypeFlags.Nullable: Emit(ILOpcode.ldelem, _emitter.NewToken(type)); break; default: Debug.Fail("Unexpected TypeDesc category"); break; } } public void EmitLabel(ILCodeLabel label) { label.Place(this, _length); } internal void PatchLabels() { for (int i = 0; i < _offsetsNeedingPatching.Count; i++) { LabelAndOffset patch = _offsetsNeedingPatching[i]; Debug.Assert(patch.Label.IsPlaced); Debug.Assert(_startOffsetForLinking > -1); int offset = patch.Offset; int delta = _instructions[offset + 3] << 24 | _instructions[offset + 2] << 16 | _instructions[offset + 1] << 8 | _instructions[offset]; int value = patch.Label.AbsoluteOffset - _startOffsetForLinking - patch.Offset - delta; _instructions[offset] = (byte)value; _instructions[offset + 1] = (byte)(value >> 8); _instructions[offset + 2] = (byte)(value >> 16); _instructions[offset + 3] = (byte)(value >> 24); } } public void DefineSequencePoint(string document, int lineNumber) { // Last sequence point defined for this offset wins. if (_sequencePoints.Count > 0 && _sequencePoints[_sequencePoints.Count - 1].Offset == _length) { _sequencePoints[_sequencePoints.Count - 1] = new ILSequencePoint(_length, document, lineNumber); } else { _sequencePoints.Add(new ILSequencePoint(_length, document, lineNumber)); } } } /// <summary> /// Represent a token. Use one of the overloads of <see cref="ILEmitter.NewToken"/> /// to create a new token. /// </summary> public enum ILToken { } /// <summary> /// Represents a local variable. Use <see cref="ILEmitter.NewLocal"/> to create a new local variable. /// </summary> public enum ILLocalVariable { } public class ILStubMethodIL : MethodIL { private readonly byte[] _ilBytes; private readonly LocalVariableDefinition[] _locals; private readonly Object[] _tokens; private readonly MethodDesc _method; private readonly MethodDebugInformation _debugInformation; private const int MaxStackNotSet = -1; private int _maxStack; public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefinition[] locals, Object[] tokens, MethodDebugInformation debugInfo = null) { _ilBytes = ilBytes; _locals = locals; _tokens = tokens; _method = owningMethod; _maxStack = MaxStackNotSet; if (debugInfo == null) debugInfo = MethodDebugInformation.None; _debugInformation = debugInfo; } public ILStubMethodIL(ILStubMethodIL methodIL) { _ilBytes = methodIL._ilBytes; _locals = methodIL._locals; _tokens = methodIL._tokens; _method = methodIL._method; _debugInformation = methodIL._debugInformation; _maxStack = methodIL._maxStack; } public override MethodDesc OwningMethod { get { return _method; } } public override byte[] GetILBytes() { return _ilBytes; } public override MethodDebugInformation GetDebugInfo() { return _debugInformation; } public override int MaxStack { get { if (_maxStack == MaxStackNotSet) _maxStack = this.ComputeMaxStack(); return _maxStack; } } public override ILExceptionRegion[] GetExceptionRegions() { return Array.Empty<ILExceptionRegion>(); } public override bool IsInitLocals { get { return true; } } public override LocalVariableDefinition[] GetLocals() { return _locals; } public override Object GetObject(int token) { return _tokens[(token & 0xFFFFFF) - 1]; } } public class ILCodeLabel { private ILCodeStream _codeStream; private int _offsetWithinCodeStream; internal bool IsPlaced { get { return _codeStream != null; } } internal int AbsoluteOffset { get { Debug.Assert(IsPlaced); Debug.Assert(_codeStream._startOffsetForLinking >= 0); return _codeStream._startOffsetForLinking + _offsetWithinCodeStream; } } internal ILCodeLabel() { } internal void Place(ILCodeStream codeStream, int offsetWithinCodeStream) { Debug.Assert(!IsPlaced); _codeStream = codeStream; _offsetWithinCodeStream = offsetWithinCodeStream; } } public class ILEmitter { private ArrayBuilder<ILCodeStream> _codeStreams; private ArrayBuilder<LocalVariableDefinition> _locals; private ArrayBuilder<Object> _tokens; public ILEmitter() { } public ILCodeStream NewCodeStream() { ILCodeStream stream = new ILCodeStream(this); _codeStreams.Add(stream); return stream; } private ILToken NewToken(Object value, int tokenType) { Debug.Assert(value != null); _tokens.Add(value); return (ILToken)(_tokens.Count | tokenType); } public ILToken NewToken(TypeDesc value) { return NewToken(value, 0x01000000); } public ILToken NewToken(MethodDesc value) { return NewToken(value, 0x0a000000); } public ILToken NewToken(FieldDesc value) { return NewToken(value, 0x0a000000); } public ILToken NewToken(string value) { return NewToken(value, 0x70000000); } public ILToken NewToken(MethodSignature value) { return NewToken(value, 0x11000000); } public ILLocalVariable NewLocal(TypeDesc localType, bool isPinned = false) { int index = _locals.Count; _locals.Add(new LocalVariableDefinition(localType, isPinned)); return (ILLocalVariable)index; } public ILCodeLabel NewCodeLabel() { var newLabel = new ILCodeLabel(); return newLabel; } public MethodIL Link(MethodDesc owningMethod) { int totalLength = 0; int numSequencePoints = 0; for (int i = 0; i < _codeStreams.Count; i++) { ILCodeStream ilCodeStream = _codeStreams[i]; ilCodeStream._startOffsetForLinking = totalLength; totalLength += ilCodeStream._length; numSequencePoints += ilCodeStream._sequencePoints.Count; } byte[] ilInstructions = new byte[totalLength]; int copiedLength = 0; for (int i = 0; i < _codeStreams.Count; i++) { ILCodeStream ilCodeStream = _codeStreams[i]; ilCodeStream.PatchLabels(); Array.Copy(ilCodeStream._instructions, 0, ilInstructions, copiedLength, ilCodeStream._length); copiedLength += ilCodeStream._length; } MethodDebugInformation debugInfo = null; if (numSequencePoints > 0) { ILSequencePoint[] sequencePoints = new ILSequencePoint[numSequencePoints]; int copiedSequencePointLength = 0; for (int codeStreamIndex = 0; codeStreamIndex < _codeStreams.Count; codeStreamIndex++) { ILCodeStream ilCodeStream = _codeStreams[codeStreamIndex]; for (int sequencePointIndex = 0; sequencePointIndex < ilCodeStream._sequencePoints.Count; sequencePointIndex++) { ILSequencePoint sequencePoint = ilCodeStream._sequencePoints[sequencePointIndex]; sequencePoints[copiedSequencePointLength] = new ILSequencePoint( ilCodeStream._startOffsetForLinking + sequencePoint.Offset, sequencePoint.Document, sequencePoint.LineNumber); copiedSequencePointLength++; } } debugInfo = new EmittedMethodDebugInformation(sequencePoints); } var result = new ILStubMethodIL(owningMethod, ilInstructions, _locals.ToArray(), _tokens.ToArray(), debugInfo); result.CheckStackBalance(); return result; } private class EmittedMethodDebugInformation : MethodDebugInformation { private readonly ILSequencePoint[] _sequencePoints; public EmittedMethodDebugInformation(ILSequencePoint[] sequencePoints) { _sequencePoints = sequencePoints; } public override IEnumerable<ILSequencePoint> GetSequencePoints() { return _sequencePoints; } } } public abstract partial class ILStubMethod : MethodDesc { public abstract MethodIL EmitIL(); public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (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.oculusvr.com/licenses/LICENSE-3.2 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 UnityEngine; using System.Collections; public class OVRPlatformMenu : MonoBehaviour { public GameObject cursorTimer; public Color cursorTimerColor = new Color(0.0f, 0.643f, 1.0f, 1.0f); // set default color to same as native cursor timer public OVRCameraRig cameraRig = null; public float fixedDepth = 3.0f; private GameObject instantiatedCursorTimer = null; private Material cursorTimerMaterial = null; private float doubleTapDelay = 0.25f; private float longPressDelay = 0.75f; private float homeButtonDownTime = 0.0f; private bool platformUIStarted = false; /// <summary> /// Instantiate the cursor timer /// </summary> void Awake() { if (cameraRig == null) { Debug.LogError ("ERROR: missing camera controller object on " + name); enabled = false; return; } if ((cursorTimer != null) && (instantiatedCursorTimer == null)) { Debug.Log("Instantiating CursorTimer"); instantiatedCursorTimer = Instantiate(cursorTimer) as GameObject; if (instantiatedCursorTimer != null) { cursorTimerMaterial = instantiatedCursorTimer.GetComponent<Renderer>().material; cursorTimerMaterial.SetColor ( "_Color", cursorTimerColor ); instantiatedCursorTimer.GetComponent<Renderer>().enabled = false; } } // reset each time we resume/start platformUIStarted = false; } /// <summary> /// Destroy the cloned material /// </summary> void OnDestroy() { if (cursorTimerMaterial != null) { Destroy(cursorTimerMaterial); } } /// <summary> /// Reset when resuming /// </summary> void OnApplicationFocus() { platformUIStarted = false; } /// <summary> /// Show the confirm quit menu /// </summary> void ShowConfirmQuitMenu() { #if UNITY_ANDROID && !UNITY_EDITOR Debug.Log("[PlatformUI-ConfirmQuit] Showing @ " + Time.time); OVRManager.PlatformUIConfirmQuit(); platformUIStarted = true; #endif } /// <summary> /// Show the platform UI global menu /// </summary> void ShowGlobalMenu() { #if UNITY_ANDROID && !UNITY_EDITOR Debug.Log("[PlatformUI-Global] Showing @ " + Time.time); OVRManager.PlatformUIGlobalMenu(); platformUIStarted = true; #endif } /// <summary> /// Tests for long-press and activates global platform menu when detected. /// as per the Unity integration doc, the back button responds to "mouse 1" button down/up/etc /// </summary> void Update() { if (!platformUIStarted) { // process input for the home button if (Input.GetKeyDown (KeyCode.Escape)) { CancelInvoke("ShowConfirmQuitMenu"); CancelInvoke("ShowGlobalMenu"); if (Time.realtimeSinceStartup < (homeButtonDownTime + doubleTapDelay)) { // reset so the menu doesn't pop up after resetting orientation homeButtonDownTime = 0.0f; // reset the HMT orientation //OVRManager.display.RecenterPose(); } else { homeButtonDownTime = Time.realtimeSinceStartup; } } else if (Input.GetKeyUp(KeyCode.Escape)) { float elapsedTime = (Time.realtimeSinceStartup - homeButtonDownTime); if (elapsedTime < longPressDelay) { if (elapsedTime >= doubleTapDelay) { CancelInvoke( "ShowGlobalMenu" ); CancelInvoke( "ShowConfirmQuitMenu" ); } else { Invoke("ShowConfirmQuitMenu", (doubleTapDelay - elapsedTime)); } } // reset the timer cursor any time escape released ResetCursor (); } else if (Input.GetKey(KeyCode.Escape)) { float elapsedHomeButtonDownTime = Time.realtimeSinceStartup - homeButtonDownTime; if (elapsedHomeButtonDownTime > doubleTapDelay) { // Update the timer cursor using the amount of time we've held down for long press UpdateCursor(elapsedHomeButtonDownTime / longPressDelay); } // Check for long press if (elapsedHomeButtonDownTime >= longPressDelay && (homeButtonDownTime > 0.0f)) { // reset so something else doesn't trigger afterwards Input.ResetInputAxes(); homeButtonDownTime = 0.0f; // Reset the timer cursor once long press activated ResetCursor(); CancelInvoke("ShowConfirmQuitMenu"); Invoke("ShowGlobalMenu", 0); } } } } /// <summary> /// Update the cursor based on how long the back button is pressed /// </summary> void UpdateCursor(float timerRotateRatio) { if (instantiatedCursorTimer != null) { instantiatedCursorTimer.GetComponent<Renderer>().enabled = true; // Clamp the rotation ratio to avoid rendering artifacts float alphaAmount = Mathf.Clamp(1.0f - timerRotateRatio, 0.0f, 1.0f); cursorTimerMaterial.SetFloat ( "_Cutoff", alphaAmount ); // Draw timer at fixed distance in front of camera OVRPose pose = OVRManager.display.GetHeadPose(); // cursor positions itself based on camera forward and draws at a fixed depth Vector3 cameraForward = pose.orientation * Vector3.forward; instantiatedCursorTimer.transform.position = pose.position + (cameraForward * fixedDepth); instantiatedCursorTimer.transform.forward = cameraForward; } } void ResetCursor() { if (instantiatedCursorTimer != null) { cursorTimerMaterial.SetFloat("_Cutoff", 1.0f); instantiatedCursorTimer.GetComponent<Renderer>().enabled = false; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using System.IO; using NPOI.Util; using NPOI.SS.Formula.PTG; using System.Globalization; /** * A sub-record within the OBJ record which stores a reference to an object * stored in a Separate entry within the OLE2 compound file. * * @author Daniel Noll */ public class EmbeddedObjectRefSubRecord : SubRecord { private static POILogger logger = POILogFactory.GetLogger(typeof(EmbeddedObjectRefSubRecord)); public const short sid = 0x9; private static byte[] EMPTY_BYTE_ARRAY = { }; private int field_1_unknown_int; // Unknown stuff at the front. TODO: Confirm that it's a short[] /** either an area or a cell ref */ private Ptg field_2_refPtg; private byte[] field_2_unknownFormulaData; // TODO: Consider making a utility class for these. I've discovered the same field ordering // in FormatRecord and StringRecord, it may be elsewhere too. public bool field_3_unicode_flag; // Flags whether the string is Unicode. private String field_4_ole_classname; // Classname of the embedded OLE document (e.g. Word.Document.8) /** Formulas often have a single non-zero trailing byte. * This is in a similar position to he pre-streamId padding * It is unknown if the value is important (it seems to mirror a value a few bytes earlier) * */ private Byte? field_4_unknownByte; private int? field_5_stream_id; // ID of the OLE stream containing the actual data. private byte[] field_6_unknown; public EmbeddedObjectRefSubRecord() { field_2_unknownFormulaData = new byte[] { 0x02, 0x6C, 0x6A, 0x16, 0x01, }; // just some sample data. These values vary a lot field_6_unknown = EMPTY_BYTE_ARRAY; field_4_ole_classname = null; field_4_unknownByte = null; } /** * Constructs an EmbeddedObjectRef record and Sets its fields appropriately. * * @param in the record input stream. */ public EmbeddedObjectRefSubRecord(ILittleEndianInput in1, int size) { // Much guess-work going on here due to lack of any documentation. // See similar source code in OOO: // http://lxr.go-oo.org/source/sc/sc/source/filter/excel/xiescher.cxx // 1223 void XclImpOleObj::ReadPictFmla( XclImpStream& rStrm, sal_uInt16 nRecSize ) int streamIdOffset = in1.ReadShort(); // OOO calls this 'nFmlaLen' int remaining = size - LittleEndianConsts.SHORT_SIZE; int dataLenAfterFormula = remaining - streamIdOffset; int formulaSize = in1.ReadUShort(); remaining -= LittleEndianConsts.SHORT_SIZE; field_1_unknown_int = in1.ReadInt(); remaining -= LittleEndianConsts.INT_SIZE; byte[] formulaRawBytes = ReadRawData(in1, formulaSize); remaining -= formulaSize; field_2_refPtg = ReadRefPtg(formulaRawBytes); if (field_2_refPtg == null) { // common case // field_2_n16 seems to be 5 here // The formula almost looks like tTbl but the row/column values seem like garbage. field_2_unknownFormulaData = formulaRawBytes; } else { field_2_unknownFormulaData = null; } int stringByteCount; if (remaining >= dataLenAfterFormula + 3) { int tag = in1.ReadByte(); stringByteCount = LittleEndianConsts.BYTE_SIZE; if (tag != 0x03) { throw new RecordFormatException("Expected byte 0x03 here"); } int nChars = in1.ReadUShort(); stringByteCount += LittleEndianConsts.SHORT_SIZE; if (nChars > 0) { // OOO: the 4th way Xcl stores a unicode string: not even a Grbit byte present if Length 0 field_3_unicode_flag = (in1.ReadByte() & 0x01) != 0; stringByteCount += LittleEndianConsts.BYTE_SIZE; if (field_3_unicode_flag) { field_4_ole_classname = StringUtil.ReadUnicodeLE(in1,nChars); stringByteCount += nChars * 2; } else { field_4_ole_classname = StringUtil.ReadCompressedUnicode(in1,nChars); stringByteCount += nChars; } } else { field_4_ole_classname = ""; } } else { field_4_ole_classname = null; stringByteCount = 0; } remaining -= stringByteCount; // Pad to next 2-byte boundary if (((stringByteCount + formulaSize) % 2) != 0) { int b = in1.ReadByte(); remaining -= LittleEndianConsts.BYTE_SIZE; if (field_2_refPtg != null && field_4_ole_classname == null) { field_4_unknownByte = (byte)b; } } int nUnexpectedPadding = remaining - dataLenAfterFormula; if (nUnexpectedPadding > 0) { logger.Log(POILogger.ERROR, "Discarding " + nUnexpectedPadding + " unexpected padding bytes "); ReadRawData(in1, nUnexpectedPadding); remaining -= nUnexpectedPadding; } // Fetch the stream ID if (dataLenAfterFormula >= 4) { field_5_stream_id = in1.ReadInt(); remaining -= LittleEndianConsts.INT_SIZE; } else { field_5_stream_id = null; } field_6_unknown = ReadRawData(in1, remaining); } public override short Sid { get { return sid; } } private static Ptg ReadRefPtg(byte[] formulaRawBytes) { using (MemoryStream ms = new MemoryStream(formulaRawBytes)) { ILittleEndianInput in1 = new LittleEndianInputStream(ms); byte ptgSid = (byte)in1.ReadByte(); switch (ptgSid) { case AreaPtg.sid: return new AreaPtg(in1); case Area3DPtg.sid: return new Area3DPtg(in1); case RefPtg.sid: return new RefPtg(in1); case Ref3DPtg.sid: return new Ref3DPtg(in1); } return null; } } private static byte[] ReadRawData(ILittleEndianInput in1, int size) { if (size < 0) { throw new ArgumentException("Negative size (" + size + ")"); } if (size == 0) { return EMPTY_BYTE_ARRAY; } byte[] result = new byte[size]; in1.ReadFully(result); return result; } private int GetStreamIDOffset(int formulaSize) { int result = 2 + 4; // formulaSize + f2unknown_int result += formulaSize; int stringLen; if (field_4_ole_classname == null) { // don't write 0x03, stringLen, flag, text stringLen = 0; } else { result += 1 + 2; // 0x03, stringLen, flag stringLen = field_4_ole_classname.Length; if (stringLen > 0) { result += 1; // flag if (field_3_unicode_flag) { result += stringLen * 2; } else { result += stringLen; } } } // pad to next 2 byte boundary if ((result % 2) != 0) { result++; } return result; } private int GetDataSize(int idOffset) { int result = 2 + idOffset; // 2 for idOffset short field itself if (field_5_stream_id != null) { result += 4; } return result + field_6_unknown.Length; } public override int DataSize { get { int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.Length : field_2_refPtg.Size; int idOffset = GetStreamIDOffset(formulaSize); return GetDataSize(idOffset); } } public override void Serialize(ILittleEndianOutput out1) { int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.Length : field_2_refPtg.Size; int idOffset = GetStreamIDOffset(formulaSize); int dataSize = GetDataSize(idOffset); out1.WriteShort(sid); out1.WriteShort(dataSize); out1.WriteShort(idOffset); out1.WriteShort(formulaSize); out1.WriteInt(field_1_unknown_int); int pos = 12; if (field_2_refPtg == null) { out1.Write(field_2_unknownFormulaData); } else { field_2_refPtg.Write(out1); } pos += formulaSize; int stringLen; if (field_4_ole_classname == null) { // don't write 0x03, stringLen, flag, text stringLen = 0; } else { out1.WriteByte(0x03); pos += 1; stringLen = field_4_ole_classname.Length; out1.WriteShort(stringLen); pos += 2; if (stringLen > 0) { out1.WriteByte(field_3_unicode_flag ? 0x01 : 0x00); pos += 1; if (field_3_unicode_flag) { StringUtil.PutUnicodeLE(field_4_ole_classname, out1); pos += stringLen * 2; } else { StringUtil.PutCompressedUnicode(field_4_ole_classname, out1); pos += stringLen; } } } // pad to next 2-byte boundary (requires 0 or 1 bytes) switch (idOffset - (pos - 6 )) { // 6 for 3 shorts: sid, dataSize, idOffset case 1: out1.WriteByte(field_4_unknownByte == null ? 0x00 : (int)Convert.ToByte(field_4_unknownByte, CultureInfo.InvariantCulture)); pos++; break; case 0: break; default: throw new InvalidOperationException("Bad padding calculation (" + idOffset + ", " + pos + ")"); } if (field_5_stream_id != null) { out1.WriteInt(Convert.ToInt32(field_5_stream_id, CultureInfo.InvariantCulture)); pos += 4; } out1.Write(field_6_unknown); } /** * Gets the stream ID containing the actual data. The data itself * can be found under a top-level directory entry in the OLE2 filesystem * under the name "MBD<var>xxxxxxxx</var>" where <var>xxxxxxxx</var> is * this ID converted into hex (in big endian order, funnily enough.) * * @return the data stream ID. Possibly <c>null</c> */ public int? StreamId { get { return field_5_stream_id; } } public String OLEClassName { get { return field_4_ole_classname; } } public byte[] ObjectData { get { return field_6_unknown; } } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("[ftPictFmla]\n"); sb.Append(" .f2unknown = ").Append(HexDump.IntToHex(field_1_unknown_int)).Append("\n"); if (field_2_refPtg == null) { sb.Append(" .f3unknown = ").Append(HexDump.ToHex(field_2_unknownFormulaData)).Append("\n"); } else { sb.Append(" .formula = ").Append(field_2_refPtg.ToString()).Append("\n"); } if (field_4_ole_classname != null) { sb.Append(" .unicodeFlag = ").Append(field_3_unicode_flag).Append("\n"); sb.Append(" .oleClassname = ").Append(field_4_ole_classname).Append("\n"); } if (field_4_unknownByte != null) { sb.Append(" .f4unknown = ").Append(HexDump.ByteToHex(Convert.ToByte(field_4_unknownByte, CultureInfo.InvariantCulture))).Append("\n"); } if (field_5_stream_id != null) { sb.Append(" .streamId = ").Append(HexDump.IntToHex(Convert.ToInt32(field_5_stream_id, CultureInfo.InvariantCulture))).Append("\n"); } if (field_6_unknown.Length > 0) { sb.Append(" .f7unknown = ").Append(HexDump.ToHex(field_6_unknown)).Append("\n"); } sb.Append("[/ftPictFmla]"); return sb.ToString(); } public override Object Clone() { return this; // TODO proper clone } } }
#define USE_INTERPOLATION // // By Anomalous Underdog, 2011 // // Based on code made by Forest Johnson (Yoggy) and xyber // using UnityEngine; using System.Collections; using System.Collections.Generic; public class MeleeWeaponTrail : MonoBehaviour { [SerializeField] bool _emit = true; public bool Emit { set{_emit = value;} } bool _use = true; public bool Use { set{_use = value;} } [SerializeField] float _emitTime = 0.0f; [SerializeField] Material _material; [SerializeField] float _lifeTime = 1.0f; [SerializeField] Color[] _colors; [SerializeField] float[] _sizes; [SerializeField] float _minVertexDistance = 0.1f; [SerializeField] float _maxVertexDistance = 10.0f; float _minVertexDistanceSqr = 0.0f; float _maxVertexDistanceSqr = 0.0f; [SerializeField] float _maxAngle = 3.00f; [SerializeField] bool _autoDestruct = false; #if USE_INTERPOLATION [SerializeField] int subdivisions = 4; #endif [SerializeField] Transform _base; [SerializeField] Transform _tip; List<Point> _points = new List<Point>(); #if USE_INTERPOLATION List<Point> _smoothedPoints = new List<Point>(); #endif GameObject _trailObject; Mesh _trailMesh; Vector3 _lastPosition; [System.Serializable] public class Point { public float timeCreated = 0.0f; public Vector3 basePosition; public Vector3 tipPosition; } void Start() { _lastPosition = transform.position; _trailObject = new GameObject("Trail"); _trailObject.transform.parent = null; _trailObject.transform.position = Vector3.zero; _trailObject.transform.rotation = Quaternion.identity; _trailObject.transform.localScale = Vector3.one; _trailObject.AddComponent(typeof(MeshFilter)); _trailObject.AddComponent(typeof(MeshRenderer)); _trailObject.GetComponent<Renderer>().material = _material; _trailMesh = new Mesh(); _trailMesh.name = name + "TrailMesh"; _trailObject.GetComponent<MeshFilter>().mesh = _trailMesh; _minVertexDistanceSqr = _minVertexDistance * _minVertexDistance; _maxVertexDistanceSqr = _maxVertexDistance * _maxVertexDistance; } void OnDisable() { Destroy(_trailObject); } void Update() { if (!_use) { return; } if (_emit && _emitTime != 0) { _emitTime -= Time.deltaTime; if (_emitTime == 0) _emitTime = -1; if (_emitTime < 0) _emit = false; } if (!_emit && _points.Count == 0 && _autoDestruct) { Destroy(_trailObject); Destroy(gameObject); } // early out if there is no camera if (!Camera.main) return; // if we have moved enough, create a new vertex and make sure we rebuild the mesh float theDistanceSqr = (_lastPosition - transform.position).sqrMagnitude; if (_emit) { if (theDistanceSqr > _minVertexDistanceSqr) { bool make = false; if (_points.Count < 3) { make = true; } else { //Vector3 l1 = _points[_points.Count - 2].basePosition - _points[_points.Count - 3].basePosition; //Vector3 l2 = _points[_points.Count - 1].basePosition - _points[_points.Count - 2].basePosition; Vector3 l1 = _points[_points.Count - 2].tipPosition - _points[_points.Count - 3].tipPosition; Vector3 l2 = _points[_points.Count - 1].tipPosition - _points[_points.Count - 2].tipPosition; if (Vector3.Angle(l1, l2) > _maxAngle || theDistanceSqr > _maxVertexDistanceSqr) make = true; } if (make) { Point p = new Point(); p.basePosition = _base.position; p.tipPosition = _tip.position; p.timeCreated = Time.time; _points.Add(p); _lastPosition = transform.position; #if USE_INTERPOLATION if (_points.Count == 1) { _smoothedPoints.Add(p); } else if (_points.Count > 1) { // add 1+subdivisions for every possible pair in the _points for (int n = 0; n < 1+subdivisions; ++n) _smoothedPoints.Add(p); } // we use 4 control points for the smoothing if (_points.Count >= 4) { Vector3[] tipPoints = new Vector3[4]; tipPoints[0] = _points[_points.Count - 4].tipPosition; tipPoints[1] = _points[_points.Count - 3].tipPosition; tipPoints[2] = _points[_points.Count - 2].tipPosition; tipPoints[3] = _points[_points.Count - 1].tipPosition; //IEnumerable<Vector3> smoothTip = Interpolate.NewBezier(Interpolate.Ease(Interpolate.EaseType.Linear), tipPoints, subdivisions); IEnumerable<Vector3> smoothTip = Interpolate.NewCatmullRom(tipPoints, subdivisions, false); Vector3[] basePoints = new Vector3[4]; basePoints[0] = _points[_points.Count - 4].basePosition; basePoints[1] = _points[_points.Count - 3].basePosition; basePoints[2] = _points[_points.Count - 2].basePosition; basePoints[3] = _points[_points.Count - 1].basePosition; //IEnumerable<Vector3> smoothBase = Interpolate.NewBezier(Interpolate.Ease(Interpolate.EaseType.Linear), basePoints, subdivisions); IEnumerable<Vector3> smoothBase = Interpolate.NewCatmullRom(basePoints, subdivisions, false); List<Vector3> smoothTipList = new List<Vector3>(smoothTip); List<Vector3> smoothBaseList = new List<Vector3>(smoothBase); float firstTime = _points[_points.Count - 4].timeCreated; float secondTime = _points[_points.Count - 1].timeCreated; //Debug.Log(" smoothTipList.Count: " + smoothTipList.Count); for (int n = 0; n < smoothTipList.Count; ++n) { int idx = _smoothedPoints.Count - (smoothTipList.Count-n); // there are moments when the _smoothedPoints are lesser // than what is required, when elements from it are removed if (idx > -1 && idx < _smoothedPoints.Count) { Point sp = new Point(); sp.basePosition = smoothBaseList[n]; sp.tipPosition = smoothTipList[n]; sp.timeCreated = Mathf.Lerp(firstTime, secondTime, (float)n/smoothTipList.Count); _smoothedPoints[idx] = sp; } //else //{ // Debug.LogError(idx + "/" + _smoothedPoints.Count); //} } } #endif } else { _points[_points.Count - 1].basePosition = _base.position; _points[_points.Count - 1].tipPosition = _tip.position; //_points[_points.Count - 1].timeCreated = Time.time; #if USE_INTERPOLATION _smoothedPoints[_smoothedPoints.Count - 1].basePosition = _base.position; _smoothedPoints[_smoothedPoints.Count - 1].tipPosition = _tip.position; #endif } } else { if (_points.Count > 0) { _points[_points.Count - 1].basePosition = _base.position; _points[_points.Count - 1].tipPosition = _tip.position; //_points[_points.Count - 1].timeCreated = Time.time; } #if USE_INTERPOLATION if (_smoothedPoints.Count > 0) { _smoothedPoints[_smoothedPoints.Count - 1].basePosition = _base.position; _smoothedPoints[_smoothedPoints.Count - 1].tipPosition = _tip.position; } #endif } } RemoveOldPoints(_points); if (_points.Count == 0) { _trailMesh.Clear(); } #if USE_INTERPOLATION RemoveOldPoints(_smoothedPoints); if (_smoothedPoints.Count == 0) { _trailMesh.Clear(); } #endif #if USE_INTERPOLATION List<Point> pointsToUse = _smoothedPoints; #else List<Point> pointsToUse = _points; #endif if (pointsToUse.Count > 1) { Vector3[] newVertices = new Vector3[pointsToUse.Count * 2]; Vector2[] newUV = new Vector2[pointsToUse.Count * 2]; int[] newTriangles = new int[(pointsToUse.Count - 1) * 6]; Color[] newColors = new Color[pointsToUse.Count * 2]; for (int n = 0; n < pointsToUse.Count; ++n) { Point p = pointsToUse[n]; float time = (Time.time - p.timeCreated) / _lifeTime; Color color = Color.Lerp(Color.white, Color.clear, time); if (_colors != null && _colors.Length > 0) { float colorTime = time * (_colors.Length - 1); float min = Mathf.Floor(colorTime); float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, _colors.Length - 1); float lerp = Mathf.InverseLerp(min, max, colorTime); if (min >= _colors.Length) min = _colors.Length - 1; if (min < 0) min = 0; if (max >= _colors.Length) max = _colors.Length - 1; if (max < 0) max = 0; color = Color.Lerp(_colors[(int)min], _colors[(int)max], lerp); } float size = 0f; if (_sizes != null && _sizes.Length > 0) { float sizeTime = time * (_sizes.Length - 1); float min = Mathf.Floor(sizeTime); float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, _sizes.Length - 1); float lerp = Mathf.InverseLerp(min, max, sizeTime); if (min >= _sizes.Length) min = _sizes.Length - 1; if (min < 0) min = 0; if (max >= _sizes.Length) max = _sizes.Length - 1; if (max < 0) max = 0; size = Mathf.Lerp(_sizes[(int)min], _sizes[(int)max], lerp); } Vector3 lineDirection = p.tipPosition - p.basePosition; newVertices[n * 2] = p.basePosition - (lineDirection * (size * 0.5f)); newVertices[(n * 2) + 1] = p.tipPosition + (lineDirection * (size * 0.5f)); newColors[n * 2] = newColors[(n * 2) + 1] = color; float uvRatio = (float)n/pointsToUse.Count; newUV[n * 2] = new Vector2(uvRatio, 0); newUV[(n * 2) + 1] = new Vector2(uvRatio, 1); if (n > 0) { newTriangles[(n - 1) * 6] = (n * 2) - 2; newTriangles[((n - 1) * 6) + 1] = (n * 2) - 1; newTriangles[((n - 1) * 6) + 2] = n * 2; newTriangles[((n - 1) * 6) + 3] = (n * 2) + 1; newTriangles[((n - 1) * 6) + 4] = n * 2; newTriangles[((n - 1) * 6) + 5] = (n * 2) - 1; } } _trailMesh.Clear(); _trailMesh.vertices = newVertices; _trailMesh.colors = newColors; _trailMesh.uv = newUV; _trailMesh.triangles = newTriangles; } } void RemoveOldPoints(List<Point> pointList) { List<Point> remove = new List<Point>(); foreach (Point p in pointList) { // cull old points first if (Time.time - p.timeCreated > _lifeTime) { remove.Add(p); } } foreach (Point p in remove) { pointList.Remove(p); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security.Claims; using System.Text; using System.Threading; using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE; using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON; using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags; using LUID = Interop.LUID; using LSA_STRING = Interop.SspiCli.LSA_STRING; using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS; using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE; using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE; using System.Runtime.Serialization; namespace System.Security.Principal { [Serializable] public class WindowsIdentity : ClaimsIdentity, IDisposable, ISerializable, IDeserializationCallback { private string _name = null; private SecurityIdentifier _owner = null; private SecurityIdentifier _user = null; private IdentityReferenceCollection _groups = null; private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string _authType = null; private int _isAuthenticated = -1; private volatile TokenImpersonationLevel _impersonationLevel; private volatile bool _impersonationLevelInitialized; public new const string DefaultIssuer = @"AD AUTHORITY"; [NonSerialized] private string _issuerName = DefaultIssuer; [NonSerialized] private object _claimsIntiailizedLock = new object(); [NonSerialized] private volatile bool _claimsInitialized; [NonSerialized] private List<Claim> _deviceClaims; [NonSerialized] private List<Claim> _userClaims; // // Constructors. // private WindowsIdentity() : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { } /// <summary> /// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN). /// </summary> /// <remarks> /// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current /// thread privilege to include Tcb. /// </remarks> public WindowsIdentity(string sUserPrincipalName) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { // Desktop compat: See comments below for why we don't validate sUserPrincipalName. using (SafeLsaHandle lsaHandle = ConnectToLsa()) { int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A); // 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api // so we'll use the same name the CLR used even though we're not actually the "CLR." byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 }; TOKEN_SOURCE sourceContext; if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) throw new SecurityException(new Win32Exception().Message); sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); // Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) throw new ArgumentNullException("s"); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) { // Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort, // effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.) Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue); } unsafe { // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length); using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength)))) { if (authenticationInfo.IsInvalid) throw new OutOfMemoryException(); KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle()); pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon; pKerbS4uLogin->Flags = KerbS4uLogonFlags.None; pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length); IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1); pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset; Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length); pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0; pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero; ushort sourceNameLength = checked((ushort)(sourceName.Length)); using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength))) { if (sourceNameBuffer.IsInvalid) throw new OutOfMemoryException(); Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length); LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength); SafeLsaReturnBufferHandle profileBuffer; int profileBufferLength; LUID logonId; SafeAccessTokenHandle accessTokenHandle; QUOTA_LIMITS quota; int subStatus; int ntStatus = Interop.SspiCli.LsaLogonUser( lsaHandle, ref lsaOriginName, SECURITY_LOGON_TYPE.Network, packageId, authenticationInfo.DangerousGetHandle(), authenticationInfoLength, IntPtr.Zero, ref sourceContext, out profileBuffer, out profileBufferLength, out logonId, out accessTokenHandle, out quota, out subStatus); if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0) ntStatus = subStatus; if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); if (profileBuffer != null) profileBuffer.Dispose(); _safeTokenHandle = accessTokenHandle; } } } } } private static SafeLsaHandle ConnectToLsa() { SafeLsaHandle lsaHandle; int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); return lsaHandle; } private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName) { Debug.Assert(!string.IsNullOrEmpty(packageName)); unsafe { int packageId; byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName); fixed (byte* pAsciiPackageName = &asciiPackageName[0]) { LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length))); int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); } return packageId; } } public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { } public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { } private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { CreateFromToken(userToken); _authType = authType; _isAuthenticated = isAuthenticated; } private void CreateFromToken(IntPtr userToken) { if (userToken == IntPtr.Zero) throw new ArgumentException(SR.Argument_TokenZero); Contract.EndContractBlock(); // Find out if the specified token is a valid. uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType, SafeLocalAllocHandle.InvalidHandle, 0, out dwLength); if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE) throw new ArgumentException(SR.Argument_InvalidImpersonationToken); if (!Interop.Kernel32.DuplicateHandle(Interop.Kernel32.GetCurrentProcess(), userToken, Interop.Kernel32.GetCurrentProcess(), ref _safeTokenHandle, 0, true, Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) throw new SecurityException(new Win32Exception().Message); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public WindowsIdentity(SerializationInfo info, StreamingContext context) { _claimsInitialized = false; IntPtr userToken = (IntPtr)info.GetValue("m_userToken", typeof(IntPtr)); if (userToken != IntPtr.Zero) { CreateFromToken(userToken); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // TODO: Add back when ClaimsIdentity is serializable // base.GetObjectData(info, context); info.AddValue("m_userToken", _safeTokenHandle.DangerousGetHandle()); } void IDeserializationCallback.OnDeserialization(object sender) { } // // Factory methods. // public static WindowsIdentity GetCurrent() { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false); } public static WindowsIdentity GetCurrent(bool ifImpersonating) { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating); } public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { return GetCurrentInternal(desiredAccess, false); } // GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate // the request is anonymous. It does not represent a real process or thread token so // it cannot impersonate or do anything useful. Note this identity does not represent the // usual concept of an anonymous token, and the name is simply misleading but we cannot change it now. public static WindowsIdentity GetAnonymous() { return new WindowsIdentity(); } // // Properties. // // this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same. public override sealed string AuthenticationType { get { // If this is an anonymous identity, return an empty string if (_safeTokenHandle.IsInvalid) return String.Empty; if (_authType == null) { Interop.LUID authId = GetLogonAuthId(_safeTokenHandle); if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID) return String.Empty; // no authentication, just return an empty string SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle; try { int status = Interop.SspiCli.LsaGetLogonSessionData(ref authId, ref pLogonSessionData); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>()); Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0); return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer); } finally { if (!pLogonSessionData.IsInvalid) pLogonSessionData.Dispose(); } } return _authType; } } public TokenImpersonationLevel ImpersonationLevel { get { // In case of a race condition here here, both threads will set m_impersonationLevel to the same value, // which is ok. if (!_impersonationLevelInitialized) { TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; // If this is an anonymous identity if (_safeTokenHandle.IsInvalid) { impersonationLevel = TokenImpersonationLevel.Anonymous; } else { TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType); if (tokenType == TokenType.TokenPrimary) { impersonationLevel = TokenImpersonationLevel.None; // primary token; } else { /// This is an impersonation token, get the impersonation level int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel); impersonationLevel = (TokenImpersonationLevel)level + 1; } } _impersonationLevel = impersonationLevel; _impersonationLevelInitialized = true; } return _impersonationLevel; } } public override bool IsAuthenticated { get { if (_isAuthenticated == -1) { // This approach will not work correctly for domain guests (will return false // instead of true). This is a corner-case that is not very interesting. _isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0; } return _isAuthenticated == 1; } } private bool CheckNtTokenForSid(SecurityIdentifier sid) { Contract.EndContractBlock(); // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; TokenImpersonationLevel til = ImpersonationLevel; bool isMember = false; try { if (til == TokenImpersonationLevel.None) { if (!Interop.Advapi32.DuplicateTokenEx(_safeTokenHandle, (uint)TokenAccessLevels.Query, IntPtr.Zero, (uint)TokenImpersonationLevel.Identification, (uint)TokenType.TokenImpersonation, ref token)) throw new SecurityException(new Win32Exception().Message); } // CheckTokenMembership will check if the SID is both present and enabled in the access token. if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token), sid.BinaryForm, ref isMember)) throw new SecurityException(new Win32Exception().Message); } finally { if (token != SafeAccessTokenHandle.InvalidHandle) { token.Dispose(); } } return isMember; } // // IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always // possible to extract this same information from the User SID property and the new // (and more general) methods defined in the SID class (IsWellKnown, etc...). // public virtual bool IsGuest { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest })); } } public virtual bool IsSystem { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }); return (this.User == sid); } } public virtual bool IsAnonymous { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return true; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }); return (this.User == sid); } } public override string Name { get { return GetName(); } } internal String GetName() { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return String.Empty; if (_name == null) { // revert thread impersonation for the duration of the call to get the name. RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate { NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount; _name = ntAccount.ToString(); }); } return _name; } public SecurityIdentifier Owner { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_owner == null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner)) { _owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true); } } return _owner; } } public SecurityIdentifier User { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_user == null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser)) { _user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true); } } return _user; } } public IdentityReferenceCollection Groups { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_groups == null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups)) { uint groupCount = pGroups.Read<uint>(0); Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0); Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(), groupDetails, 0, groupDetails.Length); foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails) { // Ignore disabled, logon ID, and deny-only groups. uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { groups.Add(new SecurityIdentifier(group.Sid, true)); } } } Interlocked.CompareExchange(ref _groups, groups, null); } return _groups; } } public SafeAccessTokenHandle AccessToken { get { return _safeTokenHandle; } } public virtual IntPtr Token { get { return _safeTokenHandle.DangerousGetHandle(); } } // // Public methods. // public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); RunImpersonatedInternal(safeAccessTokenHandle, action); } public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { if (func == null) throw new ArgumentNullException(nameof(func)); T result = default(T); RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; } protected virtual void Dispose(bool disposing) { if (disposing) { if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed) _safeTokenHandle.Dispose(); } _name = null; _owner = null; _user = null; } public void Dispose() { Dispose(true); } // // internal. // private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged); private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action) { bool isImpersonating; int hr; SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr); if (previousToken == null || previousToken.IsInvalid) throw new SecurityException(new Win32Exception(hr).Message); s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null; ExecutionContext currentContext = ExecutionContext.Capture(); // Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone // on the way out. ExecutionContext.Run( currentContext, delegate { if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); s_currentImpersonatedToken.Value = null; if (!token.IsInvalid && !Interop.Advapi32.ImpersonateLoggedOnUser(token)) throw new SecurityException(SR.Argument_ImpersonateUser); s_currentImpersonatedToken.Value = token; action(); }, null); } private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args) { if (!args.ThreadContextChanged) return; // we handle explicit Value property changes elsewhere. if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); if (args.CurrentValue != null && !args.CurrentValue.IsInvalid) { if (!Interop.Advapi32.ImpersonateLoggedOnUser(args.CurrentValue)) Environment.FailFast(new Win32Exception().Message); } } internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly) { int hr = 0; bool isImpersonating; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { // either we wanted only ThreadToken - return null if (threadOnly && !isImpersonating) return null; // or there was an error throw new SecurityException(new Win32Exception(hr).Message); } WindowsIdentity wi = new WindowsIdentity(); wi._safeTokenHandle.Dispose(); wi._safeTokenHandle = safeTokenHandle; return wi; } // // private. // private static int GetHRForWin32Error(int dwLastError) { if ((dwLastError & 0x80000000) == 0x80000000) return dwLastError; else return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } private static Exception GetExceptionFromNtStatus(int status) { if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED) return new UnauthorizedAccessException(); if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY) return new OutOfMemoryException(); int win32ErrorCode = Interop.NtDll.RtlNtStatusToDosError(status); return new SecurityException(new Win32Exception(win32ErrorCode).Message); } private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr) { isImpersonating = true; SafeAccessTokenHandle safeTokenHandle; hr = 0; bool success = Interop.Advapi32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle); if (!success) hr = Marshal.GetHRForLastWin32Error(); if (!success && hr == GetHRForWin32Error(Interop.Errors.ERROR_NO_TOKEN)) { // No impersonation isImpersonating = false; if (!threadOnly) safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr); } return safeTokenHandle; } private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr) { hr = 0; SafeAccessTokenHandle safeTokenHandle; if (!Interop.Advapi32.OpenProcessToken(Interop.Kernel32.GetCurrentProcess(), desiredAccess, out safeTokenHandle)) hr = GetHRForWin32Error(Marshal.GetLastWin32Error()); return safeTokenHandle; } /// <summary> /// Get a property from the current token /// </summary> private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct { Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass)) { Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return information.Read<T>(0); } } private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0); return statistics.AuthenticationId; } } private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Interop.Errors.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) throw new OutOfMemoryException(); safeLocalAllocHandle.Initialize(dwLength); result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) throw new SecurityException(new Win32Exception().Message); break; case Interop.Errors.ERROR_INVALID_HANDLE: throw new ArgumentException(SR.Argument_InvalidImpersonationToken); default: throw new SecurityException(new Win32Exception(dwErrorCode).Message); } return safeLocalAllocHandle; } protected WindowsIdentity(WindowsIdentity identity) : base(identity, null, GetAuthType(identity), null, null) { bool mustDecrement = false; try { if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) { identity._safeTokenHandle.DangerousAddRef(ref mustDecrement); if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) CreateFromToken(identity._safeTokenHandle.DangerousGetHandle()); _authType = identity._authType; _isAuthenticated = identity._isAuthenticated; } } finally { if (mustDecrement) identity._safeTokenHandle.DangerousRelease(); } } private static string GetAuthType(WindowsIdentity identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } return identity._authType; } /// <summary> /// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object. /// </summary> public override ClaimsIdentity Clone() { return new WindowsIdentity(this); } /// <summary> /// Gets the 'User Claims' from the NTToken that represents this identity /// </summary> public virtual IEnumerable<Claim> UserClaims { get { InitializeClaims(); return _userClaims.ToArray(); } } /// <summary> /// Gets the 'Device Claims' from the NTToken that represents the device the identity is using /// </summary> public virtual IEnumerable<Claim> DeviceClaims { get { InitializeClaims(); return _deviceClaims.ToArray(); } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>. /// Includes UserClaims and DeviceClaims. /// </summary> public override IEnumerable<Claim> Claims { get { if (!_claimsInitialized) { InitializeClaims(); } foreach (Claim claim in base.Claims) yield return claim; foreach (Claim claim in _userClaims) yield return claim; foreach (Claim claim in _deviceClaims) yield return claim; } } /// <summary> /// Intenal method to initialize the claim collection. /// Lazy init is used so claims are not initialzed until needed /// </summary> private void InitializeClaims() { if (!_claimsInitialized) { lock (_claimsIntiailizedLock) { if (!_claimsInitialized) { _userClaims = new List<Claim>(); _deviceClaims = new List<Claim>(); if (!String.IsNullOrEmpty(Name)) { // // Add the name claim only if the WindowsIdentity.Name is populated // WindowsIdentity.Name will be null when it is the fake anonymous user // with a token value of IntPtr.Zero // _userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this)); } // primary sid AddPrimarySidClaim(_userClaims); // group sids AddGroupSidClaims(_userClaims); _claimsInitialized = true; } } } } /// <summary> /// Creates a collection of SID claims that represent the users groups. /// </summary> private void AddGroupSidClaims(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve the primary group sid safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup); Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle()); SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true); // only add one primary group sid bool foundPrimaryGroupSid = false; // Retrieve all group sids, primary group sid is one of them safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups")); Claim claim; for (int i = 0; i < count; ++i) { Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes); uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>()); } } finally { safeAllocHandle.Dispose(); safeAllocHandlePrimaryGroup.Dispose(); } } /// <summary> /// Creates a Windows SID Claim and adds to collection of claims. /// </summary> private void AddPrimarySidClaim(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser); Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle()); uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true); Claim claim; if (user.Attributes == 0) { claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } } finally { safeAllocHandle.Dispose(); } } } internal enum WinSecurityContext { Thread = 1, // OpenAsSelf = false Process = 2, // OpenAsSelf = true Both = 3 // OpenAsSelf = true, then OpenAsSelf = false } internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } internal enum TokenInformationClass : int { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using System.Xml; namespace OpenSim.Framework.Console { public class Commands : ICommands { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Encapsulates a command that can be invoked from the console /// </summary> private class CommandInfo { /// <value> /// The module from which this command comes /// </value> public string module; /// <value> /// Whether the module is shared /// </value> public bool shared; /// <value> /// Very short BNF description /// </value> public string help_text; /// <value> /// Longer one line help text /// </value> public string long_help; /// <value> /// Full descriptive help for this command /// </value> public string descriptive_help; /// <value> /// The method to invoke for this command /// </value> public List<CommandDelegate> fn; } public const string GeneralHelpText = "To enter an argument that contains spaces, surround the argument with double quotes.\nFor example, show object name \"My long object name\"\n"; public const string ItemHelpText = @"For more information, type 'help all' to get a list of all commands, or type help <item>' where <item> is one of the following:"; /// <value> /// Commands organized by keyword in a tree /// </value> private Dictionary<string, object> tree = new Dictionary<string, object>(); /// <summary> /// Commands organized by module /// </summary> private ThreadedClasses.RwLockedDictionaryAutoAdd<string, ThreadedClasses.RwLockedList<CommandInfo>> m_modulesCommands = new ThreadedClasses.RwLockedDictionaryAutoAdd<string, ThreadedClasses.RwLockedList<CommandInfo>>( delegate() { return new ThreadedClasses.RwLockedList<CommandInfo>(); }); /// <summary> /// Get help for the given help string /// </summary> /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param> /// <returns></returns> public List<string> GetHelp(string[] cmd) { List<string> help = new List<string>(); List<string> helpParts = new List<string>(cmd); // Remove initial help keyword helpParts.RemoveAt(0); help.Add(""); // Will become a newline. // General help if (helpParts.Count == 0) { help.Add(GeneralHelpText); help.Add(ItemHelpText); help.AddRange(CollectModulesHelp(tree)); } else if (helpParts.Count == 1 && helpParts[0] == "all") { help.AddRange(CollectAllCommandsHelp()); } else { help.AddRange(CollectHelp(helpParts)); } help.Add(""); // Will become a newline. return help; } /// <summary> /// Collects the help from all commands and return in alphabetical order. /// </summary> /// <returns></returns> private List<string> CollectAllCommandsHelp() { List<string> help = new List<string>(); m_modulesCommands.ForEach(delegate(ThreadedClasses.RwLockedList<CommandInfo> commands) { List<string> ourHelpText = new List<string>(); commands.ForEach(delegate(CommandInfo c) { ourHelpText.Add(string.Format("{0} - {1}", c.help_text, c.long_help)); }); help.AddRange(ourHelpText); }); help.Sort(); return help; } /// <summary> /// See if we can find the requested command in order to display longer help /// </summary> /// <param name="helpParts"></param> /// <returns></returns> private List<string> CollectHelp(List<string> helpParts) { string originalHelpRequest = string.Join(" ", helpParts.ToArray()); List<string> help = new List<string>(); // Check modules first to see if we just need to display a list of those commands if (TryCollectModuleHelp(originalHelpRequest, help)) { help.Insert(0, ItemHelpText); return help; } Dictionary<string, object> dict = tree; while (helpParts.Count > 0) { string helpPart = helpParts[0]; if (!dict.ContainsKey(helpPart)) break; //m_log.Debug("Found {0}", helpParts[0]); if (dict[helpPart] is Dictionary<string, Object>) dict = (Dictionary<string, object>)dict[helpPart]; helpParts.RemoveAt(0); } // There was a command for the given help string if (dict.ContainsKey(String.Empty)) { CommandInfo commandInfo = (CommandInfo)dict[String.Empty]; help.Add(commandInfo.help_text); help.Add(commandInfo.long_help); string descriptiveHelp = commandInfo.descriptive_help; // If we do have some descriptive help then insert a spacing line before for readability. if (descriptiveHelp != string.Empty) help.Add(string.Empty); help.Add(commandInfo.descriptive_help); } else { help.Add(string.Format("No help is available for {0}", originalHelpRequest)); } return help; } /// <summary> /// Try to collect help for the given module if that module exists. /// </summary> /// <param name="moduleName"></param> /// <param name="helpText">/param> /// <returns>true if there was the module existed, false otherwise.</returns> private bool TryCollectModuleHelp(string moduleName, List<string> helpText) { try { m_modulesCommands.ForEach(delegate(KeyValuePair<string, ThreadedClasses.RwLockedList<CommandInfo>> kvp) { // Allow topic help requests to succeed whether they are upper or lowercase. if (moduleName.ToLower() == kvp.Key.ToLower()) { List<string> ourHelpText = new List<string>(); kvp.Value.ForEach(delegate(CommandInfo c) { ourHelpText.Add(string.Format("{0} - {1}", c.help_text, c.long_help)); }); ourHelpText.Sort(); helpText.AddRange(ourHelpText); throw new ThreadedClasses.ReturnValueException<bool>(true); } }); } catch(ThreadedClasses.ReturnValueException<bool>) { return true; } return false; } private List<string> CollectModulesHelp(Dictionary<string, object> dict) { List<string> helpText = new List<string>(m_modulesCommands.Keys); helpText.Sort(); return helpText; } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn) { AddCommand(module, shared, command, help, longhelp, String.Empty, fn); } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="descriptivehelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, string descriptivehelp, CommandDelegate fn) { string[] parts = Parser.Parse(command); Dictionary<string, Object> current = tree; foreach (string part in parts) { if (current.ContainsKey(part)) { if (current[part] is Dictionary<string, Object>) current = (Dictionary<string, Object>)current[part]; else return; } else { current[part] = new Dictionary<string, Object>(); current = (Dictionary<string, Object>)current[part]; } } CommandInfo info; if (current.ContainsKey(String.Empty)) { info = (CommandInfo)current[String.Empty]; if (!info.shared && !info.fn.Contains(fn)) info.fn.Add(fn); return; } info = new CommandInfo(); info.module = module; info.shared = shared; info.help_text = help; info.long_help = longhelp; info.descriptive_help = descriptivehelp; info.fn = new List<CommandDelegate>(); info.fn.Add(fn); current[String.Empty] = info; // Now add command to modules dictionary ThreadedClasses.RwLockedList<CommandInfo> commands = m_modulesCommands[module]; commands.Add(info); } public string[] FindNextOption(string[] cmd, bool term) { Dictionary<string, object> current = tree; int remaining = cmd.Length; foreach (string s in cmd) { remaining--; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (remaining > 0 && opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1 && (remaining != 0 || term)) { current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return found.ToArray(); } else { break; // return new string[] {"<cr>"}; } } if (current.Count > 1) { List<string> choices = new List<string>(); bool addcr = false; foreach (string s in current.Keys) { if (s == String.Empty) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count != 0) addcr = true; } else choices.Add(s); } if (addcr) choices.Add("<cr>"); return choices.ToArray(); } if (current.ContainsKey(String.Empty)) return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text}; return new string[] { new List<string>(current.Keys)[0] }; } public string[] Resolve(string[] cmd) { string[] result = cmd; int index = -1; Dictionary<string, object> current = tree; foreach (string s in cmd) { // If a user puts an empty string on the console then this cannot be part of the command. if (s == "") break; index++; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1) { result[index] = found[0]; current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return new string[0]; } else { break; } } if (current.ContainsKey(String.Empty)) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count == 0) return new string[0]; foreach (CommandDelegate fn in ci.fn) { if (fn != null) fn(ci.module, result); else return new string[0]; } return result; } return new string[0]; } public XmlElement GetXml(XmlDocument doc) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); XmlElement root = doc.CreateElement("", "HelpTree", ""); ProcessTreeLevel(tree, root, doc); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; return root; } private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc) { foreach (KeyValuePair<string, object> kvp in level) { if (kvp.Value is Dictionary<string, Object>) { XmlElement next = doc.CreateElement("", "Level", ""); next.SetAttribute("Name", kvp.Key); xml.AppendChild(next); ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc); } else { CommandInfo c = (CommandInfo)kvp.Value; XmlElement cmd = doc.CreateElement("", "Command", ""); XmlElement e; e = doc.CreateElement("", "Module", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.module)); e = doc.CreateElement("", "Shared", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.shared.ToString())); e = doc.CreateElement("", "HelpText", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.help_text)); e = doc.CreateElement("", "LongHelp", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.long_help)); e = doc.CreateElement("", "Description", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.descriptive_help)); xml.AppendChild(cmd); } } } public void FromXml(XmlElement root, CommandDelegate fn) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); tree.Clear(); ReadTreeLevel(tree, root, fn); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; } private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn) { Dictionary<string, object> next; string name; XmlNodeList nodeL = node.ChildNodes; XmlNodeList cmdL; CommandInfo c; foreach (XmlNode part in nodeL) { switch (part.Name) { case "Level": name = ((XmlElement)part).GetAttribute("Name"); next = new Dictionary<string, object>(); level[name] = next; ReadTreeLevel(next, part, fn); break; case "Command": cmdL = part.ChildNodes; c = new CommandInfo(); foreach (XmlNode cmdPart in cmdL) { switch (cmdPart.Name) { case "Module": c.module = cmdPart.InnerText; break; case "Shared": c.shared = Convert.ToBoolean(cmdPart.InnerText); break; case "HelpText": c.help_text = cmdPart.InnerText; break; case "LongHelp": c.long_help = cmdPart.InnerText; break; case "Description": c.descriptive_help = cmdPart.InnerText; break; } } c.fn = new List<CommandDelegate>(); c.fn.Add(fn); level[String.Empty] = c; break; } } } } public class Parser { // If an unquoted portion ends with an element matching this regex // and the next element contains a space, then we have stripped // embedded quotes that should not have been stripped private static Regex optionRegex = new Regex("^--[a-zA-Z0-9-]+=$"); public static string[] Parse(string text) { List<string> result = new List<string>(); int index; string[] unquoted = text.Split(new char[] {'"'}); for (index = 0 ; index < unquoted.Length ; index++) { if (index % 2 == 0) { string[] words = unquoted[index].Split(new char[] {' '}); bool option = false; foreach (string w in words) { if (w != String.Empty) { if (optionRegex.Match(w) == Match.Empty) option = false; else option = true; result.Add(w); } } // The last item matched the regex, put the quotes back if (option) { // If the line ended with it, don't do anything if (index < (unquoted.Length - 1)) { // Get and remove the option name string optionText = result[result.Count - 1]; result.RemoveAt(result.Count - 1); // Add the quoted value back optionText += "\"" + unquoted[index + 1] + "\""; // Push the result into our return array result.Add(optionText); // Skip the already used value index++; } } } else { result.Add(unquoted[index]); } } return result.ToArray(); } } /// <summary> /// A console that processes commands internally /// </summary> public class CommandConsole : ConsoleBase, ICommandConsole { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event OnOutputDelegate OnOutput; public ICommands Commands { get; private set; } public CommandConsole(string defaultPrompt) : base(defaultPrompt) { Commands = new Commands(); Commands.AddCommand( "Help", false, "help", "help [<item>]", "Display help on a particular command or on a list of commands in a category", Help); } private void Help(string module, string[] cmd) { List<string> help = Commands.GetHelp(cmd); foreach (string s in help) Output(s); } protected void FireOnOutput(string text) { OnOutputDelegate onOutput = OnOutput; if (onOutput != null) onOutput(text); } /// <summary> /// Display a command prompt on the console and wait for user input /// </summary> public void Prompt() { string line = ReadLine(DefaultPrompt + "# ", true, true); if (line != String.Empty) Output("Invalid command"); } public void RunCommand(string cmd) { string[] parts = Parser.Parse(cmd); Commands.Resolve(parts); } public override string ReadLine(string p, bool isCommand, bool e) { System.Console.Write("{0}", p); string cmdinput = System.Console.ReadLine(); if (isCommand) { string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i=0 ; i < cmd.Length ; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } return cmdinput; } } }
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 MiniTrello.Win8Phone.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
// 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; namespace System.Linq.Expressions { /// <summary> /// Strongly-typed and parameterized string resources. /// </summary> internal static class Strings { /// <summary> /// A string like "reducible nodes must override Expression.Reduce()" /// </summary> internal static string ReducibleMustOverrideReduce { get { return SR.ReducibleMustOverrideReduce; } } /// <summary> /// A string like "node cannot reduce to itself or null" /// </summary> internal static string MustReduceToDifferent { get { return SR.MustReduceToDifferent; } } /// <summary> /// A string like "cannot assign from the reduced node type to the original node type" /// </summary> internal static string ReducedNotCompatible { get { return SR.ReducedNotCompatible; } } /// <summary> /// A string like "Setter must have parameters." /// </summary> internal static string SetterHasNoParams { get { return SR.SetterHasNoParams; } } /// <summary> /// A string like "Property cannot have a managed pointer type." /// </summary> internal static string PropertyCannotHaveRefType { get { return SR.PropertyCannotHaveRefType; } } /// <summary> /// A string like "Indexing parameters of getter and setter must match." /// </summary> internal static string IndexesOfSetGetMustMatch { get { return SR.IndexesOfSetGetMustMatch; } } /// <summary> /// A string like "Accessor method should not have VarArgs." /// </summary> internal static string AccessorsCannotHaveVarArgs { get { return SR.AccessorsCannotHaveVarArgs; } } /// <summary> /// A string like "Accessor indexes cannot be passed ByRef." /// </summary> internal static string AccessorsCannotHaveByRefArgs { get { return SR.AccessorsCannotHaveByRefArgs; } } /// <summary> /// A string like "Bounds count cannot be less than 1" /// </summary> internal static string BoundsCannotBeLessThanOne { get { return SR.BoundsCannotBeLessThanOne; } } /// <summary> /// A string like "type must not be ByRef" /// </summary> internal static string TypeMustNotBeByRef { get { return SR.TypeMustNotBeByRef; } } /// <summary> /// A string like "Type doesn't have constructor with a given signature" /// </summary> internal static string TypeDoesNotHaveConstructorForTheSignature { get { return SR.TypeDoesNotHaveConstructorForTheSignature; } } /// <summary> /// A string like "Count must be non-negative." /// </summary> internal static string CountCannotBeNegative { get { return SR.CountCannotBeNegative; } } /// <summary> /// A string like "arrayType must be an array type" /// </summary> internal static string ArrayTypeMustBeArray { get { return SR.ArrayTypeMustBeArray; } } /// <summary> /// A string like "Setter should have void type." /// </summary> internal static string SetterMustBeVoid { get { return SR.SetterMustBeVoid; } } /// <summary> /// A string like "Property type must match the value type of setter" /// </summary> internal static string PropertyTyepMustMatchSetter { get { return SR.PropertyTyepMustMatchSetter; } } /// <summary> /// A string like "Both accessors must be static." /// </summary> internal static string BothAccessorsMustBeStatic { get { return SR.BothAccessorsMustBeStatic; } } /// <summary> /// A string like "Static field requires null instance, non-static field requires non-null instance." /// </summary> internal static string OnlyStaticFieldsHaveNullInstance { get { return SR.OnlyStaticFieldsHaveNullInstance; } } /// <summary> /// A string like "Static property requires null instance, non-static property requires non-null instance." /// </summary> internal static string OnlyStaticPropertiesHaveNullInstance { get { return SR.OnlyStaticPropertiesHaveNullInstance; } } /// <summary> /// A string like "Static method requires null instance, non-static method requires non-null instance." /// </summary> internal static string OnlyStaticMethodsHaveNullInstance { get { return SR.OnlyStaticMethodsHaveNullInstance; } } /// <summary> /// A string like "Property cannot have a void type." /// </summary> internal static string PropertyTypeCannotBeVoid { get { return SR.PropertyTypeCannotBeVoid; } } /// <summary> /// A string like "Can only unbox from an object or interface type to a value type." /// </summary> internal static string InvalidUnboxType { get { return SR.InvalidUnboxType; } } /// <summary> /// A string like "Expression must be writeable" /// </summary> internal static string ExpressionMustBeWriteable { get { return SR.ExpressionMustBeWriteable; } } /// <summary> /// A string like "Argument must not have a value type." /// </summary> internal static string ArgumentMustNotHaveValueType { get { return SR.ArgumentMustNotHaveValueType; } } /// <summary> /// A string like "must be reducible node" /// </summary> internal static string MustBeReducible { get { return SR.MustBeReducible; } } /// <summary> /// A string like "All test values must have the same type." /// </summary> internal static string AllTestValuesMustHaveSameType { get { return SR.AllTestValuesMustHaveSameType; } } /// <summary> /// A string like "All case bodies and the default body must have the same type." /// </summary> internal static string AllCaseBodiesMustHaveSameType { get { return SR.AllCaseBodiesMustHaveSameType; } } /// <summary> /// A string like "Default body must be supplied if case bodies are not System.Void." /// </summary> internal static string DefaultBodyMustBeSupplied { get { return SR.DefaultBodyMustBeSupplied; } } /// <summary> /// A string like "MethodBuilder does not have a valid TypeBuilder" /// </summary> internal static string MethodBuilderDoesNotHaveTypeBuilder { get { return SR.MethodBuilderDoesNotHaveTypeBuilder; } } /// <summary> /// A string like "Label type must be System.Void if an expression is not supplied" /// </summary> internal static string LabelMustBeVoidOrHaveExpression { get { return SR.LabelMustBeVoidOrHaveExpression; } } /// <summary> /// A string like "Type must be System.Void for this label argument" /// </summary> internal static string LabelTypeMustBeVoid { get { return SR.LabelTypeMustBeVoid; } } /// <summary> /// A string like "Quoted expression must be a lambda" /// </summary> internal static string QuotedExpressionMustBeLambda { get { return SR.QuotedExpressionMustBeLambda; } } /// <summary> /// A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." /// </summary> internal static string VariableMustNotBeByRef(object p0, object p1) { return SR.Format(SR.VariableMustNotBeByRef, p0, p1); } /// <summary> /// A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." /// </summary> internal static string DuplicateVariable(object p0) { return SR.Format(SR.DuplicateVariable, p0); } /// <summary> /// A string like "Start and End must be well ordered" /// </summary> internal static string StartEndMustBeOrdered { get { return SR.StartEndMustBeOrdered; } } /// <summary> /// A string like "fault cannot be used with catch or finally clauses" /// </summary> internal static string FaultCannotHaveCatchOrFinally { get { return SR.FaultCannotHaveCatchOrFinally; } } /// <summary> /// A string like "try must have at least one catch, finally, or fault clause" /// </summary> internal static string TryMustHaveCatchFinallyOrFault { get { return SR.TryMustHaveCatchFinallyOrFault; } } /// <summary> /// A string like "Body of catch must have the same type as body of try." /// </summary> internal static string BodyOfCatchMustHaveSameTypeAsBodyOfTry { get { return SR.BodyOfCatchMustHaveSameTypeAsBodyOfTry; } } /// <summary> /// A string like "Extension node must override the property {0}." /// </summary> internal static string ExtensionNodeMustOverrideProperty(object p0) { return SR.Format(SR.ExtensionNodeMustOverrideProperty, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must be static." /// </summary> internal static string UserDefinedOperatorMustBeStatic(object p0) { return SR.Format(SR.UserDefinedOperatorMustBeStatic, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must not be void." /// </summary> internal static string UserDefinedOperatorMustNotBeVoid(object p0) { return SR.Format(SR.UserDefinedOperatorMustNotBeVoid, p0); } /// <summary> /// A string like "No coercion operator is defined between types '{0}' and '{1}'." /// </summary> internal static string CoercionOperatorNotDefined(object p0, object p1) { return SR.Format(SR.CoercionOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The unary operator {0} is not defined for the type '{1}'." /// </summary> internal static string UnaryOperatorNotDefined(object p0, object p1) { return SR.Format(SR.UnaryOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'." /// </summary> internal static string BinaryOperatorNotDefined(object p0, object p1, object p2) { return SR.Format(SR.BinaryOperatorNotDefined, p0, p1, p2); } /// <summary> /// A string like "Reference equality is not defined for the types '{0}' and '{1}'." /// </summary> internal static string ReferenceEqualityNotDefined(object p0, object p1) { return SR.Format(SR.ReferenceEqualityNotDefined, p0, p1); } /// <summary> /// A string like "The operands for operator '{0}' do not match the parameters of method '{1}'." /// </summary> internal static string OperandTypesDoNotMatchParameters(object p0, object p1) { return SR.Format(SR.OperandTypesDoNotMatchParameters, p0, p1); } /// <summary> /// A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." /// </summary> internal static string OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) { return SR.Format(SR.OverloadOperatorTypeDoesNotMatchConversionType, p0, p1); } /// <summary> /// A string like "Conversion is not supported for arithmetic types without operator overloading." /// </summary> internal static string ConversionIsNotSupportedForArithmeticTypes { get { return SR.ConversionIsNotSupportedForArithmeticTypes; } } /// <summary> /// A string like "Argument must be array" /// </summary> internal static string ArgumentMustBeArray { get { return SR.ArgumentMustBeArray; } } /// <summary> /// A string like "Argument must be boolean" /// </summary> internal static string ArgumentMustBeBoolean { get { return SR.ArgumentMustBeBoolean; } } /// <summary> /// A string like "The user-defined equality method '{0}' must return a boolean value." /// </summary> internal static string EqualityMustReturnBoolean(object p0) { return SR.Format(SR.EqualityMustReturnBoolean, p0); } /// <summary> /// A string like "Argument must be either a FieldInfo or PropertyInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfo { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfo; } } /// <summary> /// A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod; } } /// <summary> /// A string like "Argument must be an instance member" /// </summary> internal static string ArgumentMustBeInstanceMember { get { return SR.ArgumentMustBeInstanceMember; } } /// <summary> /// A string like "Argument must be of an integer type" /// </summary> internal static string ArgumentMustBeInteger { get { return SR.ArgumentMustBeInteger; } } /// <summary> /// A string like "Argument for array index must be of type Int32" /// </summary> internal static string ArgumentMustBeArrayIndexType { get { return SR.ArgumentMustBeArrayIndexType; } } /// <summary> /// A string like "Argument must be single dimensional array type" /// </summary> internal static string ArgumentMustBeSingleDimensionalArrayType { get { return SR.ArgumentMustBeSingleDimensionalArrayType; } } /// <summary> /// A string like "Argument types do not match" /// </summary> internal static string ArgumentTypesMustMatch { get { return SR.ArgumentTypesMustMatch; } } /// <summary> /// A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeElementThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeElementThroughProperty, p0); } /// <summary> /// A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeMemberThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeMemberThroughProperty, p0); } /// <summary> /// A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" /// </summary> internal static string IncorrectTypeForTypeAs(object p0) { return SR.Format(SR.IncorrectTypeForTypeAs, p0); } /// <summary> /// A string like "Coalesce used with type that cannot be null" /// </summary> internal static string CoalesceUsedOnNonNullType { get { return SR.CoalesceUsedOnNonNullType; } } /// <summary> /// A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" /// </summary> internal static string ExpressionTypeCannotInitializeArrayType(object p0, object p1) { return SR.Format(SR.ExpressionTypeCannotInitializeArrayType, p0, p1); } /// <summary> /// A string like " Argument type '{0}' does not match the corresponding member type '{1}'" /// </summary> internal static string ArgumentTypeDoesNotMatchMember(object p0, object p1) { return SR.Format(SR.ArgumentTypeDoesNotMatchMember, p0, p1); } /// <summary> /// A string like " The member '{0}' is not declared on type '{1}' being created" /// </summary> internal static string ArgumentMemberNotDeclOnType(object p0, object p1) { return SR.Format(SR.ArgumentMemberNotDeclOnType, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for return type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchReturn(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchReturn, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchAssignment(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchAssignment, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for label of type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchLabel(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchLabel, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be invoked" /// </summary> internal static string ExpressionTypeNotInvocable(object p0) { return SR.Format(SR.ExpressionTypeNotInvocable, p0); } /// <summary> /// A string like "Field '{0}' is not defined for type '{1}'" /// </summary> internal static string FieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.FieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance field '{0}' is not defined for type '{1}'" /// </summary> internal static string InstanceFieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstanceFieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Field '{0}.{1}' is not defined for type '{2}'" /// </summary> internal static string FieldInfoNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.FieldInfoNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Incorrect number of indexes" /// </summary> internal static string IncorrectNumberOfIndexes { get { return SR.IncorrectNumberOfIndexes; } } /// <summary> /// A string like "Incorrect number of parameters supplied for lambda declaration" /// </summary> internal static string IncorrectNumberOfLambdaDeclarationParameters { get { return SR.IncorrectNumberOfLambdaDeclarationParameters; } } /// <summary> /// A string like " Incorrect number of members for constructor" /// </summary> internal static string IncorrectNumberOfMembersForGivenConstructor { get { return SR.IncorrectNumberOfMembersForGivenConstructor; } } /// <summary> /// A string like "Incorrect number of arguments for the given members " /// </summary> internal static string IncorrectNumberOfArgumentsForMembers { get { return SR.IncorrectNumberOfArgumentsForMembers; } } /// <summary> /// A string like "Lambda type parameter must be derived from System.Delegate" /// </summary> internal static string LambdaTypeMustBeDerivedFromSystemDelegate { get { return SR.LambdaTypeMustBeDerivedFromSystemDelegate; } } /// <summary> /// A string like "Member '{0}' not field or property" /// </summary> internal static string MemberNotFieldOrProperty(object p0) { return SR.Format(SR.MemberNotFieldOrProperty, p0); } /// <summary> /// A string like "Method {0} contains generic parameters" /// </summary> internal static string MethodContainsGenericParameters(object p0) { return SR.Format(SR.MethodContainsGenericParameters, p0); } /// <summary> /// A string like "Method {0} is a generic method definition" /// </summary> internal static string MethodIsGeneric(object p0) { return SR.Format(SR.MethodIsGeneric, p0); } /// <summary> /// A string like "The method '{0}.{1}' is not a property accessor" /// </summary> internal static string MethodNotPropertyAccessor(object p0, object p1) { return SR.Format(SR.MethodNotPropertyAccessor, p0, p1); } /// <summary> /// A string like "The property '{0}' has no 'get' accessor" /// </summary> internal static string PropertyDoesNotHaveGetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveGetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'set' accessor" /// </summary> internal static string PropertyDoesNotHaveSetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveSetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'get' or 'set' accessors" /// </summary> internal static string PropertyDoesNotHaveAccessor(object p0) { return SR.Format(SR.PropertyDoesNotHaveAccessor, p0); } /// <summary> /// A string like "'{0}' is not a member of type '{1}'" /// </summary> internal static string NotAMemberOfType(object p0, object p1) { return SR.Format(SR.NotAMemberOfType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for type '{1}'" /// </summary> internal static string ExpressionNotSupportedForType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for nullable type '{1}'" /// </summary> internal static string ExpressionNotSupportedForNullableType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForNullableType, p0, p1); } /// <summary> /// A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" /// </summary> internal static string ParameterExpressionNotValidAsDelegate(object p0, object p1) { return SR.Format(SR.ParameterExpressionNotValidAsDelegate, p0, p1); } /// <summary> /// A string like "Property '{0}' is not defined for type '{1}'" /// </summary> internal static string PropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.PropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' is not defined for type '{1}'" /// </summary> internal static string InstancePropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'" /// </summary> internal static string InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyWithoutParameterNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}{1}' is not defined for type '{2}'" /// </summary> internal static string InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.InstancePropertyWithSpecifiedParametersNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" /// </summary> internal static string InstanceAndMethodTypeMismatch(object p0, object p1, object p2) { return SR.Format(SR.InstanceAndMethodTypeMismatch, p0, p1, p2); } /// <summary> /// A string like "Type '{0}' does not have a default constructor" /// </summary> internal static string TypeMissingDefaultConstructor(object p0) { return SR.Format(SR.TypeMissingDefaultConstructor, p0); } /// <summary> /// A string like "List initializers must contain at least one initializer" /// </summary> internal static string ListInitializerWithZeroMembers { get { return SR.ListInitializerWithZeroMembers; } } /// <summary> /// A string like "Element initializer method must be named 'Add'" /// </summary> internal static string ElementInitializerMethodNotAdd { get { return SR.ElementInitializerMethodNotAdd; } } /// <summary> /// A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" /// </summary> internal static string ElementInitializerMethodNoRefOutParam(object p0, object p1) { return SR.Format(SR.ElementInitializerMethodNoRefOutParam, p0, p1); } /// <summary> /// A string like "Element initializer method must have at least 1 parameter" /// </summary> internal static string ElementInitializerMethodWithZeroArgs { get { return SR.ElementInitializerMethodWithZeroArgs; } } /// <summary> /// A string like "Element initializer method must be an instance method" /// </summary> internal static string ElementInitializerMethodStatic { get { return SR.ElementInitializerMethodStatic; } } /// <summary> /// A string like "Type '{0}' is not IEnumerable" /// </summary> internal static string TypeNotIEnumerable(object p0) { return SR.Format(SR.TypeNotIEnumerable, p0); } /// <summary> /// A string like "Unexpected coalesce operator." /// </summary> internal static string UnexpectedCoalesceOperator { get { return SR.UnexpectedCoalesceOperator; } } /// <summary> /// A string like "Cannot cast from type '{0}' to type '{1}" /// </summary> internal static string InvalidCast(object p0, object p1) { return SR.Format(SR.InvalidCast, p0, p1); } /// <summary> /// A string like "Unhandled binary: {0}" /// </summary> internal static string UnhandledBinary(object p0) { return SR.Format(SR.UnhandledBinary, p0); } /// <summary> /// A string like "Unhandled binding " /// </summary> internal static string UnhandledBinding { get { return SR.UnhandledBinding; } } /// <summary> /// A string like "Unhandled Binding Type: {0}" /// </summary> internal static string UnhandledBindingType(object p0) { return SR.Format(SR.UnhandledBindingType, p0); } /// <summary> /// A string like "Unhandled convert: {0}" /// </summary> internal static string UnhandledConvert(object p0) { return SR.Format(SR.UnhandledConvert, p0); } /// <summary> /// A string like "Unhandled Expression Type: {0}" /// </summary> internal static string UnhandledExpressionType(object p0) { return SR.Format(SR.UnhandledExpressionType, p0); } /// <summary> /// A string like "Unhandled unary: {0}" /// </summary> internal static string UnhandledUnary(object p0) { return SR.Format(SR.UnhandledUnary, p0); } /// <summary> /// A string like "Unknown binding type" /// </summary> internal static string UnknownBindingType { get { return SR.UnknownBindingType; } } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." /// </summary> internal static string UserDefinedOpMustHaveConsistentTypes(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveConsistentTypes, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." /// </summary> internal static string UserDefinedOpMustHaveValidReturnType(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveValidReturnType, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." /// </summary> internal static string LogicalOperatorMustHaveBooleanOperators(object p0, object p1) { return SR.Format(SR.LogicalOperatorMustHaveBooleanOperators, p0, p1); } /// <summary> /// A string like "No method '{0}' exists on type '{1}'." /// </summary> internal static string MethodDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " /// </summary> internal static string GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.GenericMethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.MethodWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string PropertyWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.PropertyWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of a Func type." /// </summary> internal static string IncorrectNumberOfTypeArgsForFunc { get { return SR.IncorrectNumberOfTypeArgsForFunc; } } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of an Action type." /// </summary> internal static string IncorrectNumberOfTypeArgsForAction { get { return SR.IncorrectNumberOfTypeArgsForAction; } } /// <summary> /// A string like "Argument type cannot be System.Void." /// </summary> internal static string ArgumentCannotBeOfTypeVoid { get { return SR.ArgumentCannotBeOfTypeVoid; } } /// <summary> /// A string like "Invalid operation: '{0}'" /// </summary> internal static string InvalidOperation(object p0) { return SR.Format(SR.InvalidOperation, p0); } /// <summary> /// A string like "{0} must be greater than or equal to {1}" /// </summary> internal static string OutOfRange(object p0, object p1) { return SR.Format(SR.OutOfRange, p0, p1); } /// <summary> /// A string like "Queue empty." /// </summary> internal static string QueueEmpty { get { return SR.QueueEmpty; } } /// <summary> /// A string like "Cannot redefine label '{0}' in an inner block." /// </summary> internal static string LabelTargetAlreadyDefined(object p0) { return SR.Format(SR.LabelTargetAlreadyDefined, p0); } /// <summary> /// A string like "Cannot jump to undefined label '{0}'." /// </summary> internal static string LabelTargetUndefined(object p0) { return SR.Format(SR.LabelTargetUndefined, p0); } /// <summary> /// A string like "Control cannot leave a finally block." /// </summary> internal static string ControlCannotLeaveFinally { get { return SR.ControlCannotLeaveFinally; } } /// <summary> /// A string like "Control cannot leave a filter test." /// </summary> internal static string ControlCannotLeaveFilterTest { get { return SR.ControlCannotLeaveFilterTest; } } /// <summary> /// A string like "Cannot jump to ambiguous label '{0}'." /// </summary> internal static string AmbiguousJump(object p0) { return SR.Format(SR.AmbiguousJump, p0); } /// <summary> /// A string like "Control cannot enter a try block." /// </summary> internal static string ControlCannotEnterTry { get { return SR.ControlCannotEnterTry; } } /// <summary> /// A string like "Control cannot enter an expression--only statements can be jumped into." /// </summary> internal static string ControlCannotEnterExpression { get { return SR.ControlCannotEnterExpression; } } /// <summary> /// A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." /// </summary> internal static string NonLocalJumpWithValue(object p0) { return SR.Format(SR.NonLocalJumpWithValue, p0); } /// <summary> /// A string like "Extension should have been reduced." /// </summary> internal static string ExtensionNotReduced { get { return SR.ExtensionNotReduced; } } /// <summary> /// A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." /// </summary> internal static string CannotCompileConstant(object p0) { return SR.Format(SR.CannotCompileConstant, p0); } /// <summary> /// A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." /// </summary> internal static string CannotCompileDynamic { get { return SR.CannotCompileDynamic; } } /// <summary> /// A string like "Invalid lvalue for assignment: {0}." /// </summary> internal static string InvalidLvalue(object p0) { return SR.Format(SR.InvalidLvalue, p0); } /// <summary> /// A string like "Invalid member type: {0}." /// </summary> internal static string InvalidMemberType(object p0) { return SR.Format(SR.InvalidMemberType, p0); } /// <summary> /// A string like "unknown lift type: '{0}'." /// </summary> internal static string UnknownLiftType(object p0) { return SR.Format(SR.UnknownLiftType, p0); } /// <summary> /// A string like "Invalid output directory." /// </summary> internal static string InvalidOutputDir { get { return SR.InvalidOutputDir; } } /// <summary> /// A string like "Invalid assembly name or file extension." /// </summary> internal static string InvalidAsmNameOrExtension { get { return SR.InvalidAsmNameOrExtension; } } /// <summary> /// A string like "Cannot create instance of {0} because it contains generic parameters" /// </summary> internal static string IllegalNewGenericParams(object p0) { return SR.Format(SR.IllegalNewGenericParams, p0); } /// <summary> /// A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" /// </summary> internal static string UndefinedVariable(object p0, object p1, object p2) { return SR.Format(SR.UndefinedVariable, p0, p1, p2); } /// <summary> /// A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" /// </summary> internal static string CannotCloseOverByRef(object p0, object p1) { return SR.Format(SR.CannotCloseOverByRef, p0, p1); } /// <summary> /// A string like "Unexpected VarArgs call to method '{0}'" /// </summary> internal static string UnexpectedVarArgsCall(object p0) { return SR.Format(SR.UnexpectedVarArgsCall, p0); } /// <summary> /// A string like "Rethrow statement is valid only inside a Catch block." /// </summary> internal static string RethrowRequiresCatch { get { return SR.RethrowRequiresCatch; } } /// <summary> /// A string like "Try expression is not allowed inside a filter body." /// </summary> internal static string TryNotAllowedInFilter { get { return SR.TryNotAllowedInFilter; } } /// <summary> /// A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." /// </summary> internal static string MustRewriteToSameNode(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteToSameNode, p0, p1, p2); } /// <summary> /// A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteChildToSameType(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteChildToSameType, p0, p1, p2); } /// <summary> /// A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteWithoutMethod(object p0, object p1) { return SR.Format(SR.MustRewriteWithoutMethod, p0, p1); } /// <summary> /// A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForMethodsWithRefArgs(object p0) { return SR.Format(SR.TryNotSupportedForMethodsWithRefArgs, p0); } /// <summary> /// A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForValueTypeInstances(object p0) { return SR.Format(SR.TryNotSupportedForValueTypeInstances, p0); } /// <summary> /// A string like "Dynamic operations can only be performed in homogenous AppDomain." /// </summary> internal static string HomogenousAppDomainRequired { get { return SR.HomogenousAppDomainRequired; } } /// <summary> /// A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.TestValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } /// <summary> /// A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.SwitchValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } /// <summary> /// A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." /// </summary> internal static string PdbGeneratorNeedsExpressionCompiler { get { return SR.PdbGeneratorNeedsExpressionCompiler; } } #if FEATURE_COMPILE /// <summary> /// A string like "The operator '{0}' is not implemented for type '{1}'" /// </summary> internal static string OperatorNotImplementedForType(object p0, object p1) { return SR.Format(SR.OperatorNotImplementedForType, p0, p1); } #endif /// <summary> /// A string like "The constructor should not be static" /// </summary> internal static string NonStaticConstructorRequired { get { return SR.NonStaticConstructorRequired; } } /// <summary> /// A string like "The constructor should not be declared on an abstract class" /// </summary> internal static string NonAbstractConstructorRequired { get { return SR.NonAbstractConstructorRequired; } } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using Antlr.StringTemplate; using Antlr.StringTemplate.Language; using System.Globalization; namespace Thor.DataForge { public class EnumDeclaration:BaseType { private Dictionary<string, int> m_Values = new Dictionary<string, int>(); private StringTemplate m_Header; private StringTemplate m_Source; public StringTemplate Header { get { return m_Header; } } public StringTemplate Source { get { return m_Source; } } public Dictionary<string, int> Values { get { return m_Values; } } public int GetValue(string name) { int result = 0; if (m_Values.TryGetValue(name, out result)) return result; else return -1; } public void AddValue(string name, int val) { try { m_Values.Add(name, val); } catch(System.ArgumentException) { Compiler.Instance.DuplicateEnumField(this, name); } } public string EnumName { get { return Text; } } public void GenerateTemplates(Package package, StringTemplateGroup group) { m_Header = group.GetInstanceOf("enumH"); m_Source = group.GetInstanceOf("enumCPP"); int i = 0; foreach (var item in Values) { StringTemplate enumItem = group.GetInstanceOf("enumItem"); enumItem.SetAttribute("name", item.Key); enumItem.SetAttribute("value", item.Value); enumItem.SetAttribute("index", i); ++i; m_Header.SetAttribute("enumItems", enumItem); m_Source.SetAttribute("enumItems", enumItem); } m_Header.SetAttribute("name", Name); m_Source.SetAttribute("name", Name); m_Header.SetAttribute("package", package.NameCPP); m_Source.SetAttribute("package", package.NameCPP); GeneratedFileDesc desc = Compiler.Instance.GetGeneratedFileDesc(FileName); m_Header.SetAttribute("libMacros", desc.LibMacros); //string strH = enumH.ToString(); //string strCPP = enumCPP.ToString(); } } class FieldContext { private bool m_IsMap; private bool m_IsRef; private bool m_IsList; public bool IsMap { get { return m_IsMap; } set { m_IsMap = value; } } public bool IsRef { get { return m_IsRef; } set { m_IsRef = value; } } public bool IsList { get { return m_IsList; } set { m_IsList = value; } } } class InitializerContext { private eType m_ExpectedType1 = eType.BUILTINTYPESEND; private eType m_ExpectedType2 = eType.BUILTINTYPESEND; private StringTemplate m_Template; public InitializerContext(StringTemplateGroup group) { m_Template = group.GetInstanceOf("initter"); } public eType ExpectedType1 { get { return m_ExpectedType1; } set { m_ExpectedType1 = value; } } public eType ExpectedType2 { get { return m_ExpectedType2; } set { m_ExpectedType2 = value; } } public StringTemplate Template { get { return m_Template; } } public bool IsTypeExpected(eType type) { return type == ExpectedType1 || type == ExpectedType2; } } public abstract class CompoundTypeDeclaration<T> : BaseType { private Dictionary<string, DataField> m_Fields = new Dictionary<string, DataField>(); private CompoundTypeDeclaration<T> m_Parent = null; private List<Option> m_Options = null; private DataField m_CurrentField = null; private StringTemplate m_FieldH = null; private StringTemplate m_FieldCPP = null; protected StringTemplate m_Header = null; protected StringTemplate m_Source = null; protected StringTemplateGroup m_TemplateGroup = null; private bool m_IsTemplateGenerated = false; private bool m_IsCodeGenerated = false; public bool IsCodeGenerated { get { return m_IsCodeGenerated; } set { m_IsCodeGenerated = value; } } public StringTemplate Header { get { return m_Header; } } public StringTemplate Source { get { return m_Source; } } public Dictionary<string, DataField> Fields { get { return m_Fields; } } public void SetType(BaseType type) { Type = type.Type; PackageNameQualifier = type.PackageNameQualifier; Token = type.Token; } public void AddField(DataField field) { try { if (m_Parent != null) { if (m_Parent.Fields.ContainsKey(field.Name)) { throw new System.ArgumentException(); } } m_Fields.Add(field.Name, field); } catch (System.ArgumentException) { Compiler.Instance.DuplicateDataField(this,field); } } public CompoundTypeDeclaration<T> Parent { get { return m_Parent; } set { m_Parent = value; } } public List<Option> Options { get { return m_Options; } set { m_Options = value; } } public int LastParentFieldIndex { get { if (m_Parent != null) return m_Parent.LastParentFieldIndex + m_Parent.Fields.Count; return 0; } } private bool ProcessConstant(IConstant c, InitializerContext ic) { if (ic.IsTypeExpected(eType.INT32)) { Int32Constant integerConstant = c as Int32Constant; if (integerConstant != null) { ic.Template.SetAttribute("constants", integerConstant.Value.ToString(CultureInfo.InvariantCulture)); return true; } } if (ic.IsTypeExpected(eType.DOUBLE)) { DoubleConstant doubleConstant = c as DoubleConstant; if (doubleConstant != null) { ic.Template.SetAttribute("constants", doubleConstant.Value.ToString(CultureInfo.InvariantCulture)); return true; } } if (ic.IsTypeExpected(eType.STRING)) { StringConstant stringConstant = c as StringConstant; if (stringConstant != null) { if (m_CurrentField.Type.Type == eType.STRING) ic.Template.SetAttribute("constants", "L" + stringConstant.Value); else ic.Template.SetAttribute("constants", stringConstant.Value); return true; } } return false; } private void ProcessSimpleInitializer(SimpleInitializer initializer, int numRequiredConstants, InitializerContext ic) { foreach (var c in initializer.Constants) { if (!ProcessConstant(c, ic)) { BaseType fieldType = MapType(m_CurrentField.Type); //enum constant EnumDeclaration ed = fieldType as EnumDeclaration; if (ed != null) { EnumConstant ec = c as EnumConstant; if (ec != null) { int val = ed.GetValue(ec.TextVal); if (val != -1) ic.Template.SetAttribute("constants", val); else Compiler.Instance.EnumHasNoSuchValue(m_CurrentField, ed, ec.TextVal); } else { Compiler.Instance.InvalidEnumInitializer(m_CurrentField); } break; } //named constant SymbolConstant sc = c as SymbolConstant; if (sc != null) { DataField mappedConstant = MapConstant(sc); if (mappedConstant != null) { ProcessInitializer(mappedConstant.Initter, numRequiredConstants, ic); } else { Compiler.Instance.ConstantNotFound(sc); } } } } } private void ProcessDefaultValue(InitializerContext ic) { IDictionary defaultValues = m_TemplateGroup.GetMap("defaultValues"); foreach (System.Collections.DictionaryEntry p in defaultValues) { if ((string)p.Key == m_CurrentField.Type.Name) { ic.Template.SetAttribute("constants", p.Value.ToString()); return; } } } private void ProcessInitializer(Initializer initializer, int numRequiredConstants, InitializerContext ic) { if (initializer.Count != numRequiredConstants) { Compiler.Instance.InvalidFieldInitializer(m_CurrentField, numRequiredConstants); return; } SimpleInitializer si = initializer as SimpleInitializer; if (si != null) ProcessSimpleInitializer(si, numRequiredConstants, ic); } private eRuntimeKind GetRuntimeKind(DataField f) { RuntimeKindOption options = Utilities.GetOption<RuntimeKindOption>(f.Options); if (options != null) return options.Value; options = Utilities.GetOption<RuntimeKindOption>(Options); if (options != null) return options.Value; return Compiler.Instance.Options.RuntimeKind; } private bool IsFieldInProfile(DataField f) { ProfileOption po = Utilities.GetOption<ProfileOption>(f.Options); if (po != null) return po.Expr.Evaluate(); return true; } protected bool IsInProfile() { if (Parent != null) { bool result = Parent.IsInProfile(); if (!result) return false; } ProfileOption po = Utilities.GetOption<ProfileOption>(Options); if (po != null) return po.Expr.Evaluate(); return true; } private bool IsNoSerializeField(DataField f) { if (Utilities.GetOption<NoSerializeOption>(f.Options) != null) return true; return false; } private void ProcessBuiltInType(BaseType type, ref string typeName, FieldContext fc) { IDictionary typeMap = null; eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeMap = m_TemplateGroup.GetMap("typeMapSimple"); else if (rtk == eRuntimeKind.SimpleThreadSafe) typeMap = m_TemplateGroup.GetMap("typeMapSimpleThreadSafe"); else if (rtk == eRuntimeKind.DualBuffer) typeMap = m_TemplateGroup.GetMap("typeMapDualBuffer"); typeName = type.Name; foreach (System.Collections.DictionaryEntry p in typeMap) { if ((string)p.Key == type.Name) { typeName = p.Value.ToString(); break; } } InitializerContext ic = new InitializerContext(m_TemplateGroup); if (m_CurrentField.Initter != null) { int numRequiredConstants = 0; if (type.Type == eType.BOOL) { ic.ExpectedType1 = eType.BOOL; numRequiredConstants = 1; } else if (type.Type == eType.STRING || type.Type == eType.CSTRING) { ic.ExpectedType1 = eType.STRING; ic.ExpectedType2 = eType.CSTRING; numRequiredConstants = 1; } else if (type.Type > eType.INTEGERTYPESBEGIN && type.Type < eType.INTEGERTYPESEND) { ic.ExpectedType1 = eType.INT32; numRequiredConstants = 1; } else if (type.Type > eType.FPTYPESBEGIN && type.Type < eType.FPTYPESEND) { ic.ExpectedType1 = eType.INT32; ic.ExpectedType2 = eType.DOUBLE; numRequiredConstants = 1; } else if (type.Type > eType.BASICTYPESEND && type.Type < eType.BUILTINTYPESEND) { ic.ExpectedType1 = eType.INT32; ic.ExpectedType2 = eType.DOUBLE; numRequiredConstants = 1; } switch (type.Type) { case eType.VEC2: case eType.VEC2F: case eType.VEC2D: { numRequiredConstants = 2; break; } case eType.VEC3: case eType.VEC3D: case eType.VEC3F: { numRequiredConstants = 3; break; } case eType.VEC4: case eType.VEC4D: case eType.VEC4F: case eType.QUAT: case eType.QUATD: case eType.QUATF: case eType.MAT2X2: case eType.MAT2X2D: case eType.MAT2X2F: { numRequiredConstants = 4; break; } case eType.MAT3X3: case eType.MAT3X3D: case eType.MAT3X3F: { numRequiredConstants = 9; break; } case eType.MAT4X4: case eType.MAT4X4D: case eType.MAT4X4F: { numRequiredConstants = 16; break; } } if (numRequiredConstants > 0 && !fc.IsList && !fc.IsMap && !fc.IsRef) { ProcessInitializer(m_CurrentField.Initter, numRequiredConstants, ic); } else Compiler.Instance.InitializerNotSupported(m_CurrentField); var valueTypeMap = m_TemplateGroup.GetMap("valueTypeMap"); foreach (System.Collections.DictionaryEntry p in valueTypeMap) { if ((string)p.Key == type.Name) { ic.Template.SetAttribute("type",p.Value.ToString()); break; } } m_FieldCPP.SetAttribute("initVal", ic.Template); } else { ProcessDefaultValue(ic); m_FieldCPP.SetAttribute("initVal", ic.Template); } } private void ProcessMap(MapType type, ref string typeName, FieldContext fc) { m_FieldH.SetAttribute("isMap", true); m_FieldCPP.SetAttribute("isMap", true); fc.IsMap = true; string keyType = string.Empty; string valueType = string.Empty; ProcessType(type.KeyType, ref keyType, fc); ProcessType(type.ValueType, ref valueType, fc); eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeName = "ThMapSimpleField< " + keyType + ", " + valueType + ", false>"; else if (rtk == eRuntimeKind.SimpleThreadSafe) typeName = "ThMapSimpleField< " + keyType + ", " + valueType + ", true>"; else if (rtk == eRuntimeKind.DualBuffer) typeName = "ThMapDualBufferField< " + keyType + ", " + valueType + " >"; } private void ProcessList(ListType type, ref string typeName, FieldContext fc) { m_FieldH.SetAttribute("isList", true); m_FieldCPP.SetAttribute("isList", true); fc.IsList = true; string itemType = string.Empty; ProcessType(type.ContainedType, ref itemType, fc); eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeName = "ThListSimpleField< " + itemType + ", false>"; else if (rtk == eRuntimeKind.SimpleThreadSafe) typeName = "ThListSimpleField< " + itemType + ", true>"; else if (rtk == eRuntimeKind.DualBuffer) typeName = "ThListDualBufferField< " + itemType + " >"; } private void ProcessReference(RefType type, ref string typeName, FieldContext fc) { m_FieldH.SetAttribute("isRef", true); m_FieldCPP.SetAttribute("isRef", true); fc.IsRef = true; string refType = null; ProcessType(type.ContainedType, ref refType, fc); eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeName = "ThRefPtrSimpleField< " + refType + ", false>"; else if (rtk == eRuntimeKind.SimpleThreadSafe) typeName = "ThRefPtrSimpleField< " + refType + ", true>"; else if (rtk == eRuntimeKind.DualBuffer) typeName = "ThRefPtrDualBufferField< " + refType + " >"; } private void ProcessWeakReference(WeakRefType type, ref string typeName, FieldContext fc) { m_FieldH.SetAttribute("isWeakRef", true); m_FieldCPP.SetAttribute("isWeakRef", true); fc.IsRef = true; string refType = null; ProcessType(type.ContainedType, ref refType, fc); eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeName = "ThWeakPtrSimpleField< " + refType + ", false>"; else if (rtk == eRuntimeKind.SimpleThreadSafe) typeName = "ThWeakPtrSimpleField< " + refType + ", true>"; else if (rtk == eRuntimeKind.DualBuffer) typeName = "ThWeakPtrDualBufferField< " + refType + " >"; } private void ProcessCustom(BaseType type, ref string typeName, FieldContext fc) { Symbol sym = null; if (type.PackageNameQualifier == string.Empty) sym = Package.FindSymbolUp(type.FullName); else sym = Compiler.Instance.RootPackage.FindSymbolDown(type.FullName); if (sym != null) { if (!Compiler.Instance.IsFileInImports(FileName, sym.FileName)) Compiler.Instance.TypeNotImported(sym as BaseType, FileName); EntityDeclaration entityDecl = sym as EntityDeclaration; if (entityDecl != null) { if(!fc.IsRef) Compiler.Instance.EntityFieldDeclared(this, type); if (!entityDecl.IsInProfile()) Compiler.Instance.TypeNotInProfile(type); } StructDeclaration structDecl = sym as StructDeclaration; if (structDecl != null) { if (!structDecl.IsInProfile()) Compiler.Instance.TypeNotInProfile(type); if (!fc.IsList && !fc.IsMap) { m_FieldH.SetAttribute("isStruct", true); m_FieldCPP.SetAttribute("isStruct", true); } } EnumDeclaration enumDecl = sym as EnumDeclaration; if (enumDecl != null) { eRuntimeKind rtk = GetRuntimeKind(m_CurrentField); if (rtk == eRuntimeKind.Simple) typeName = string.Format("{0}Simple", type.FullNameCPP); else if (rtk == eRuntimeKind.SimpleThreadSafe) typeName = string.Format("{0}SimpleThreadSafe", type.FullNameCPP); else if (rtk == eRuntimeKind.DualBuffer) typeName = type.FullNameCPP; } else typeName = type.FullNameCPP; if (m_CurrentField.Initter != null) { InitializerContext ic = new InitializerContext(m_TemplateGroup); ProcessInitializer(m_CurrentField.Initter, 1, ic); m_FieldCPP.SetAttribute("initVal", ic.Template); } } else { Compiler.Instance.TypeNotFound(type); //throw new CompileException("Type not found"); } } protected BaseType MapType(BaseType type) { BaseType result = null; if (type.PackageNameQualifier == string.Empty) result = Package.FindSymbolUp(type.FullName); else result = Compiler.Instance.RootPackage.FindSymbolDown(type.FullName); return result; } protected DataField MapConstant(BaseType constant) { DataField result = null; if (constant.PackageNameQualifier == string.Empty) result = Package.FindConstantUp(constant.FullName); else result = Compiler.Instance.RootPackage.FindConstantDown(constant.FullName); return result; } private void ProcessType(BaseType type, ref string typeName, FieldContext fc) { if (type.IsBuiltIn) { ProcessBuiltInType(type, ref typeName, fc); } else if (type.Type == eType.LIST) { ProcessList(type as ListType, ref typeName, fc); } else if (type.Type == eType.MAP) { ProcessMap(type as MapType, ref typeName, fc); } else if (type.Type == eType.REF) { ProcessReference(type as RefType, ref typeName, fc); } else if (type.Type == eType.WEAKREF) { ProcessWeakReference(type as WeakRefType, ref typeName, fc); } else if (type.Type == eType.CUSTOM) { ProcessCustom(type, ref typeName, fc); } } public void GenerateFields(Package package, StringTemplate h, StringTemplate cpp, StringTemplateGroup group) { int index = LastParentFieldIndex; foreach (var f in m_Fields) { if (!IsFieldInProfile(f.Value)) continue; m_FieldH = group.GetInstanceOf("fieldH"); m_FieldCPP = group.GetInstanceOf("fieldCPP"); m_CurrentField = f.Value; m_FieldH.SetAttribute("name", f.Value.Name); m_FieldCPP.SetAttribute("name", f.Value.Name); m_FieldCPP.SetAttribute("index", index); m_FieldH.SetAttribute("package", package.NameCPP); m_FieldCPP.SetAttribute("package", package.NameCPP); string typeName = null; ProcessType(f.Value.Type, ref typeName, new FieldContext()); if (typeName != null) { m_FieldH.SetAttribute("type", typeName); m_FieldCPP.SetAttribute("type", typeName); } h.SetAttribute("fields", m_FieldH); cpp.SetAttribute("fields", m_FieldCPP); if (IsNoSerializeField(f.Value)) m_FieldCPP.SetAttribute("noSerialize", true); ++index; } } public void GenerateParentTypeInfo(StringTemplate h, StringTemplate cpp) { if (Parent != null) { h.SetAttribute("base", Parent.Header); cpp.SetAttribute("base", Parent.Source); } } public abstract void Preprocess(); public void GenerateTemplates(Package package, StringTemplateGroup group) { if (!IsInProfile()) { m_IsTemplateGenerated = true; return; } m_TemplateGroup = group; if (!m_IsTemplateGenerated) { m_IsTemplateGenerated = true; if (Parent != null) Parent.GenerateTemplates(package, group); GenerateTemplatesImpl(package, group); } } protected abstract void GenerateTemplatesImpl(Package package, StringTemplateGroup group); } public class StructDeclaration:CompoundTypeDeclaration<StructDeclaration> { public override void Preprocess() { if (Parent != null) { BaseType pc = MapType(Parent); StructDeclaration sd = pc as StructDeclaration; if (sd != null) { if (!Compiler.Instance.IsFileInImports(FileName, sd.FileName)) Compiler.Instance.TypeNotImported(sd, FileName); Parent = sd; } else { Compiler.Instance.StructureNotFound(this); //throw new CompileException("StructureNotFound"); } } } protected override void GenerateTemplatesImpl(Package package, StringTemplateGroup group) { m_Header = group.GetInstanceOf("structH"); m_Source = group.GetInstanceOf("structCPP"); m_Header.SetAttribute("package", package.NameCPP); m_Source.SetAttribute("package", package.NameCPP); m_Header.SetAttribute("name", Name); m_Source.SetAttribute("name", Name); GeneratedFileDesc desc = Compiler.Instance.GetGeneratedFileDesc(FileName); m_Header.SetAttribute("libMacros", desc.LibMacros); GenerateFields(package, m_Header, m_Source, group); GenerateParentTypeInfo(m_Header, m_Source); string h = m_Header.ToString(); string cpp = m_Source.ToString(); } } public class EntityDeclaration : CompoundTypeDeclaration<EntityDeclaration> { public override void Preprocess() { if (Parent != null) { Symbol pc = MapType(Parent); EntityDeclaration ed = pc as EntityDeclaration; if (ed != null) { if (!Compiler.Instance.IsFileInImports(FileName, ed.FileName)) Compiler.Instance.TypeNotImported(ed, FileName); Parent = ed; } else { Compiler.Instance.EntityNotFound(this); //throw new CompileException("EntityNotFound"); } } } protected override void GenerateTemplatesImpl(Package package, StringTemplateGroup group) { m_Header = group.GetInstanceOf("entityH"); m_Source = group.GetInstanceOf("entityCPP"); m_Header.SetAttribute("package", package.NameCPP); m_Source.SetAttribute("package", package.NameCPP); m_Header.SetAttribute("name", Name); m_Source.SetAttribute("name", Name); GeneratedFileDesc desc = Compiler.Instance.GetGeneratedFileDesc(FileName); m_Header.SetAttribute("libMacros", desc.LibMacros); GenerateFields(package, m_Header, m_Source, group); GenerateParentTypeInfo(m_Header, m_Source); string h = m_Header.ToString(); string cpp = m_Source.ToString(); } } }
using System; using System.Collections.Generic; using SilentOrbit.Code; namespace SilentOrbit.ProtocolBuffers { class FieldSerializer { readonly CodeWriter cw; readonly Options options; public FieldSerializer(CodeWriter cw, Options options) { this.cw = cw; this.options = options; } #region Reader /// <summary> /// Return true for normal code and false if generated thrown exception. /// In the latter case a break is not needed to be generated afterwards. /// </summary> public bool FieldReader(Field f) { if (f.Rule == FieldRule.Repeated) { //Make sure we are not reading a list of interfaces if (f.ProtoType.OptionType == "interface") { cw.WriteLine("throw new NotSupportedException(\"Can't deserialize a list of interfaces\");"); return false; } if (f.OptionPacked == true) { cw.Comment("repeated packed"); cw.WriteLine("long end" + f.ID + " = " + ProtocolParser.Base + ".ReadUInt32(stream);"); cw.WriteLine("end" + f.ID + " += stream.Position;"); cw.WhileBracket("stream.Position < end" + f.ID); cw.WriteLine("instance." + f.CsName + ".Add(" + FieldReaderType(f, "stream", "br", null) + ");"); cw.EndBracket(); cw.WriteLine("if (stream.Position != end" + f.ID + ")"); cw.WriteIndent("throw new global::SilentOrbit.ProtocolBuffers.ProtocolBufferException(\"Read too many bytes in packed data\");"); } else { cw.Comment("repeated"); cw.WriteLine("instance." + f.CsName + ".Add(" + FieldReaderType(f, "stream", "br", null) + ");"); } } else { if (f.OptionReadOnly) { //The only "readonly" fields we can modify //We could possibly support bytes primitive too but it would require the incoming length to match the wire length if (f.ProtoType is ProtoMessage) { cw.WriteLine(FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); return true; } cw.WriteLine("throw new InvalidOperationException(\"Can't deserialize into a readonly primitive field\");"); return false; } if (f.ProtoType is ProtoMessage) { if (f.ProtoType.OptionType == "struct") { if (options.Nullable) cw.WriteLine("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", null) + ";"); else cw.WriteLine(FieldReaderType(f, "stream", "br", "ref instance." + f.CsName) + ";"); return true; } cw.WriteLine("if (instance." + f.CsName + " == null)"); if (f.ProtoType.OptionType == "interface") cw.WriteIndent("throw new InvalidOperationException(\"Can't deserialize into a interfaces null pointer\");"); else cw.WriteIndent("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", null) + ";"); cw.WriteLine("else"); cw.WriteIndent(FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); return true; } cw.WriteLine("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); cw.WriteLine("instance.ChangedProp += \"" + f.CsName + ",\";"); } return true; } /// <summary> /// Read a primitive from the stream /// </summary> string FieldReaderType(Field f, string stream, string binaryReader, string instance) { if (f.OptionCodeType != null) { switch (f.OptionCodeType) { case "DateTime": switch (f.ProtoType.ProtoName) { case ProtoBuiltin.UInt64: case ProtoBuiltin.Int64: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed64: if (options.Utc) return "new DateTime((long)" + FieldReaderPrimitive(f, stream, binaryReader, instance) + ", DateTimeKind.Utc)"; else return "new DateTime((long)" + FieldReaderPrimitive(f, stream, binaryReader, instance) + ")"; } throw new ProtoFormatException("Local feature, DateTime, must be stored in a 64 bit field", f.Source); case "TimeSpan": switch (f.ProtoType.ProtoName) { case ProtoBuiltin.UInt64: case ProtoBuiltin.Int64: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed64: return "new TimeSpan((long)" + FieldReaderPrimitive(f, stream, binaryReader, instance) + ")"; } throw new ProtoFormatException("Local feature, TimeSpan, must be stored in a 64 bit field", f.Source); default: //Assume enum return "(" + f.OptionCodeType + ")" + FieldReaderPrimitive(f, stream, binaryReader, instance); } } return FieldReaderPrimitive(f, stream, binaryReader, instance); } static string FieldReaderPrimitive(Field f, string stream, string binaryReader, string instance) { if (f.ProtoType is ProtoMessage) { var m = f.ProtoType as ProtoMessage; if (f.Rule == FieldRule.Repeated || instance == null) return m.FullSerializerType + ".DeserializeLengthDelimited(" + stream + ")"; else return m.FullSerializerType + ".DeserializeLengthDelimited(" + stream + ", " + instance + ")"; } if (f.ProtoType is ProtoEnum) return "(" + f.ProtoType.FullCsType + ")" + ProtocolParser.Base + ".ReadUInt64(" + stream + ")"; if (f.ProtoType is ProtoBuiltin) { switch (f.ProtoType.ProtoName) { case ProtoBuiltin.Double: return binaryReader + ".ReadDouble()"; case ProtoBuiltin.Float: return binaryReader + ".ReadSingle()"; case ProtoBuiltin.Int32: //Wire format is 64 bit varint return "(int)" + ProtocolParser.Base + ".ReadUInt64(" + stream + ")"; case ProtoBuiltin.Int64: return "(long)" + ProtocolParser.Base + ".ReadUInt64(" + stream + ")"; case ProtoBuiltin.UInt32: return ProtocolParser.Base + ".ReadUInt32(" + stream + ")"; case ProtoBuiltin.UInt64: return ProtocolParser.Base + ".ReadUInt64(" + stream + ")"; case ProtoBuiltin.SInt32: return ProtocolParser.Base + ".ReadZInt32(" + stream + ")"; case ProtoBuiltin.SInt64: return ProtocolParser.Base + ".ReadZInt64(" + stream + ")"; case ProtoBuiltin.Fixed32: return binaryReader + ".ReadUInt32()"; case ProtoBuiltin.Fixed64: return binaryReader + ".ReadUInt64()"; case ProtoBuiltin.SFixed32: return binaryReader + ".ReadInt32()"; case ProtoBuiltin.SFixed64: return binaryReader + ".ReadInt64()"; case ProtoBuiltin.Bool: return ProtocolParser.Base + ".ReadBool(" + stream + ")"; case ProtoBuiltin.String: return ProtocolParser.Base + ".ReadString(" + stream + ")"; case ProtoBuiltin.Bytes: return ProtocolParser.Base + ".ReadBytes(" + stream + ")"; default: throw new ProtoFormatException("unknown build in: " + f.ProtoType.ProtoName, f.Source); } } throw new NotImplementedException(); } #endregion #region Writer static void KeyWriter(string stream, int id, Wire wire, CodeWriter cw) { uint n = ((uint)id << 3) | ((uint)wire); cw.Comment("Key for field: " + id + ", " + wire); //cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", " + n + ");"); VarintWriter(stream, n, cw); } /// <summary> /// Generates writer for a varint value known at compile time /// </summary> static void VarintWriter(string stream, uint value, CodeWriter cw) { while (true) { byte b = (byte)(value & 0x7F); value = value >> 7; if (value == 0) { cw.WriteLine(stream + ".WriteByte(" + b + ");"); break; } //Write part of value b |= 0x80; cw.WriteLine(stream + ".WriteByte(" + b + ");"); } } /// <summary> /// Generates inline writer of a length delimited byte array /// </summary> static void BytesWriter(Field f, string stream, CodeWriter cw) { cw.Comment("Length delimited byte array"); //Original //cw.WriteLine("ProtocolParser.WriteBytes(" + stream + ", " + memoryStream + ".ToArray());"); //Much slower than original /* cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", (uint)" + memoryStream + ".Length);"); cw.WriteLine(memoryStream + ".Seek(0, System.IO.SeekOrigin.Begin);"); cw.WriteLine(memoryStream + ".CopyTo(" + stream + ");"); */ //Same speed as original /* cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", (uint)" + memoryStream + ".Length);"); cw.WriteLine(stream + ".Write(" + memoryStream + ".ToArray(), 0, (int)" + memoryStream + ".Length);"); */ //10% faster than original using GetBuffer rather than ToArray cw.WriteLine("uint length" + f.ID + " = (uint)msField.Length;"); cw.WriteLine(ProtocolParser.Base + ".WriteUInt32(" + stream + ", length" + f.ID + ");"); cw.WriteLine("msField.WriteTo(" + stream + ");"); } /// <summary> /// Generates code for writing one field /// </summary> public void FieldWriter(ProtoMessage m, Field f, CodeWriter cw, Options options) { try { cw.WriteLine("if (instance.ChangedProp.IndexOf(\"" + f.CsName + "\") >= 0)"); cw.Bracket(); if (f.Rule == FieldRule.Repeated) { if (f.OptionPacked == true) { //Repeated packed cw.IfBracket("instance." + f.CsName + " != null"); KeyWriter("stream", f.ID, Wire.LengthDelimited, cw); if (f.ProtoType.WireSize < 0) { //Un-optimized, unknown size cw.WriteLine("msField.SetLength(0);"); if (f.IsUsingBinaryWriter) cw.WriteLine("BinaryWriter bw" + f.ID + " = new BinaryWriter(ms" + f.ID + ");"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); FieldWriterType(f, "msField", "bw" + f.ID, "i" + f.ID, cw); cw.EndBracket(); BytesWriter(f, "stream", cw); } else { //Optimized with known size //No memorystream buffering, write size first at once //For constant size messages we can skip serializing to the MemoryStream cw.WriteLine(ProtocolParser.Base + ".WriteUInt32(stream, " + f.ProtoType.WireSize + "u * (uint)instance." + f.CsName + ".Count);"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); FieldWriterType(f, "stream", "bw", "i" + f.ID, cw); cw.EndBracket(); } cw.EndBracket(); } else { //Repeated not packet cw.IfBracket("instance." + f.CsName + " != null"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); FieldWriterType(f, "stream", "bw", "i" + f.ID, cw); cw.EndBracket(); cw.EndBracket(); } return; } else if (f.Rule == FieldRule.Optional) { if (options.Nullable || f.ProtoType is ProtoMessage || f.ProtoType.ProtoName == ProtoBuiltin.String || f.ProtoType.ProtoName == ProtoBuiltin.Bytes) { if (f.ProtoType.Nullable || options.Nullable) //Struct always exist, not optional cw.IfBracket("instance." + f.CsName + " != null"); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); var needValue = !f.ProtoType.Nullable && options.Nullable; FieldWriterType(f, "stream", "bw", "instance." + f.CsName + (needValue ? ".Value" : ""), cw); if (f.ProtoType.Nullable || options.Nullable) //Struct always exist, not optional cw.EndBracket(); return; } if (f.ProtoType is ProtoEnum) { if (f.OptionDefault != null) cw.IfBracket("instance." + f.CsName + " != " + f.ProtoType.CsType + "." + f.OptionDefault); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); FieldWriterType(f, "stream", "bw", "instance." + f.CsName, cw); if (f.OptionDefault != null) cw.EndBracket(); return; } KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); FieldWriterType(f, "stream", "bw", "instance." + f.CsName, cw); return; } else if (f.Rule == FieldRule.Required) { if (f.ProtoType is ProtoMessage && f.ProtoType.OptionType != "struct" || f.ProtoType.ProtoName == ProtoBuiltin.String || f.ProtoType.ProtoName == ProtoBuiltin.Bytes) { cw.WriteLine("if (instance." + f.CsName + " == null)"); cw.WriteIndent("throw new global::SilentOrbit.ProtocolBuffers.ProtocolBufferException(\"" + f.CsName + " is required by the proto specification.\");"); } KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); FieldWriterType(f, "stream", "bw", "instance." + f.CsName, cw); return; } } finally { cw.EndBracket(); } throw new NotImplementedException("Unknown rule: " + f.Rule); } void FieldWriterType(Field f, string stream, string binaryWriter, string instance, CodeWriter cw) { if (f.OptionCodeType != null) { switch (f.OptionCodeType) { case "DateTime": if (options.Utc) { cw.WriteLine(FieldWriterPrimitive(f, stream, binaryWriter, "(" + instance + ".Kind == DateTimeKind.Utc ? " + instance + " : " + instance + ".ToUniversalTime()).Ticks")); } else cw.WriteLine(FieldWriterPrimitive(f, stream, binaryWriter, instance + ".Ticks")); return; case "TimeSpan": cw.WriteLine(FieldWriterPrimitive(f, stream, binaryWriter, instance + ".Ticks")); return; default: //enum break; } } cw.WriteLine(FieldWriterPrimitive(f, stream, binaryWriter, instance)); return; } static string FieldWriterPrimitive(Field f, string stream, string binaryWriter, string instance) { if (f.ProtoType is ProtoEnum) return ProtocolParser.Base + ".WriteUInt64(" + stream + ",(ulong)" + instance + ");"; if (f.ProtoType is ProtoMessage) { ProtoMessage pm = f.ProtoType as ProtoMessage; CodeWriter cw = new CodeWriter(); cw.WriteLine("msField.SetLength(0);"); cw.WriteLine(pm.FullSerializerType + ".Serialize(msField, " + instance + ");"); BytesWriter(f, stream, cw); return cw.Code; } switch (f.ProtoType.ProtoName) { case ProtoBuiltin.Double: case ProtoBuiltin.Float: case ProtoBuiltin.Fixed32: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed32: case ProtoBuiltin.SFixed64: return binaryWriter + ".Write(" + instance + ");"; case ProtoBuiltin.Int32: //Serialized as 64 bit varint return ProtocolParser.Base + ".WriteUInt64(" + stream + ",(ulong)" + instance + ");"; case ProtoBuiltin.Int64: return ProtocolParser.Base + ".WriteUInt64(" + stream + ",(ulong)" + instance + ");"; case ProtoBuiltin.UInt32: return ProtocolParser.Base + ".WriteUInt32(" + stream + ", " + instance + ");"; case ProtoBuiltin.UInt64: return ProtocolParser.Base + ".WriteUInt64(" + stream + ", " + instance + ");"; case ProtoBuiltin.SInt32: return ProtocolParser.Base + ".WriteZInt32(" + stream + ", " + instance + ");"; case ProtoBuiltin.SInt64: return ProtocolParser.Base + ".WriteZInt64(" + stream + ", " + instance + ");"; case ProtoBuiltin.Bool: return ProtocolParser.Base + ".WriteBool(" + stream + ", " + instance + ");"; case ProtoBuiltin.String: return ProtocolParser.Base + ".WriteBytes(" + stream + ", Encoding.UTF8.GetBytes(" + instance + "));"; case ProtoBuiltin.Bytes: return ProtocolParser.Base + ".WriteBytes(" + stream + ", " + instance + ");"; } throw new NotImplementedException(); } #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 AngularWebApi.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 Shouldly; using Veggerby.Algorithm.Calculus.Parser; using Xunit; namespace Veggerby.Algorithm.Tests.Calculus.Parser { public class SyntaxtParserTests { [Fact] public void Should_get_simple_parse_tree() { // arrange var parser = new SyntaxParser(); var xtoken = new Token(TokenType.Identifier, "x", new TokenPosition(0, 1, 0)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), xtoken, new Token(TokenType.End, null, new TokenPosition(1, 1, 1)) }; // act var actual = parser.ParseTree(tokens); // assert actual.Token.ShouldBe(xtoken); } [Fact] public void Should_get_parse_tree_binary() { // arrange var parser = new SyntaxParser(); var xToken = new Token(TokenType.Identifier, "x", new TokenPosition(0, 1, 0)); var signToken = new Token(TokenType.Sign, "+", new TokenPosition(1, 1, 1)); var numberToken = new Token(TokenType.Number, "1.2", new TokenPosition(2, 1, 2)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), xToken, signToken, numberToken, new Token(TokenType.End, null, new TokenPosition(5, 1, 5)) }; // act var actual = parser.ParseTree(tokens); // assert actual.ShouldBeOfType<BinaryNode>(); actual.Token.ShouldBe(signToken); ((BinaryNode)actual).Left.Token.ShouldBe(xToken); ((BinaryNode)actual).Right.Token.ShouldBe(numberToken); } [Fact] public void Should_get_parse_tree_unary_function() { // arrange var parser = new SyntaxParser(); var sinToken = new Token(TokenType.Function, "sin", new TokenPosition(0, 1, 0)); var startParenthesisToken = new Token(TokenType.StartParenthesis, "(", new TokenPosition(4, 1, 4)); var xToken = new Token(TokenType.Identifier, "x", new TokenPosition(5, 1, 5)); var endParenthesisToken = new Token(TokenType.EndParenthesis, ")", new TokenPosition(6, 1, 6)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), sinToken, startParenthesisToken, xToken, endParenthesisToken, new Token(TokenType.End, null, new TokenPosition(7, 1, 7)) }; // act var actual = parser.ParseTree(tokens); // assert actual.ShouldBeOfType<UnaryNode>(); actual.Token.ShouldBe(sinToken); ((UnaryNode)actual).Inner.Token.ShouldBe(xToken); } [Fact] public void Should_get_parse_tree_unary_factorial() { // arrange var parser = new SyntaxParser(); var xToken = new Token(TokenType.Identifier, "x", new TokenPosition(0, 1, 0)); var factorialToken = new Token(TokenType.Factorial, "!", new TokenPosition(1, 1, 1)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), xToken, factorialToken, new Token(TokenType.End, null, new TokenPosition(2, 1, 2)) }; // act var actual = parser.ParseTree(tokens); // assert actual.ShouldBeOfType<UnaryNode>(); actual.Token.ShouldBe(factorialToken); ((UnaryNode)actual).Inner.Token.ShouldBe(xToken); } [Fact] public void Should_get_parse_tree_binary_function() { // arrange var parser = new SyntaxParser(); var maxToken = new Token(TokenType.Function, "max", new TokenPosition(0, 1, 0)); var startParenthesisToken = new Token(TokenType.StartParenthesis, "(", new TokenPosition(4, 1, 4)); var xToken = new Token(TokenType.Identifier, "x", new TokenPosition(5, 1, 5)); var separatorToken = new Token(TokenType.Separator, "m", new TokenPosition(6, 1, 6)); var yToken = new Token(TokenType.Identifier, "y", new TokenPosition(7, 1, 7)); var endParenthesisToken = new Token(TokenType.EndParenthesis, ")", new TokenPosition(8, 1, 8)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), maxToken, startParenthesisToken, xToken, separatorToken, yToken, endParenthesisToken, new Token(TokenType.End, null, new TokenPosition(7, 1, 7)) }; // act var actual = parser.ParseTree(tokens); // assert actual.ShouldBeOfType<BinaryNode>(); actual.Token.ShouldBe(maxToken); ((BinaryNode)actual).Left.Token.ShouldBe(xToken); ((BinaryNode)actual).Right.Token.ShouldBe(yToken); } [Fact] public void Should_get_parse_tree_complex_function() { // arrange var parser = new SyntaxParser(); // x^2+sin(x*cos(3*pi-x)) var xToken1 = new Token(TokenType.Identifier, "x", new TokenPosition(0, 1, 0)); var powerToken = new Token(TokenType.OperatorPriority1, "^", new TokenPosition(1, 1, 1)); var constant2Token = new Token(TokenType.Number, "2", new TokenPosition(2, 1, 2)); var signPlusToken = new Token(TokenType.Sign, "+", new TokenPosition(3, 1, 3)); var sinToken = new Token(TokenType.Function, "sin", new TokenPosition(4, 1, 4)); var parenthesisToken1 = new Token(TokenType.StartParenthesis, "(", new TokenPosition(7, 1, 7)); var xToken2 = new Token(TokenType.Identifier, "x", new TokenPosition(8, 1, 8)); var multiplicationToken1 = new Token(TokenType.OperatorPriority1, "*", new TokenPosition(9, 1, 9)); var cosToken = new Token(TokenType.Function, "cos", new TokenPosition(10, 1, 10)); var parenthesisToken2 = new Token(TokenType.StartParenthesis, "(", new TokenPosition(11, 1, 11)); var constant3Token = new Token(TokenType.Number, "3", new TokenPosition(12, 1, 12)); var multiplicationToken2 = new Token(TokenType.OperatorPriority1, "*", new TokenPosition(13, 1, 13)); var piToken = new Token(TokenType.Identifier, "pi", new TokenPosition(15, 1, 15)); var signMinusToken = new Token(TokenType.Sign, "-", new TokenPosition(17, 1, 17)); var xToken3 = new Token(TokenType.Identifier, "x", new TokenPosition(18, 1, 18)); var parenthesisToken3 = new Token(TokenType.EndParenthesis, ")", new TokenPosition(19, 1, 19)); var parenthesisToken4 = new Token(TokenType.EndParenthesis, ")", new TokenPosition(20, 1, 20)); var tokens = new [] { new Token(TokenType.Start, null, new TokenPosition(0, 1, 0)), xToken1, powerToken, constant2Token, signPlusToken, sinToken, parenthesisToken1, xToken2, multiplicationToken1, cosToken, parenthesisToken2, constant3Token, multiplicationToken2, piToken, signMinusToken, xToken3, parenthesisToken3, parenthesisToken4, new Token(TokenType.End, null, new TokenPosition(21, 1, 21)) }; // act var actual = parser.ParseTree(tokens); // assert actual.ShouldBeOfType<BinaryNode>(); actual.Token.ShouldBe(signPlusToken); var left = ((BinaryNode)actual).Left as BinaryNode; var right = ((BinaryNode)actual).Right as UnaryNode; left.Token.ShouldBe(powerToken); right.Token.ShouldBe(sinToken); left.Left.Token.ShouldBe(xToken1); left.Right.Token.ShouldBe(constant2Token); right.Inner.Token.ShouldBe(multiplicationToken1); var rightInner = (BinaryNode)right.Inner; rightInner.Left.Token.ShouldBe(xToken2); rightInner.Right.Token.ShouldBe(cosToken); var cosInner = ((UnaryNode)rightInner.Right).Inner as BinaryNode; cosInner.Token.ShouldBe(signMinusToken); cosInner.Left.Token.ShouldBe(multiplicationToken2); cosInner.Right.Token.ShouldBe(xToken3); var cosInnerLeft = (BinaryNode)cosInner.Left; cosInnerLeft.Left.Token.ShouldBe(constant3Token); cosInnerLeft.Right.Token.ShouldBe(piToken); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 SensusService; using System; using System.IO; using System.Linq; using Xamarin.Forms; using SensusUI.Inputs; using System.Collections.Generic; using SensusService.Probes.User; using SensusService.Probes; using SensusService.Exceptions; using System.Threading; using ZXing; using Plugin.Permissions.Abstractions; namespace SensusUI { /// <summary> /// Displays all protocols. /// </summary> public class ProtocolsPage : ContentPage { private class ProtocolNameValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Protocol protocol = value as Protocol; if (protocol == null) return null; else return protocol.Name + " (" + (protocol.Running ? "Running" : "Stopped") + ")"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { new SensusException("Invalid call to " + GetType().FullName + ".ConvertBack."); return null; } } private class ProtocolColorValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Protocol protocol = value as Protocol; if (protocol == null) return Color.Default; else return protocol.Running ? Color.Green : Color.Red; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { new SensusException("Invalid call to " + GetType().FullName + ".ConvertBack."); return null; } } public static void ExecuteActionUponProtocolAuthentication(Protocol protocol, Action successAction, Action failAction = null) { if (protocol.LockPasswordHash == "") successAction(); else { SensusServiceHelper.Get().PromptForInputAsync( "Authenticate \"" + protocol.Name + "\"", new SingleLineTextInput("Protocol Password:", Keyboard.Text, true), null, true, null, null, null, null, false, input => { if (input == null) { if (failAction != null) failAction(); } else { string password = input.Value as string; if (password != null && SensusServiceHelper.Get().GetHash(password) == protocol.LockPasswordHash) successAction(); else { SensusServiceHelper.Get().FlashNotificationAsync("The password you entered was not correct."); if (failAction != null) failAction(); } } }); } } private ListView _protocolsList; public ProtocolsPage() { Title = "Your Sensus Studies"; _protocolsList = new ListView(); _protocolsList.ItemTemplate = new DataTemplate(typeof(TextCell)); _protocolsList.ItemTemplate.SetBinding(TextCell.TextProperty, new Binding(".", converter: new ProtocolNameValueConverter())); _protocolsList.ItemTemplate.SetBinding(TextCell.TextColorProperty, new Binding(".", converter: new ProtocolColorValueConverter())); _protocolsList.ItemTapped += async (o, e) => { if (_protocolsList.SelectedItem == null) return; Protocol selectedProtocol = _protocolsList.SelectedItem as Protocol; List<string> actions = new List<string>(); actions.Add(selectedProtocol.Running ? "Stop" : "Start"); if (selectedProtocol.Running) actions.Add("Display Participation"); actions.AddRange(new string[] { "Scan Participation Barcode", "Edit", "Copy", "Share" }); List<Protocol> groupableProtocols = SensusServiceHelper.Get().RegisteredProtocols.Where(registeredProtocol => registeredProtocol != selectedProtocol && registeredProtocol.Groupable && registeredProtocol.GroupedProtocols.Count == 0).ToList(); if (selectedProtocol.Groupable) { if (selectedProtocol.GroupedProtocols.Count == 0 && groupableProtocols.Count > 0) actions.Add("Group"); else if (selectedProtocol.GroupedProtocols.Count > 0) actions.Add("Ungroup"); } if (selectedProtocol.Running) actions.Add("Status"); actions.Add("Delete"); string selectedAction = await DisplayActionSheet(selectedProtocol.Name, "Cancel", null, actions.ToArray()); // must reset the protocol select manually Device.BeginInvokeOnMainThread(() => { _protocolsList.SelectedItem = null; }); if (selectedAction == "Start") { selectedProtocol.StartWithUserAgreementAsync(null, () => { // rebind to pick up color and running status changes Device.BeginInvokeOnMainThread(Bind); }); } else if (selectedAction == "Stop") { if (await DisplayAlert("Confirm Stop", "Are you sure you want to stop " + selectedProtocol.Name + "?", "Yes", "No")) { selectedProtocol.StopAsync(() => { // rebind to pick up color and running status changes Device.BeginInvokeOnMainThread(Bind); }); } } else if (selectedAction == "Display Participation") { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); // pop up wait screen while we submit the participation reward datum SensusServiceHelper.Get().PromptForInputsAsync( null, new InputGroup[] { new InputGroup("Please Wait", new LabelOnlyInput("Submitting participation information.", false)) }, cancellationTokenSource.Token, false, "Cancel", null, null, null, false, async () => { // add participation reward datum to remote data store and commit immediately ParticipationRewardDatum participationRewardDatum = new ParticipationRewardDatum(DateTimeOffset.UtcNow, selectedProtocol.Participation); selectedProtocol.RemoteDataStore.AddNonProbeDatum(participationRewardDatum); bool commitFailed; try { await selectedProtocol.RemoteDataStore.CommitAsync(cancellationTokenSource.Token); // we should not have any remaining non-probe data commitFailed = selectedProtocol.RemoteDataStore.HasNonProbeDatumToCommit(participationRewardDatum.Id); } catch (Exception) { commitFailed = true; } if (commitFailed) SensusServiceHelper.Get().FlashNotificationAsync("Failed to submit participation information to remote server. You will not be able to verify your participation at this time."); // cancel the token to close the input above, but only if the token hasn't already been canceled. if (!cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); Device.BeginInvokeOnMainThread(async() => { // only show the QR code for the reward datum if the datum was committed to the remote data store await Navigation.PushAsync(new ParticipationReportPage(selectedProtocol, participationRewardDatum, !commitFailed)); }); }, inputs => { // if the prompt was closed by the user instead of the cancellation token, cancel the token in order // to cancel the remote data store commit. if the prompt was closed by the termination of the remote // data store commit (i.e., by the canceled token), then don't cancel the token again. if (!cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); }); } else if (selectedAction == "Scan Participation Barcode") { Result barcodeResult = null; try { if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Camera) != PermissionStatus.Granted) throw new Exception("Could not access camera."); ZXing.Mobile.MobileBarcodeScanner scanner = SensusServiceHelper.Get().BarcodeScanner; if (scanner == null) throw new Exception("Barcode scanner not present."); scanner.TopText = "Position a Sensus participation barcode in the window below, with the red line across the middle of the barcode."; scanner.BottomText = "Sensus is not recording any of these images. Sensus is only trying to find a barcode."; scanner.CameraUnsupportedMessage = "There is not a supported camera on this phone. Cannot scan barcode."; barcodeResult = await scanner.Scan(new ZXing.Mobile.MobileBarcodeScanningOptions { PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE }.ToList() }); } catch (Exception ex) { string message = "Failed to scan barcode: " + ex.Message; SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType()); SensusServiceHelper.Get().FlashNotificationAsync(message); } if (barcodeResult != null) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); // pop up wait screen while we get the participation reward datum SensusServiceHelper.Get().PromptForInputsAsync( null, new InputGroup[] { new InputGroup("Please Wait", new LabelOnlyInput("Retrieving participation information.", false)) }, cancellationTokenSource.Token, false, "Cancel", null, null, null, false, async () => { try { ParticipationRewardDatum participationRewardDatum = await selectedProtocol.RemoteDataStore.GetDatum<ParticipationRewardDatum>(barcodeResult.Text, cancellationTokenSource.Token); // cancel the token to close the input above, but only if the token hasn't already been canceled. if (!cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); // ensure that the participation datum has not expired if (participationRewardDatum.Timestamp > DateTimeOffset.UtcNow.AddSeconds(-SensusServiceHelper.PARTICIPATION_VERIFICATION_TIMEOUT_SECONDS)) { Device.BeginInvokeOnMainThread(async() => { await Navigation.PushAsync(new VerifiedParticipationPage(selectedProtocol, participationRewardDatum)); }); } else SensusServiceHelper.Get().FlashNotificationAsync("Participation barcode has expired. The participant needs to regenerate the barcode."); } catch (Exception) { SensusServiceHelper.Get().FlashNotificationAsync("Failed to retrieve participation information."); } finally { // cancel the token to close the input above, but only if the token hasn't already been canceled. this will be // used if an exception is thrown while getting the participation reward datum. if (!cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); } }, inputs => { // if the prompt was closed by the user instead of the cancellation token, cancel the token in order // to cancel the datum retrieval. if the prompt was closed by the termination of the remote // data store get (i.e., by the canceled token), then don't cancel the token again. if (!cancellationTokenSource.IsCancellationRequested) cancellationTokenSource.Cancel(); }); } } else if (selectedAction == "Edit") { ExecuteActionUponProtocolAuthentication(selectedProtocol, () => { Device.BeginInvokeOnMainThread(async () => { ProtocolPage protocolPage = new ProtocolPage(selectedProtocol); protocolPage.Disappearing += (oo, ee) => Bind(); // rebind to pick up name changes await Navigation.PushAsync(protocolPage); }); } ); } else if (selectedAction == "Copy") selectedProtocol.CopyAsync(true, true); else if (selectedAction == "Share") { Action ShareSelectedProtocol = new Action(() => { // make a deep copy of the selected protocol so we can reset it for sharing selectedProtocol.CopyAsync(false, false, selectedProtocolCopy => { selectedProtocolCopy.ResetForSharing(); // write protocol to file and share string sharePath = SensusServiceHelper.Get().GetSharePath(".json"); selectedProtocolCopy.Save(sharePath); SensusServiceHelper.Get().ShareFileAsync(sharePath, "Sensus Protocol: " + selectedProtocolCopy.Name, "application/json"); }); }); if (selectedProtocol.Shareable) ShareSelectedProtocol(); else ExecuteActionUponProtocolAuthentication(selectedProtocol, ShareSelectedProtocol); } else if (selectedAction == "Group") { SensusServiceHelper.Get().PromptForInputAsync("Group", new ItemPickerPageInput("Select Protocols", groupableProtocols.Cast<object>().ToList(), "Name") { Multiselect = true }, null, true, "Group", null, null, null, false, input => { if (input == null) { SensusServiceHelper.Get().FlashNotificationAsync("No protocols grouped."); return; } ItemPickerPageInput itemPickerPageInput = input as ItemPickerPageInput; List<Protocol> selectedProtocols = (itemPickerPageInput.Value as List<object>).Cast<Protocol>().ToList(); if (selectedProtocols.Count == 0) SensusServiceHelper.Get().FlashNotificationAsync("No protocols grouped."); else { selectedProtocol.GroupedProtocols.AddRange(selectedProtocols); SensusServiceHelper.Get().FlashNotificationAsync("Grouped \"" + selectedProtocol.Name + "\" with " + selectedProtocols.Count + " other protocol" + (selectedProtocols.Count == 1 ? "" : "s") + "."); } }); } else if (selectedAction == "Ungroup") { if (await DisplayAlert("Ungroup " + selectedProtocol.Name + "?", "This protocol is currently grouped with the following other protocols:" + Environment.NewLine + Environment.NewLine + string.Concat(selectedProtocol.GroupedProtocols.Select(protocol => protocol.Name + Environment.NewLine)), "Ungroup", "Cancel")) selectedProtocol.GroupedProtocols.Clear(); } else if (selectedAction == "Status") { if (SensusServiceHelper.Get().ProtocolShouldBeRunning(selectedProtocol)) { selectedProtocol.TestHealthAsync(true, () => { Device.BeginInvokeOnMainThread(async () => { if (selectedProtocol.MostRecentReport == null) await DisplayAlert("No Report", "Status check failed.", "OK"); else await Navigation.PushAsync(new ViewTextLinesPage("Protocol Status", selectedProtocol.MostRecentReport.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(), null, null)); }); }); } else await DisplayAlert("Protocol Not Running", "Cannot check status of protocol when protocol is not running.", "OK"); } else if (selectedAction == "Delete") { if (await DisplayAlert("Delete " + selectedProtocol.Name + "?", "This action cannot be undone.", "Delete", "Cancel")) selectedProtocol.DeleteAsync(); } }; Content = _protocolsList; ToolbarItems.Add(new ToolbarItem(null, "gear_wrench.png", async () => { double shareDirectoryMB = SensusServiceHelper.GetDirectorySizeMB(SensusServiceHelper.SHARE_DIRECTORY); string clearShareDirectoryAction = "Clear Share Directory (" + Math.Round(shareDirectoryMB, 1) + " MB)"; List<string> buttons = new string[] { "New Protocol", "View Log", "View Points of Interest", clearShareDirectoryAction }.ToList(); // stopping only makes sense on android, where we use a background service. on ios, there is no concept // of stopping the app other than the user or system terminating the app. #if __ANDROID__ buttons.Add("Stop Sensus"); #endif string action = await DisplayActionSheet("Other Actions", "Back", null, buttons.ToArray()); if (action == "New Protocol") Protocol.CreateAsync("New Protocol", null); else if (action == "View Log") { await Navigation.PushAsync(new ViewTextLinesPage("Log", SensusServiceHelper.Get().Logger.Read(200, true), () => { string sharePath = null; try { sharePath = SensusServiceHelper.Get().GetSharePath(".txt"); SensusServiceHelper.Get().Logger.CopyTo(sharePath); } catch (Exception) { sharePath = null; } if (sharePath != null) SensusServiceHelper.Get().ShareFileAsync(sharePath, "Log: " + Path.GetFileName(sharePath), "text/plain"); }, () => SensusServiceHelper.Get().Logger.Clear())); } else if (action == "View Points of Interest") await Navigation.PushAsync(new PointsOfInterestPage(SensusServiceHelper.Get().PointsOfInterest)); else if (action == clearShareDirectoryAction) { foreach (string sharePath in Directory.GetFiles(SensusServiceHelper.SHARE_DIRECTORY)) { try { File.Delete(sharePath); } catch (Exception ex) { string errorMessage = "Failed to delete shared file \"" + Path.GetFileName(sharePath) + "\": " + ex.Message; SensusServiceHelper.Get().FlashNotificationAsync(errorMessage); SensusServiceHelper.Get().Logger.Log(errorMessage, LoggingLevel.Normal, GetType()); } } } #if __ANDROID__ else if (action == "Stop Sensus" && await DisplayAlert("Confirm", "Are you sure you want to stop Sensus? This will end your participation in all studies.", "Stop Sensus", "Go Back")) SensusServiceHelper.Get().Stop(); #endif })); } public void Bind() { _protocolsList.ItemsSource = null; SensusServiceHelper serviceHelper = SensusServiceHelper.Get(); // make sure we have a service helper -- it might get disconnected before we get the OnDisappearing event that calls Bind if (serviceHelper != null) _protocolsList.ItemsSource = serviceHelper.RegisteredProtocols; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.OpsWorks.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// UpdateStack Request Marshaller /// </summary> public class UpdateStackRequestMarshaller : IMarshaller<IRequest, UpdateStackRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateStackRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateStackRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.OpsWorks"); string target = "OpsWorks_20130218.UpdateStack"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAgentVersion()) { context.Writer.WritePropertyName("AgentVersion"); context.Writer.Write(publicRequest.AgentVersion); } if(publicRequest.IsSetAttributes()) { context.Writer.WritePropertyName("Attributes"); context.Writer.WriteObjectStart(); foreach (var publicRequestAttributesKvp in publicRequest.Attributes) { context.Writer.WritePropertyName(publicRequestAttributesKvp.Key); var publicRequestAttributesValue = publicRequestAttributesKvp.Value; context.Writer.Write(publicRequestAttributesValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetChefConfiguration()) { context.Writer.WritePropertyName("ChefConfiguration"); context.Writer.WriteObjectStart(); var marshaller = ChefConfigurationMarshaller.Instance; marshaller.Marshall(publicRequest.ChefConfiguration, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetConfigurationManager()) { context.Writer.WritePropertyName("ConfigurationManager"); context.Writer.WriteObjectStart(); var marshaller = StackConfigurationManagerMarshaller.Instance; marshaller.Marshall(publicRequest.ConfigurationManager, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetCustomCookbooksSource()) { context.Writer.WritePropertyName("CustomCookbooksSource"); context.Writer.WriteObjectStart(); var marshaller = SourceMarshaller.Instance; marshaller.Marshall(publicRequest.CustomCookbooksSource, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetCustomJson()) { context.Writer.WritePropertyName("CustomJson"); context.Writer.Write(publicRequest.CustomJson); } if(publicRequest.IsSetDefaultAvailabilityZone()) { context.Writer.WritePropertyName("DefaultAvailabilityZone"); context.Writer.Write(publicRequest.DefaultAvailabilityZone); } if(publicRequest.IsSetDefaultInstanceProfileArn()) { context.Writer.WritePropertyName("DefaultInstanceProfileArn"); context.Writer.Write(publicRequest.DefaultInstanceProfileArn); } if(publicRequest.IsSetDefaultOs()) { context.Writer.WritePropertyName("DefaultOs"); context.Writer.Write(publicRequest.DefaultOs); } if(publicRequest.IsSetDefaultRootDeviceType()) { context.Writer.WritePropertyName("DefaultRootDeviceType"); context.Writer.Write(publicRequest.DefaultRootDeviceType); } if(publicRequest.IsSetDefaultSshKeyName()) { context.Writer.WritePropertyName("DefaultSshKeyName"); context.Writer.Write(publicRequest.DefaultSshKeyName); } if(publicRequest.IsSetDefaultSubnetId()) { context.Writer.WritePropertyName("DefaultSubnetId"); context.Writer.Write(publicRequest.DefaultSubnetId); } if(publicRequest.IsSetHostnameTheme()) { context.Writer.WritePropertyName("HostnameTheme"); context.Writer.Write(publicRequest.HostnameTheme); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetServiceRoleArn()) { context.Writer.WritePropertyName("ServiceRoleArn"); context.Writer.Write(publicRequest.ServiceRoleArn); } if(publicRequest.IsSetStackId()) { context.Writer.WritePropertyName("StackId"); context.Writer.Write(publicRequest.StackId); } if(publicRequest.IsSetUseCustomCookbooks()) { context.Writer.WritePropertyName("UseCustomCookbooks"); context.Writer.Write(publicRequest.UseCustomCookbooks); } if(publicRequest.IsSetUseOpsworksSecurityGroups()) { context.Writer.WritePropertyName("UseOpsworksSecurityGroups"); context.Writer.Write(publicRequest.UseOpsworksSecurityGroups); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
using System; using System.Buffers.Text; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Orleans.Runtime { [Serializable] internal class UniqueKey : IComparable<UniqueKey>, IEquatable<UniqueKey> { private const ulong TYPE_CODE_DATA_MASK = 0xFFFFFFFF; // Lowest 4 bytes private static readonly char[] KeyExtSeparationChar = {'+'}; /// <summary> /// Type id values encoded into UniqueKeys /// </summary> public enum Category : byte { None = 0, SystemTarget = 1, SystemGrain = 2, Grain = 3, Client = 4, KeyExtGrain = 6, GeoClient = 7, KeyExtSystemTarget = 8, } public UInt64 N0 { get; private set; } public UInt64 N1 { get; private set; } public UInt64 TypeCodeData { get; private set; } public string KeyExt { get; private set; } [NonSerialized] private uint uniformHashCache; public int BaseTypeCode { get { return (int)(TypeCodeData & TYPE_CODE_DATA_MASK); } } public Category IdCategory { get { return GetCategory(TypeCodeData); } } public bool IsLongKey { get { return N0 == 0; } } public bool IsSystemTargetKey => IsSystemTarget(IdCategory); private static bool IsSystemTarget(Category category) => category == Category.SystemTarget || category == Category.KeyExtSystemTarget; public bool HasKeyExt => IsKeyExt(IdCategory); private static bool IsKeyExt(Category category) => category == Category.KeyExtGrain || category == Category.KeyExtSystemTarget || category == Category.GeoClient; // geo clients use the KeyExt string to specify the cluster id internal static readonly UniqueKey Empty = new UniqueKey { N0 = 0, N1 = 0, TypeCodeData = 0, KeyExt = null }; internal static UniqueKey Parse(ReadOnlySpan<char> input) { var trimmed = input.Trim().ToString(); // first, for convenience we attempt to parse the string using GUID syntax. this is needed by unit // tests but i don't know if it's needed for production. Guid guid; if (Guid.TryParse(trimmed, out guid)) return NewKey(guid); else { var fields = trimmed.Split(KeyExtSeparationChar, 2); var n0 = ulong.Parse(fields[0].Substring(0, 16), NumberStyles.HexNumber); var n1 = ulong.Parse(fields[0].Substring(16, 16), NumberStyles.HexNumber); var typeCodeData = ulong.Parse(fields[0].Substring(32, 16), NumberStyles.HexNumber); string keyExt = null; switch (fields.Length) { default: throw new InvalidDataException("UniqueKey hex strings cannot contain more than one + separator."); case 1: break; case 2: if (fields[1] != "null") { keyExt = fields[1]; } break; } return NewKey(n0, n1, typeCodeData, keyExt); } } private static UniqueKey NewKey(ulong n0, ulong n1, Category category, long typeData, string keyExt) { if (!IsKeyExt(category) && keyExt != null) throw new ArgumentException("Only key extended grains can specify a non-null key extension."); var typeCodeData = ((ulong)category << 56) + ((ulong)typeData & 0x00FFFFFFFFFFFFFF); return NewKey(n0, n1, typeCodeData, keyExt); } internal static UniqueKey NewKey(long longKey, Category category = Category.None, long typeData = 0, string keyExt = null) { ThrowIfIsSystemTargetKey(category); var n1 = unchecked((ulong)longKey); return NewKey(0, n1, category, typeData, keyExt); } public static UniqueKey NewKey() { return NewKey(Guid.NewGuid()); } internal static UniqueKey NewKey(Guid guid, Category category = Category.None, long typeData = 0, string keyExt = null) { ThrowIfIsSystemTargetKey(category); var guidBytes = guid.ToByteArray(); var n0 = BitConverter.ToUInt64(guidBytes, 0); var n1 = BitConverter.ToUInt64(guidBytes, 8); return NewKey(n0, n1, category, typeData, keyExt); } public static UniqueKey NewSystemTargetKey(Guid guid, long typeData) { var guidBytes = guid.ToByteArray(); var n0 = BitConverter.ToUInt64(guidBytes, 0); var n1 = BitConverter.ToUInt64(guidBytes, 8); return NewKey(n0, n1, Category.SystemTarget, typeData, null); } public static UniqueKey NewSystemTargetKey(short systemId) { ulong n1 = unchecked((ulong)systemId); return NewKey(0, n1, Category.SystemTarget, 0, null); } public static UniqueKey NewGrainServiceKey(short key, long typeData) { ulong n1 = unchecked((ulong)key); return NewKey(0, n1, Category.SystemTarget, typeData, null); } public static UniqueKey NewGrainServiceKey(string key, long typeData) { return NewKey(0, 0, Category.KeyExtSystemTarget, typeData, key); } internal static UniqueKey NewKey(ulong n0, ulong n1, ulong typeCodeData, string keyExt) { ValidateKeyExt(keyExt, typeCodeData); return new UniqueKey { N0 = n0, N1 = n1, TypeCodeData = typeCodeData, KeyExt = keyExt }; } private void ThrowIfIsNotLong() { if (!IsLongKey) throw new InvalidOperationException("this key cannot be interpreted as a long value"); } private static void ThrowIfIsSystemTargetKey(Category category) { if (IsSystemTarget(category)) throw new ArgumentException( "This overload of NewKey cannot be used to construct an instance of UniqueKey containing a SystemTarget id."); } private void ThrowIfHasKeyExt(string methodName) { if (HasKeyExt) throw new InvalidOperationException( string.Format( "This overload of {0} cannot be used if the grain uses the primary key extension feature.", methodName)); } public long PrimaryKeyToLong(out string extendedKey) { ThrowIfIsNotLong(); extendedKey = this.KeyExt; return unchecked((long)N1); } public long PrimaryKeyToLong() { ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToLong"); string unused; return PrimaryKeyToLong(out unused); } public Guid PrimaryKeyToGuid(out string extendedKey) { extendedKey = this.KeyExt; return ConvertToGuid(); } public Guid PrimaryKeyToGuid() { ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToGuid"); string unused; return PrimaryKeyToGuid(out unused); } public string ClusterId { get { if (IdCategory != Category.GeoClient) throw new InvalidOperationException("ClusterId is only defined for geo clients"); return this.KeyExt; } } public override bool Equals(object o) { return o is UniqueKey && Equals((UniqueKey)o); } // We really want Equals to be as fast as possible, as a minimum cost, as close to native as possible. // No function calls, no boxing, inline. public bool Equals(UniqueKey other) { return N0 == other.N0 && N1 == other.N1 && TypeCodeData == other.TypeCodeData && (!HasKeyExt || KeyExt == other.KeyExt); } // We really want CompareTo to be as fast as possible, as a minimum cost, as close to native as possible. // No function calls, no boxing, inline. public int CompareTo(UniqueKey other) { return TypeCodeData < other.TypeCodeData ? -1 : TypeCodeData > other.TypeCodeData ? 1 : N0 < other.N0 ? -1 : N0 > other.N0 ? 1 : N1 < other.N1 ? -1 : N1 > other.N1 ? 1 : !HasKeyExt || KeyExt == null ? 0 : String.Compare(KeyExt, other.KeyExt, StringComparison.Ordinal); } public override int GetHashCode() { return unchecked((int)GetUniformHashCode()); } internal uint GetUniformHashCode() { // Disabling this ReSharper warning; hashCache is a logically read-only variable, so accessing them in GetHashCode is safe. // ReSharper disable NonReadonlyFieldInGetHashCode if (uniformHashCache == 0) { uint n; if (HasKeyExt && KeyExt != null) { n = JenkinsHash.ComputeHash(this.ToByteArray()); } else { n = JenkinsHash.ComputeHash(TypeCodeData, N0, N1); } // Unchecked is required because the Jenkins hash is an unsigned 32-bit integer, // which we need to convert to a signed 32-bit integer. uniformHashCache = n; } return uniformHashCache; // ReSharper restore NonReadonlyFieldInGetHashCode } /// <summary> /// If KeyExt not exists, returns following structure /// |8 bytes|8 bytes|8 bytes|4 bytes| - total 28 bytes. /// If KeyExt exists, adds additional KeyExt bytes length /// </summary> /// <returns></returns> internal ReadOnlySpan<byte> ToByteArray() { var extBytes = this.KeyExt != null ? Encoding.UTF8.GetBytes(KeyExt) : null; var extBytesLength = extBytes?.Length ?? 0; var sizeWithoutExtBytes = sizeof(ulong) * 3 + sizeof(int); var spanBytes = new byte[sizeWithoutExtBytes + extBytesLength].AsSpan(); var offset = 0; var ulongBytes = MemoryMarshal.Cast<byte, ulong>(spanBytes.Slice(offset, sizeof(ulong) * 3)); ulongBytes[0] = this.N0; ulongBytes[1] = this.N1; ulongBytes[2] = this.TypeCodeData; offset += sizeof(ulong) * 3; // Copy KeyExt if (extBytes != null) { MemoryMarshal.Cast<byte, int>(spanBytes.Slice(offset, sizeof(int)))[0] = extBytesLength; offset += sizeof(int); extBytes.CopyTo(spanBytes.Slice(offset, extBytesLength)); } else { MemoryMarshal.Cast<byte, int>(spanBytes.Slice(offset, sizeof(int)))[0] = -1; } return spanBytes; } private Guid ConvertToGuid() { return new Guid((UInt32)(N0 & 0xffffffff), (UInt16)(N0 >> 32), (UInt16)(N0 >> 48), (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56)); } public override string ToString() { return ToHexString(); } internal string ToHexString() { var s = new StringBuilder(); s.AppendFormat("{0:x16}{1:x16}{2:x16}", N0, N1, TypeCodeData); if (!HasKeyExt) return s.ToString(); s.Append("+"); s.Append(KeyExt ?? "null"); return s.ToString(); } private static void ValidateKeyExt(string keyExt, UInt64 typeCodeData) { Category category = GetCategory(typeCodeData); if (category == Category.KeyExtGrain || category == Category.KeyExtSystemTarget) { if (string.IsNullOrWhiteSpace(keyExt)) { if (null == keyExt) { throw new ArgumentNullException("keyExt"); } else { throw new ArgumentException("Extended key is empty or white space.", "keyExt"); } } } else if (category != Category.GeoClient && null != keyExt) { throw new ArgumentException("Extended key field is not null in non-extended UniqueIdentifier."); } } internal static Category GetCategory(UInt64 typeCodeData) { return (Category)((typeCodeData >> 56) & 0xFF); } } }
using System; using Raksha.Crypto; using Raksha.Security; using Raksha.Crypto.Engines; using Raksha.Crypto.Generators; using Raksha.Crypto.Modes; using Raksha.Crypto.Parameters; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; using NUnit.Framework; namespace Raksha.Tests.Crypto { internal class DesParityTest : SimpleTest { public override string Name { get { return "DESParityTest"; } } public override void PerformTest() { byte[] k1In = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff }; byte[] k1Out = { (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe }; byte[] k2In = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f, (byte)0xaa, (byte)0x99, (byte)0x7f, (byte)0x63 }; byte[] k2Out = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f, (byte)0xab, (byte)0x98, (byte)0x7f, (byte)0x62 }; DesParameters.SetOddParity(k1In); for (int i = 0; i != k1In.Length; i++) { if (k1In[i] != k1Out[i]) { Fail("Failed " + "got " + Hex.ToHexString(k1In) + " expected " + Hex.ToHexString(k1Out)); } } DesParameters.SetOddParity(k2In); for (int i = 0; i != k2In.Length; i++) { if (k2In[i] != k2Out[i]) { Fail("Failed " + "got " + Hex.ToHexString(k2In) + " expected " + Hex.ToHexString(k2Out)); } } } } internal class KeyGenTest : SimpleTest { public override string Name { get { return "KeyGenTest"; } } public override void PerformTest() { DesKeyGenerator keyGen = new DesKeyGenerator(); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 56)); byte[] kB = keyGen.GenerateKey(); if (kB.Length != 8) { Fail("DES bit key wrong length."); } } } internal class DesParametersTest : SimpleTest { private static readonly byte[] weakKeys = { (byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01, (byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01, (byte)0x1f,(byte)0x1f,(byte)0x1f,(byte)0x1f, (byte)0x0e,(byte)0x0e,(byte)0x0e,(byte)0x0e, (byte)0xe0,(byte)0xe0,(byte)0xe0,(byte)0xe0, (byte)0xf1,(byte)0xf1,(byte)0xf1,(byte)0xf1, (byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe, (byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe, /* semi-weak keys */ (byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe, (byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe, (byte)0x1f,(byte)0xe0,(byte)0x1f,(byte)0xe0, (byte)0x0e,(byte)0xf1,(byte)0x0e,(byte)0xf1, (byte)0x01,(byte)0xe0,(byte)0x01,(byte)0xe0, (byte)0x01,(byte)0xf1,(byte)0x01,(byte)0xf1, (byte)0x1f,(byte)0xfe,(byte)0x1f,(byte)0xfe, (byte)0x0e,(byte)0xfe,(byte)0x0e,(byte)0xfe, (byte)0x01,(byte)0x1f,(byte)0x01,(byte)0x1f, (byte)0x01,(byte)0x0e,(byte)0x01,(byte)0x0e, (byte)0xe0,(byte)0xfe,(byte)0xe0,(byte)0xfe, (byte)0xf1,(byte)0xfe,(byte)0xf1,(byte)0xfe, (byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01, (byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01, (byte)0xe0,(byte)0x1f,(byte)0xe0,(byte)0x1f, (byte)0xf1,(byte)0x0e,(byte)0xf1,(byte)0x0e, (byte)0xe0,(byte)0x01,(byte)0xe0,(byte)0x01, (byte)0xf1,(byte)0x01,(byte)0xf1,(byte)0x01, (byte)0xfe,(byte)0x1f,(byte)0xfe,(byte)0x1f, (byte)0xfe,(byte)0x0e,(byte)0xfe,(byte)0x0e, (byte)0x1f,(byte)0x01,(byte)0x1f,(byte)0x01, (byte)0x0e,(byte)0x01,(byte)0x0e,(byte)0x01, (byte)0xfe,(byte)0xe0,(byte)0xfe,(byte)0xe0, (byte)0xfe,(byte)0xf1,(byte)0xfe,(byte)0xf1 }; public override string Name { get { return "DesParameters"; } } public override void PerformTest() { try { DesParameters.IsWeakKey(new byte[4], 0); Fail("no exception on small key"); } catch (ArgumentException e) { if (!e.Message.Equals("key material too short.")) { Fail("wrong exception"); } } try { new DesParameters(weakKeys); Fail("no exception on weak key"); } catch (ArgumentException e) { if (!e.Message.Equals("attempt to create weak DES key")) { Fail("wrong exception"); } } for (int i = 0; i != weakKeys.Length; i += 8) { if (!DesParameters.IsWeakKey(weakKeys, i)) { Fail("weakKey test failed"); } } } } /** * DES tester - vectors from <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIPS 81</a> */ [TestFixture] public class DesTest : CipherTest { static string input1 = "4e6f77206973207468652074696d6520666f7220616c6c20"; static string input2 = "4e6f7720697320746865"; static string input3 = "4e6f7720697320746865aabbcc"; static SimpleTest[] tests = { new BlockCipherVectorTest(0, new DesEngine(), new DesParameters(Hex.Decode("0123456789abcdef")), input1, "3fa40e8a984d48156a271787ab8883f9893d51ec4b563b53"), new BlockCipherVectorTest(1, new CbcBlockCipher(new DesEngine()), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input1, "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6"), new BlockCipherVectorTest(2, new CfbBlockCipher(new DesEngine(), 8), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input2, "f31fda07011462ee187f"), new BlockCipherVectorTest(3, new CfbBlockCipher(new DesEngine(), 64), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input1, "f3096249c7f46e51a69e839b1a92f78403467133898ea622"), new BlockCipherVectorTest(4, new OfbBlockCipher(new DesEngine(), 8), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input2, "f34a2850c9c64985d684"), new BlockCipherVectorTest(5, new CfbBlockCipher(new DesEngine(), 64), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input3, "f3096249c7f46e51a69e0954bf"), new BlockCipherVectorTest(6, new OfbBlockCipher(new DesEngine(), 64), new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")), input3, "f3096249c7f46e5135f2c0eb8b"), new DesParityTest(), new DesParametersTest(), new KeyGenTest() }; public DesTest() : base(tests, new DesEngine(), new DesParameters(new byte[8])) { } public override string Name { get { return "DES"; } } public static void Main( string[] args) { RunTest(new DesTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// 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.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(code != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; Code = code; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Creates a new version of this script with the source code specified. /// </summary> /// <param name="code">The source code of the script.</param> public Script WithCode(string code) => WithCodeInternal(code); internal abstract Script WithCodeInternal(string code); /// <summary> /// Creates a new version of this script with the specified globals type. /// The members of this type can be accessed by the script as global variables. /// </summary> /// <param name="globalsType">The type that defines members that can be accessed by the script.</param> public Script WithGlobalsType(Type globalsType) => WithGlobalsTypeInternal(globalsType); internal abstract Script WithGlobalsTypeInternal(Type globalsType); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) => new Script<TResult>(Compiler, Builder, code ?? "", options ?? Options, GlobalsType, this); /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> public Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) => CommonContinueAsync(previousState, cancellationToken); internal abstract Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken); /// <summary> /// Forces the script through the build step. /// If not called directly, the build step will occur on the first call to Run. /// </summary> public void Build(CancellationToken cancellationToken = default(CancellationToken)) => CommonBuild(cancellationToken); internal abstract void CommonBuild(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation() { var references = Options.References; var previous = Previous; if (previous != null) { // TODO (tomat): RESOLVED? bound imports should be reused from previous submission instead of passing // them to every submission in the chain. See bug #7802. var compilation = previous.GetCompilation(); return ImmutableArray.CreateRange(references.Union(compilation.References)); } var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references = references.Add(corLib); if (GlobalsType != null) { var globalsTypeAssembly = MetadataReference.CreateFromAssemblyInternal(GlobalsType.GetTypeInfo().Assembly); references = references.Add(globalsTypeAssembly); } return references; } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, code, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous); } public new Script<T> WithCode(string code) { code = code ?? ""; return (code == Code) ? this : new Script<T>(Compiler, Builder, code, Options, GlobalsType, Previous); } public new Script<T> WithGlobalsType(Type globalsType) { return (globalsType == GlobalsType) ? this : new Script<T>(Compiler, Builder, Code, Options, globalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override Script WithCodeInternal(string code) => WithCode(code); internal override Script WithGlobalsTypeInternal(Type globalsType) => WithGlobalsType(globalsType); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> internal override void CommonBuild(CancellationToken cancellationToken) { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken) => ContinueAsync(previousState, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> public new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor contruction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, token); }; } /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> public new Task<ScriptState<T>> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor contruction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, CancellationToken cancellationToken) { var result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); return new ScriptState<T>(executionState, result, this); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; using GSF.ASN1.Types; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Choice(Name = "CS_Status_Response")] public class CS_Status_Response : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(CS_Status_Response)); private FullResponseSequenceType fullResponse_; private bool fullResponse_selected; private NullObject noExtraResponse_; private bool noExtraResponse_selected; [ASN1Element(Name = "fullResponse", IsOptional = false, HasTag = false, HasDefaultValue = false)] public FullResponseSequenceType FullResponse { get { return fullResponse_; } set { selectFullResponse(value); } } [ASN1Null(Name = "noExtraResponse")] [ASN1Element(Name = "noExtraResponse", IsOptional = false, HasTag = false, HasDefaultValue = false)] public NullObject NoExtraResponse { get { return noExtraResponse_; } set { selectNoExtraResponse(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isFullResponseSelected() { return fullResponse_selected; } public void selectFullResponse(FullResponseSequenceType val) { fullResponse_ = val; fullResponse_selected = true; noExtraResponse_selected = false; } public bool isNoExtraResponseSelected() { return noExtraResponse_selected; } public void selectNoExtraResponse() { selectNoExtraResponse(new NullObject()); } public void selectNoExtraResponse(NullObject val) { noExtraResponse_ = val; noExtraResponse_selected = true; fullResponse_selected = false; } [ASN1PreparedElement] [ASN1Sequence(Name = "fullResponse", IsSet = false)] public class FullResponseSequenceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(FullResponseSequenceType)); private ExtendedStatus extendedStatusMask_; private ExtendedStatus extendedStatus_; private OperationState operationState_; private SelectedProgramInvocationChoiceType selectedProgramInvocation_; [ASN1Element(Name = "operationState", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public OperationState OperationState { get { return operationState_; } set { operationState_ = value; } } [ASN1Element(Name = "extendedStatus", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public ExtendedStatus ExtendedStatus { get { return extendedStatus_; } set { extendedStatus_ = value; } } [ASN1Element(Name = "extendedStatusMask", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = true)] public ExtendedStatus ExtendedStatusMask { get { return extendedStatusMask_; } set { extendedStatusMask_ = value; } } [ASN1Element(Name = "selectedProgramInvocation", IsOptional = false, HasTag = false, HasDefaultValue = false)] public SelectedProgramInvocationChoiceType SelectedProgramInvocation { get { return selectedProgramInvocation_; } set { selectedProgramInvocation_ = value; } } public void initWithDefaults() { ExtendedStatus param_ExtendedStatusMask = new ExtendedStatus(CoderUtils.defStringToOctetString("'1111'B")); ExtendedStatusMask = param_ExtendedStatusMask; } public IASN1PreparedElementData PreparedData { get { return preparedData; } } [ASN1PreparedElement] [ASN1Choice(Name = "selectedProgramInvocation")] public class SelectedProgramInvocationChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(SelectedProgramInvocationChoiceType)); private NullObject noneSelected_; private bool noneSelected_selected; private Identifier programInvocation_; private bool programInvocation_selected; [ASN1Element(Name = "programInvocation", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)] public Identifier ProgramInvocation { get { return programInvocation_; } set { selectProgramInvocation(value); } } [ASN1Null(Name = "noneSelected")] [ASN1Element(Name = "noneSelected", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public NullObject NoneSelected { get { return noneSelected_; } set { selectNoneSelected(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isProgramInvocationSelected() { return programInvocation_selected; } public void selectProgramInvocation(Identifier val) { programInvocation_ = val; programInvocation_selected = true; noneSelected_selected = false; } public bool isNoneSelectedSelected() { return noneSelected_selected; } public void selectNoneSelected() { selectNoneSelected(new NullObject()); } public void selectNoneSelected(NullObject val) { noneSelected_ = val; noneSelected_selected = true; programInvocation_selected = false; } } } } }
using ATL.Logging; using Commons; using System; using System.Collections.Generic; using System.IO; using System.Text; using static ATL.AudioData.AudioDataManager; using static ATL.ChannelsArrangements; namespace ATL.AudioData.IO { /// <summary> /// Class for Audio Interchange File Format files manipulation (extension : .AIF, .AIFF, .AIFC) /// /// Implementation notes /// /// 1/ Annotations being somehow deprecated (Cf. specs "Use of this chunk is discouraged within FORM AIFC. The more refined Comments Chunk should be used instead"), /// any data read from an ANNO chunk will be written as a COMT chunk when updating the file (ANNO chunks will be deleted in the process). /// /// 2/ Embedded MIDI detection, parsing and writing is not supported /// /// 3/ Instrument detection, parsing and writing is not supported /// </summary> class AIFF : MetaDataIO, IAudioDataIO, IMetaDataEmbedder { public const string AIFF_CONTAINER_ID = "FORM"; private const string FORMTYPE_AIFF = "AIFF"; private const string FORMTYPE_AIFC = "AIFC"; private const string COMPRESSION_NONE = "NONE"; private const string COMPRESSION_NONE_LE = "sowt"; private const string CHUNKTYPE_COMMON = "COMM"; private const string CHUNKTYPE_SOUND = "SSND"; private const string CHUNKTYPE_MARKER = "MARK"; private const string CHUNKTYPE_INSTRUMENT = "INST"; private const string CHUNKTYPE_COMMENTS = "COMT"; private const string CHUNKTYPE_NAME = "NAME"; private const string CHUNKTYPE_AUTHOR = "AUTH"; private const string CHUNKTYPE_COPYRIGHT = "(c) "; private const string CHUNKTYPE_ANNOTATION = "ANNO"; // Use in discouraged by specs in favour of COMT private const string CHUNKTYPE_ID3TAG = "ID3 "; // AIFx timestamp are defined as "the number of seconds since January 1, 1904" private static DateTime timestampBase = new DateTime(1904, 1, 1); public class CommentData { public uint Timestamp; public short MarkerId; } private struct ChunkHeader { public string ID; public int Size; } // Private declarations private uint bits; private uint sampleSize; private uint numSampleFrames; private string format; private string compression; private byte versionID; private int sampleRate; private double bitrate; private double duration; private ChannelsArrangement channelsArrangement; private bool isValid; private SizeInfo sizeInfo; private readonly string filePath; private long id3v2Offset; private FileStructureHelper id3v2StructureHelper = new FileStructureHelper(false); private static IDictionary<string, byte> frameMapping; // Mapping between AIFx frame codes and ATL frame codes public byte VersionID // Version code { get { return this.versionID; } } public uint Bits { get { return bits; } } public double CompressionRatio { get { return getCompressionRatio(); } } // ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES // IAudioDataIO public bool IsVBR { get { return false; } } public int CodecFamily { get { return (compression.Equals(COMPRESSION_NONE) || compression.Equals(COMPRESSION_NONE_LE)) ? AudioDataIOFactory.CF_LOSSLESS : AudioDataIOFactory.CF_LOSSY; } } public string FileName { get { return filePath; } } public int SampleRate { get { return sampleRate; } } public double BitRate { get { return bitrate; } } public double Duration { get { return duration; } } public ChannelsArrangement ChannelsArrangement { get { return channelsArrangement; } } public bool IsMetaSupported(int metaDataType) { return (metaDataType == MetaDataIOFactory.TAG_NATIVE) || (metaDataType == MetaDataIOFactory.TAG_ID3V2); } // IMetaDataIO protected override int getDefaultTagOffset() { return TO_BUILTIN; } protected override int getImplementedTagType() { return MetaDataIOFactory.TAG_NATIVE; } public override byte FieldCodeFixedLength { get { return 4; } } protected override bool isLittleEndian { get { return false; } } protected override byte getFrameMapping(string zone, string ID, byte tagVersion) { byte supportedMetaId = 255; // Finds the ATL field identifier according to the ID3v2 version if (frameMapping.ContainsKey(ID)) supportedMetaId = frameMapping[ID]; return supportedMetaId; } // IMetaDataEmbedder public long HasEmbeddedID3v2 { get { return id3v2Offset; } } public uint ID3v2EmbeddingHeaderSize { get { return 8; } } public FileStructureHelper.Zone Id3v2Zone { get { return id3v2StructureHelper.GetZone(CHUNKTYPE_ID3TAG); } } // ---------- CONSTRUCTORS & INITIALIZERS static AIFF() { frameMapping = new Dictionary<string, byte> { { CHUNKTYPE_NAME, TagData.TAG_FIELD_TITLE }, { CHUNKTYPE_AUTHOR, TagData.TAG_FIELD_ARTIST }, { CHUNKTYPE_COPYRIGHT, TagData.TAG_FIELD_COPYRIGHT } }; } private void resetData() { duration = 0; bitrate = 0; isValid = false; id3v2StructureHelper.Clear(); bits = 0; sampleRate = 0; versionID = 0; id3v2Offset = -1; ResetData(); } public AIFF(string filePath) { this.filePath = filePath; resetData(); } // ---------- SUPPORT METHODS private double getCompressionRatio() { // Get compression ratio if (isValid) return (double)sizeInfo.FileSize / ((duration / 1000.0 * sampleRate) * (channelsArrangement.NbChannels * bits / 8.0) + 44) * 100; else return 0; } /// <summary> /// Reads ID and size of a local chunk and returns them in a dedicated structure _without_ reading nor skipping the data /// </summary> /// <param name="source">Source where to read header information</param> /// <returns>Local chunk header information</returns> private ChunkHeader seekNextChunkHeader(BinaryReader source, long limit) { ChunkHeader header = new ChunkHeader(); byte[] aByte = new byte[1]; source.BaseStream.Read(aByte, 0, 1); // In case previous field size is not correctly documented, tries to advance to find a suitable first character for an ID while (!((aByte[0] == 40) || ((64 < aByte[0]) && (aByte[0] < 91))) && source.BaseStream.Position < limit) { source.BaseStream.Read(aByte, 0, 1); } if (source.BaseStream.Position < limit) { source.BaseStream.Seek(-1, SeekOrigin.Current); // Chunk ID header.ID = Utils.Latin1Encoding.GetString(source.ReadBytes(4)); // Chunk size header.Size = StreamUtils.DecodeBEInt32(source.ReadBytes(4)); } else { header.ID = ""; } return header; } public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams) { this.sizeInfo = sizeInfo; return read(source, readTagParams); } protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams) { bool result = false; long position; resetData(); source.BaseStream.Seek(0, SeekOrigin.Begin); if (AIFF_CONTAINER_ID.Equals(Utils.Latin1Encoding.GetString(source.ReadBytes(4)))) { // Container chunk size long containerChunkPos = source.BaseStream.Position; int containerChunkSize = StreamUtils.DecodeBEInt32(source.ReadBytes(4)); if (containerChunkPos + containerChunkSize + 4 != source.BaseStream.Length) { LogDelegator.GetLogDelegate()(Log.LV_WARNING, "Header size is incoherent with file size"); } // Form type format = Utils.Latin1Encoding.GetString(source.ReadBytes(4)); if (format.Equals(FORMTYPE_AIFF) || format.Equals(FORMTYPE_AIFC)) { isValid = true; StringBuilder commentStr = new StringBuilder(""); long soundChunkPosition = 0; long soundChunkSize = 0; // Header size included bool nameFound = false; bool authorFound = false; bool copyrightFound = false; bool commentsFound = false; long limit = Math.Min(containerChunkPos + containerChunkSize + 4, source.BaseStream.Length); int annotationIndex = 0; int commentIndex = 0; while (source.BaseStream.Position < limit) { ChunkHeader header = seekNextChunkHeader(source, limit); position = source.BaseStream.Position; if (header.ID.Equals(CHUNKTYPE_COMMON)) { short channels = StreamUtils.DecodeBEInt16(source.ReadBytes(2)); switch (channels) { case 1: channelsArrangement = MONO; break; case 2: channelsArrangement = STEREO; break; case 3: channelsArrangement = ISO_3_0_0; break; case 4: channelsArrangement = ISO_2_2_0; break; // Specs actually allow both 2/2.0 and LRCS case 6: channelsArrangement = LRLcRcCS; break; default: channelsArrangement = UNKNOWN; break; } numSampleFrames = StreamUtils.DecodeBEUInt32(source.ReadBytes(4)); sampleSize = (uint)StreamUtils.DecodeBEInt16(source.ReadBytes(2)); // This sample size is for uncompressed data only byte[] byteArray = source.ReadBytes(10); Array.Reverse(byteArray); double aSampleRate = StreamUtils.ExtendedToDouble(byteArray); if (format.Equals(FORMTYPE_AIFC)) { compression = Utils.Latin1Encoding.GetString(source.ReadBytes(4)); } else // AIFF <=> no compression { compression = COMPRESSION_NONE; } if (aSampleRate > 0) { sampleRate = (int)Math.Round(aSampleRate); duration = (double)numSampleFrames * 1000.0 / sampleRate; if (!compression.Equals(COMPRESSION_NONE)) // Sample size is specific to selected compression method { if (compression.ToLower().Equals("fl32")) sampleSize = 32; else if (compression.ToLower().Equals("fl64")) sampleSize = 64; else if (compression.ToLower().Equals("alaw")) sampleSize = 8; else if (compression.ToLower().Equals("ulaw")) sampleSize = 8; } if (duration > 0) bitrate = sampleSize * numSampleFrames * channelsArrangement.NbChannels / duration; } } else if (header.ID.Equals(CHUNKTYPE_SOUND)) { soundChunkPosition = source.BaseStream.Position - 8; soundChunkSize = header.Size + 8; } else if (header.ID.Equals(CHUNKTYPE_NAME) || header.ID.Equals(CHUNKTYPE_AUTHOR) || header.ID.Equals(CHUNKTYPE_COPYRIGHT)) { structureHelper.AddZone(source.BaseStream.Position - 8, header.Size + 8, header.ID); structureHelper.AddSize(containerChunkPos, containerChunkSize, header.ID); tagExists = true; if (header.ID.Equals(CHUNKTYPE_NAME)) nameFound = true; if (header.ID.Equals(CHUNKTYPE_AUTHOR)) authorFound = true; if (header.ID.Equals(CHUNKTYPE_COPYRIGHT)) copyrightFound = true; SetMetaField(header.ID, Utils.Latin1Encoding.GetString(source.ReadBytes(header.Size)), readTagParams.ReadAllMetaFrames); } else if (header.ID.Equals(CHUNKTYPE_ANNOTATION)) { annotationIndex++; structureHelper.AddZone(source.BaseStream.Position - 8, header.Size + 8, header.ID + annotationIndex); structureHelper.AddSize(containerChunkPos, containerChunkSize, header.ID + annotationIndex); if (commentStr.Length > 0) commentStr.Append(Settings.InternalValueSeparator); commentStr.Append(Utils.Latin1Encoding.GetString(source.ReadBytes(header.Size))); tagExists = true; } else if (header.ID.Equals(CHUNKTYPE_COMMENTS)) { commentIndex++; structureHelper.AddZone(source.BaseStream.Position - 8, header.Size + 8, header.ID + commentIndex); structureHelper.AddSize(containerChunkPos, containerChunkSize, header.ID + commentIndex); tagExists = true; commentsFound = true; ushort numComs = StreamUtils.DecodeBEUInt16(source.ReadBytes(2)); for (int i = 0; i < numComs; i++) { CommentData cmtData = new CommentData(); cmtData.Timestamp = StreamUtils.DecodeBEUInt32(source.ReadBytes(4)); cmtData.MarkerId = StreamUtils.DecodeBEInt16(source.ReadBytes(2)); // Comments length ushort comLength = StreamUtils.DecodeBEUInt16(source.ReadBytes(2)); MetaFieldInfo comment = new MetaFieldInfo(getImplementedTagType(), header.ID + commentIndex); comment.Value = Utils.Latin1Encoding.GetString(source.ReadBytes(comLength)); comment.SpecificData = cmtData; tagData.AdditionalFields.Add(comment); // Only read general purpose comments, not those linked to a marker if (0 == cmtData.MarkerId) { if (commentStr.Length > 0) commentStr.Append(Settings.InternalValueSeparator); commentStr.Append(comment.Value); } } } else if (header.ID.Equals(CHUNKTYPE_ID3TAG)) { id3v2Offset = source.BaseStream.Position; // Zone is already added by Id3v2.Read id3v2StructureHelper.AddZone(id3v2Offset - 8, header.Size + 8, CHUNKTYPE_ID3TAG); id3v2StructureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_ID3TAG); } source.BaseStream.Position = position + header.Size; if (header.ID.Equals(CHUNKTYPE_SOUND) && header.Size % 2 > 0) source.BaseStream.Position += 1; // Sound chunk size must be even } tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, commentStr.ToString().Replace("\0", " ").Trim()); if (-1 == id3v2Offset) { id3v2Offset = 0; // Switch status to "tried to read, but nothing found" if (readTagParams.PrepareForWriting) { id3v2StructureHelper.AddZone(soundChunkPosition + soundChunkSize, 0, CHUNKTYPE_ID3TAG); id3v2StructureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_ID3TAG); } } // Add zone placeholders for future tag writing if (readTagParams.PrepareForWriting) { if (!nameFound) { structureHelper.AddZone(soundChunkPosition, 0, CHUNKTYPE_NAME); structureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_NAME); } if (!authorFound) { structureHelper.AddZone(soundChunkPosition, 0, CHUNKTYPE_AUTHOR); structureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_AUTHOR); } if (!copyrightFound) { structureHelper.AddZone(soundChunkPosition, 0, CHUNKTYPE_COPYRIGHT); structureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_COPYRIGHT); } if (!commentsFound) { structureHelper.AddZone(soundChunkPosition, 0, CHUNKTYPE_COMMENTS); structureHelper.AddSize(containerChunkPos, containerChunkSize, CHUNKTYPE_COMMENTS); } } result = true; } } return result; } protected override int write(TagData tag, BinaryWriter w, string zone) { int result = 0; if (zone.Equals(CHUNKTYPE_NAME)) { if (tag.Title.Length > 0) { w.Write(Utils.Latin1Encoding.GetBytes(zone)); long sizePos = w.BaseStream.Position; w.Write((int)0); // Placeholder for field size that will be rewritten at the end of the method byte[] strBytes = Utils.Latin1Encoding.GetBytes(tag.Title); w.Write(strBytes); w.BaseStream.Seek(sizePos, SeekOrigin.Begin); w.Write(StreamUtils.EncodeBEInt32(strBytes.Length)); result++; } } else if (zone.Equals(CHUNKTYPE_AUTHOR)) { if (tag.Artist.Length > 0) { w.Write(Utils.Latin1Encoding.GetBytes(zone)); long sizePos = w.BaseStream.Position; w.Write((int)0); // Placeholder for field size that will be rewritten at the end of the method byte[] strBytes = Utils.Latin1Encoding.GetBytes(tag.Artist); w.Write(strBytes); w.BaseStream.Seek(sizePos, SeekOrigin.Begin); w.Write(StreamUtils.EncodeBEInt32(strBytes.Length)); result++; } } else if (zone.Equals(CHUNKTYPE_COPYRIGHT)) { if (tag.Copyright.Length > 0) { w.Write(Utils.Latin1Encoding.GetBytes(zone)); long sizePos = w.BaseStream.Position; w.Write((int)0); // Placeholder for field size that will be rewritten at the end of the method byte[] strBytes = Utils.Latin1Encoding.GetBytes(tag.Copyright); w.Write(strBytes); w.BaseStream.Seek(sizePos, SeekOrigin.Begin); w.Write(StreamUtils.EncodeBEInt32(strBytes.Length)); result++; } } else if (zone.StartsWith(CHUNKTYPE_ANNOTATION)) { // Do not write anything, this field is deprecated (Cf. specs "Use of this chunk is discouraged within FORM AIFC. The more refined Comments Chunk should be used instead") } else if (zone.StartsWith(CHUNKTYPE_COMMENTS)) { bool applicable = tag.Comment.Length > 0; if (!applicable && tag.AdditionalFields.Count > 0) { foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields) { applicable = (fieldInfo.NativeFieldCode.StartsWith(CHUNKTYPE_COMMENTS)); if (applicable) break; } } if (applicable) { ushort numComments = 0; w.Write(Utils.Latin1Encoding.GetBytes(CHUNKTYPE_COMMENTS)); long sizePos = w.BaseStream.Position; w.Write((int)0); // Placeholder for 'chunk size' field that will be rewritten at the end of the method w.Write((ushort)0); // Placeholder for 'number of comments' field that will be rewritten at the end of the method // First write generic comments (those linked to the Comment field) string[] comments = tag.Comment.Split(Settings.InternalValueSeparator); foreach (string s in comments) { writeCommentChunk(w, null, s); numComments++; } // Then write comments linked to a Marker ID if (tag.AdditionalFields != null && tag.AdditionalFields.Count > 0) { foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields) { if (fieldInfo.NativeFieldCode.StartsWith(CHUNKTYPE_COMMENTS)) { if (((CommentData)fieldInfo.SpecificData).MarkerId != 0) { writeCommentChunk(w, fieldInfo); numComments++; } } } } long dataEndPos = w.BaseStream.Position; w.BaseStream.Seek(sizePos, SeekOrigin.Begin); w.Write(StreamUtils.EncodeBEInt32((int)(dataEndPos - sizePos - 4))); w.Write(StreamUtils.EncodeBEUInt16(numComments)); result++; } } return result; } private void writeCommentChunk(BinaryWriter w, MetaFieldInfo info, string comment = "") { byte[] commentData = null; if (null == info) // Plain string { w.Write(StreamUtils.EncodeBEUInt32(encodeTimestamp(DateTime.Now))); w.Write((short)0); commentData = Utils.Latin1Encoding.GetBytes(comment); } else { w.Write(StreamUtils.EncodeBEUInt32(((CommentData)info.SpecificData).Timestamp)); w.Write(StreamUtils.EncodeBEInt16(((CommentData)info.SpecificData).MarkerId)); commentData = Utils.Latin1Encoding.GetBytes(info.Value); } w.Write(StreamUtils.EncodeBEUInt16((ushort)commentData.Length)); w.Write(commentData); } public void WriteID3v2EmbeddingHeader(BinaryWriter w, long tagSize) { w.Write(Utils.Latin1Encoding.GetBytes(CHUNKTYPE_ID3TAG)); w.Write(StreamUtils.EncodeBEInt32((int)tagSize)); } // AIFx timestamps are "the number of seconds since January 1, 1904" private static uint encodeTimestamp(DateTime when) { return (uint)Math.Round((when.Ticks - timestampBase.Ticks) * 1.0 / TimeSpan.TicksPerSecond); } } }
using System; using StructureMap.Configuration; using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap { /// <summary> /// GoF Memento representing an Object Instance /// </summary> public abstract class InstanceMemento { public const string EMPTY_STRING = "STRING.EMPTY"; public const string SUBSTITUTIONS_ATTRIBUTE = "Substitutions"; public const string TEMPLATE_ATTRIBUTE = "Template"; private string _instanceKey; private string _lastKey = string.Empty; /// <summary> /// The named type of the object instance represented by the InstanceMemento. Translates to a concrete /// type /// </summary> public string ConcreteKey { get { return innerConcreteKey; } } protected abstract string innerConcreteKey { get; } /// <summary> /// The named key of the object instance represented by the InstanceMemento /// </summary> public string InstanceKey { get { if (string.IsNullOrEmpty(_instanceKey)) { return innerInstanceKey; } else { return _instanceKey; } } set { _instanceKey = value; } } protected abstract string innerInstanceKey { get; } /// <summary> /// Gets the referred template name /// </summary> /// <returns></returns> public string TemplateName { get { string rawValue = getPropertyValue(TEMPLATE_ATTRIBUTE); return rawValue == null ? string.Empty : rawValue.Trim(); } } /// <summary> /// Template pattern property specifying whether the InstanceMemento is simply a reference /// to another named instance. Useful for child objects. /// </summary> public abstract bool IsReference { get; } /// <summary> /// Template pattern property specifying the instance key that the InstanceMemento refers to /// </summary> public abstract string ReferenceKey { get; } /// <summary> /// Is the InstanceMemento a reference to the default instance of the plugin type? /// </summary> public bool IsDefault { get { return (IsReference && ReferenceKey == string.Empty); } } public virtual Plugin FindPlugin(PluginFamily family) { Plugin plugin = getPluginByType(family) ?? family.FindPlugin(innerConcreteKey ?? string.Empty) ?? family.FindPlugin(Plugin.DEFAULT); if (plugin == null) { throw new StructureMapException(201, innerConcreteKey, InstanceKey, family.PluginType.AssemblyQualifiedName); } return plugin; } private Plugin getPluginByType(PluginFamily family) { string pluggedTypeName = getPluggedType(); if (string.IsNullOrEmpty(pluggedTypeName)) { return null; } Type pluggedType = new TypePath(pluggedTypeName).FindType(); return PluginCache.GetPlugin(pluggedType); } /// <summary> /// Retrieves the named property value as a string /// </summary> /// <param name="Key"></param> /// <returns></returns> public string GetProperty(string Key) { string returnValue = ""; try { returnValue = getPropertyValue(Key); } catch (Exception ex) { throw new StructureMapException(205, ex, Key, InstanceKey); } if (string.IsNullOrEmpty(returnValue)) return null; if (returnValue.ToUpper() == EMPTY_STRING) { returnValue = string.Empty; } return returnValue; } /// <summary> /// Template method for implementation specific retrieval of the named property /// </summary> /// <param name="Key"></param> /// <returns></returns> protected abstract string getPropertyValue(string Key); /// <summary> /// Returns the named child InstanceMemento /// </summary> /// <param name="Key"></param> /// <returns></returns> public InstanceMemento GetChildMemento(string Key) { _lastKey = Key; InstanceMemento returnValue = getChild(Key); return returnValue; } public virtual Instance ReadChildInstance(string name, PluginGraph graph, Type childType) { InstanceMemento child = GetChildMemento(name); return child == null ? null : child.ReadInstance(graph, childType); } /// <summary> /// Template method for implementation specific retrieval of the named property /// </summary> /// <param name="Key"></param> /// <returns></returns> protected abstract InstanceMemento getChild(string Key); /// <summary> /// This method is made public for testing. It is not necessary for normal usage. /// </summary> /// <returns></returns> public abstract InstanceMemento[] GetChildrenArray(string Key); /// <summary> /// Used to create a templated InstanceMemento /// </summary> /// <param name="memento"></param> /// <returns></returns> public virtual InstanceMemento Substitute(InstanceMemento memento) { throw new NotSupportedException("This type of InstanceMemento does not support the Substitute() Method"); } protected virtual string getPluggedType() { return getPropertyValue(XmlConstants.PLUGGED_TYPE); } public Instance ReadInstance(PluginGraph pluginGraph, Type pluginType) { try { Instance instance = readInstance(pluginGraph, pluginType); instance.Name = InstanceKey; return instance; } catch (StructureMapException) { throw; } catch (Exception e) { throw new StructureMapException(260, e, InstanceKey, pluginType.FullName); } } protected virtual Instance readInstance(PluginGraph pluginGraph, Type pluginType) { if (IsDefault) { return new DefaultInstance(); } if (IsReference) { return new ReferencedInstance(ReferenceKey); } return new ConfiguredInstance(this, pluginGraph, pluginType); } } }
using System; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.WebPages; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Web.Models; using Umbraco.Web.Routing; using Umbraco.Web.Security; namespace Umbraco.Web.Mvc { /// <summary> /// The View that umbraco front-end views inherit from /// </summary> public abstract class UmbracoViewPage<TModel> : WebViewPage<TModel> { /// <summary> /// Returns the current UmbracoContext /// </summary> public UmbracoContext UmbracoContext { get { //we should always try to return the context from the data tokens just in case its a custom context and not //using the UmbracoContext.Current. //we will fallback to the singleton if necessary. if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-context")) { return (UmbracoContext)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context"); } //next check if it is a child action and see if the parent has it set in data tokens if (ViewContext.IsChildAction) { if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-context")) { return (UmbracoContext)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context"); } } //lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this //class and are rendering it outside of the normal Umbraco routing process. Very unlikely. return UmbracoContext.Current; } } /// <summary> /// Returns the current ApplicationContext /// </summary> public ApplicationContext ApplicationContext { get { return UmbracoContext.Application; } } /// <summary> /// Returns the current PublishedContentRequest /// </summary> internal PublishedContentRequest PublishedContentRequest { get { //we should always try to return the object from the data tokens just in case its a custom object and not //using the UmbracoContext.Current. //we will fallback to the singleton if necessary. if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request")) { return (PublishedContentRequest)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request"); } //next check if it is a child action and see if the parent has it set in data tokens if (ViewContext.IsChildAction) { if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request")) { return (PublishedContentRequest)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request"); } } //lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this //class and are rendering it outside of the normal Umbraco routing process. Very unlikely. return UmbracoContext.Current.PublishedContentRequest; } } private UmbracoHelper _helper; private MembershipHelper _membershipHelper; /// <summary> /// Gets an UmbracoHelper /// </summary> /// <remarks> /// This constructs the UmbracoHelper with the content model of the page routed to /// </remarks> public virtual UmbracoHelper Umbraco { get { if (_helper == null) { var model = ViewData.Model; var content = model as IPublishedContent; if (content == null && model is IRenderModel) content = ((IRenderModel) model).Content; _helper = content == null ? new UmbracoHelper(UmbracoContext) : new UmbracoHelper(UmbracoContext, content); } return _helper; } } /// <summary> /// Returns the MemberHelper instance /// </summary> public MembershipHelper Members { get { return _membershipHelper ?? (_membershipHelper = new MembershipHelper(UmbracoContext)); } } /// <summary> /// Ensure that the current view context is added to the route data tokens so we can extract it if we like /// </summary> /// <remarks> /// Currently this is required by mvc macro engines /// </remarks> protected override void InitializePage() { base.InitializePage(); if (ViewContext.IsChildAction == false) { if (ViewContext.RouteData.DataTokens.ContainsKey(Constants.DataTokenCurrentViewContext) == false) { ViewContext.RouteData.DataTokens.Add(Constants.DataTokenCurrentViewContext, ViewContext); } } } // maps model protected override void SetViewData(ViewDataDictionary viewData) { // if view data contains no model, nothing to do var source = viewData.Model; if (source == null) { base.SetViewData(viewData); return; } // get the type of the view data model (what we have) // get the type of this view model (what we want) var sourceType = source.GetType(); var targetType = typeof (TModel); // it types already match, nothing to do if (sourceType.Inherits<TModel>()) // includes == { base.SetViewData(viewData); return; } // try to grab the content // if no content is found, return, nothing we can do var sourceContent = source as IPublishedContent; // check if what we have is an IPublishedContent if (sourceContent == null && sourceType.Implements<IRenderModel>()) { // else check if it's an IRenderModel => get the content sourceContent = ((IRenderModel)source).Content; } if (sourceContent == null) { // else check if we can convert it to a content var attempt = source.TryConvertTo<IPublishedContent>(); if (attempt.Success) sourceContent = attempt.Result; } var ok = sourceContent != null; if (sourceContent != null) { // try to grab the culture // using context's culture by default var culture = UmbracoContext.PublishedContentRequest.Culture; var sourceRenderModel = source as RenderModel; if (sourceRenderModel != null) culture = sourceRenderModel.CurrentCulture; // reassign the model depending on its type if (targetType.Implements<IPublishedContent>()) { // it TModel implements IPublishedContent then use the content // provided that the content is of the proper type if ((sourceContent is TModel) == false) throw new InvalidCastException(string.Format("Cannot cast source content type {0} to view model type {1}.", sourceContent.GetType(), targetType)); viewData.Model = sourceContent; } else if (targetType == typeof(RenderModel)) { // if TModel is a basic RenderModel just create it viewData.Model = new RenderModel(sourceContent, culture); } else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(RenderModel<>)) { // if TModel is a strongly-typed RenderModel<> then create it // provided that the content is of the proper type var targetContentType = targetType.GetGenericArguments()[0]; if ((sourceContent.GetType().Inherits(targetContentType)) == false) throw new InvalidCastException(string.Format("Cannot cast source content type {0} to view model content type {1}.", sourceContent.GetType(), targetContentType)); viewData.Model = Activator.CreateInstance(targetType, sourceContent, culture); } else { ok = false; } } if (ok == false) { // last chance : try to convert var attempt = source.TryConvertTo<TModel>(); if (attempt.Success) viewData.Model = attempt.Result; } base.SetViewData(viewData); } /// <summary> /// This will detect the end /body tag and insert the preview badge if in preview mode /// </summary> /// <param name="value"></param> public override void WriteLiteral(object value) { // filter / add preview banner if (Response.ContentType.InvariantEquals("text/html")) // ASP.NET default value { if (UmbracoContext.Current.IsDebug || UmbracoContext.Current.InPreviewMode) { var text = value.ToString().ToLowerInvariant(); var pos = text.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase); if (pos > -1) { string markupToInject; if (UmbracoContext.Current.InPreviewMode) { // creating previewBadge markup markupToInject = String.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.UmbracoClient), Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); } else { // creating mini-profiler markup markupToInject = Html.RenderProfiler().ToHtmlString(); } var sb = new StringBuilder(text); sb.Insert(pos, markupToInject); base.WriteLiteral(sb.ToString()); return; } } } base.WriteLiteral(value); } public HelperResult RenderSection(string name, Func<dynamic, HelperResult> defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, HelperResult defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, string defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, IHtmlString defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } } }
namespace Modbus.Device { using System; using System.Diagnostics.CodeAnalysis; using System.IO.Ports; using System.Net.Sockets; using System.Threading.Tasks; using IO; /// <summary> /// Modbus IP master device. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] public class ModbusIpMaster : ModbusMaster { private ModbusIpMaster(ModbusTransport transport) : base(transport) { } /// <summary> /// Modbus IP master factory method. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] public static ModbusIpMaster CreateIp(TcpClient tcpClient) { if (tcpClient == null) throw new ArgumentNullException("tcpClient"); return CreateIp(new TcpClientAdapter(tcpClient)); } /// <summary> /// Modbus IP master factory method. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] public static ModbusIpMaster CreateIp(UdpClient udpClient) { if (udpClient == null) throw new ArgumentNullException("udpClient"); if (!udpClient.Client.Connected) throw new InvalidOperationException(Resources.UdpClientNotConnected); return CreateIp(new UdpClientAdapter(udpClient)); } /// <summary> /// Modbus IP master factory method. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] public static ModbusIpMaster CreateIp(SerialPort serialPort) { if (serialPort == null) throw new ArgumentNullException("serialPort"); return CreateIp(new SerialPortAdapter(serialPort)); } /// <summary> /// Modbus IP master factory method. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] public static ModbusIpMaster CreateIp(IStreamResource streamResource) { if (streamResource == null) throw new ArgumentNullException("streamResource"); return new ModbusIpMaster(new ModbusIpTransport(streamResource)); } /// <summary> /// Reads from 1 to 2000 contiguous coils status. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of coils to read.</param> /// <returns>Coils status</returns> public bool[] ReadCoils(ushort startAddress, ushort numberOfPoints) { return base.ReadCoils(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Asynchronously reads from 1 to 2000 contiguous coils status. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of coils to read.</param> /// <returns>A task that represents the asynchronous read operation</returns> public Task<bool[]> ReadCoilsAsync(ushort startAddress, ushort numberOfPoints) { return base.ReadCoilsAsync(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Reads from 1 to 2000 contiguous discrete input status. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of discrete inputs to read.</param> /// <returns>Discrete inputs status</returns> public bool[] ReadInputs(ushort startAddress, ushort numberOfPoints) { return base.ReadInputs(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Asynchronously reads from 1 to 2000 contiguous discrete input status. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of discrete inputs to read.</param> /// <returns>A task that represents the asynchronous read operation</returns> public Task<bool[]> ReadInputsAsync(ushort startAddress, ushort numberOfPoints) { return base.ReadInputsAsync(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Reads contiguous block of holding registers. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>Holding registers status</returns> public ushort[] ReadHoldingRegisters(ushort startAddress, ushort numberOfPoints) { return base.ReadHoldingRegisters(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Asynchronously reads contiguous block of holding registers. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>A task that represents the asynchronous read operation</returns> public Task<ushort[]> ReadHoldingRegistersAsync(ushort startAddress, ushort numberOfPoints) { return base.ReadHoldingRegistersAsync(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Reads contiguous block of input registers. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>Input registers status</returns> public ushort[] ReadInputRegisters(ushort startAddress, ushort numberOfPoints) { return base.ReadInputRegisters(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Asynchronously reads contiguous block of input registers. /// </summary> /// <param name="startAddress">Address to begin reading.</param> /// <param name="numberOfPoints">Number of holding registers to read.</param> /// <returns>A task that represents the asynchronous read operation</returns> public Task<ushort[]> ReadInputRegistersAsync(ushort startAddress, ushort numberOfPoints) { return base.ReadInputRegistersAsync(Modbus.DefaultIpSlaveUnitId, startAddress, numberOfPoints); } /// <summary> /// Writes a single coil value. /// </summary> /// <param name="coilAddress">Address to write value to.</param> /// <param name="value">Value to write.</param> public void WriteSingleCoil(ushort coilAddress, bool value) { base.WriteSingleCoil(Modbus.DefaultIpSlaveUnitId, coilAddress, value); } /// <summary> /// Asynchronously writes a single coil value. /// </summary> /// <param name="coilAddress">Address to write value to.</param> /// <param name="value">Value to write.</param> /// <returns>A task that represents the asynchronous write operation</returns> public Task WriteSingleCoilAsync(ushort coilAddress, bool value) { return base.WriteSingleCoilAsync(Modbus.DefaultIpSlaveUnitId, coilAddress, value); } /// <summary> /// Write a single holding register. /// </summary> /// <param name="registerAddress">Address to write.</param> /// <param name="value">Value to write.</param> public void WriteSingleRegister(ushort registerAddress, ushort value) { base.WriteSingleRegister(Modbus.DefaultIpSlaveUnitId, registerAddress, value); } /// <summary> /// Asynchronously writes a single holding register. /// </summary> /// <param name="registerAddress">Address to write.</param> /// <param name="value">Value to write.</param> /// <returns>A task that represents the asynchronous write operation</returns> public Task WriteSingleRegisterAsync(ushort registerAddress, ushort value) { return base.WriteSingleRegisterAsync(Modbus.DefaultIpSlaveUnitId, registerAddress, value); } /// <summary> /// Write a block of 1 to 123 contiguous registers. /// </summary> /// <param name="startAddress">Address to begin writing values.</param> /// <param name="data">Values to write.</param> public void WriteMultipleRegisters(ushort startAddress, ushort[] data) { base.WriteMultipleRegisters(Modbus.DefaultIpSlaveUnitId, startAddress, data); } /// <summary> /// Asynchronously writes a block of 1 to 123 contiguous registers. /// </summary> /// <param name="startAddress">Address to begin writing values.</param> /// <param name="data">Values to write.</param> /// <returns>A task that represents the asynchronous write operation</returns> public Task WriteMultipleRegistersAsync(ushort startAddress, ushort[] data) { return base.WriteMultipleRegistersAsync(Modbus.DefaultIpSlaveUnitId, startAddress, data); } /// <summary> /// Force each coil in a sequence of coils to a provided value. /// </summary> /// <param name="startAddress">Address to begin writing values.</param> /// <param name="data">Values to write.</param> public void WriteMultipleCoils(ushort startAddress, bool[] data) { base.WriteMultipleCoils(Modbus.DefaultIpSlaveUnitId, startAddress, data); } /// <summary> /// Asynchronously writes a sequence of coils. /// </summary> /// <param name="startAddress">Address to begin writing values.</param> /// <param name="data">Values to write.</param> /// <returns>A task that represents the asynchronous write operation</returns> public Task WriteMultipleCoilsAsync(ushort startAddress, bool[] data) { return base.WriteMultipleCoilsAsync(Modbus.DefaultIpSlaveUnitId, startAddress, data); } /// <summary> /// Performs a combination of one read operation and one write operation in a single MODBUS transaction. /// The write operation is performed before the read. /// Message uses default TCP slave id of 0. /// </summary> /// <param name="startReadAddress">Address to begin reading (Holding registers are addressed starting at 0).</param> /// <param name="numberOfPointsToRead">Number of registers to read.</param> /// <param name="startWriteAddress">Address to begin writing (Holding registers are addressed starting at 0).</param> /// <param name="writeData">Register values to write.</param> public ushort[] ReadWriteMultipleRegisters(ushort startReadAddress, ushort numberOfPointsToRead, ushort startWriteAddress, ushort[] writeData) { return base.ReadWriteMultipleRegisters(Modbus.DefaultIpSlaveUnitId, startReadAddress, numberOfPointsToRead, startWriteAddress, writeData); } /// <summary> /// Asynchronously performs a combination of one read operation and one write operation in a single Modbus transaction. /// The write operation is performed before the read. /// </summary> /// <param name="startReadAddress">Address to begin reading (Holding registers are addressed starting at 0).</param> /// <param name="numberOfPointsToRead">Number of registers to read.</param> /// <param name="startWriteAddress">Address to begin writing (Holding registers are addressed starting at 0).</param> /// <param name="writeData">Register values to write.</param> /// <returns>A task that represents the asynchronous operation</returns> public Task<ushort[]> ReadWriteMultipleRegistersAsync(ushort startReadAddress, ushort numberOfPointsToRead, ushort startWriteAddress, ushort[] writeData) { return base.ReadWriteMultipleRegistersAsync(Modbus.DefaultIpSlaveUnitId, startReadAddress, numberOfPointsToRead, startWriteAddress, writeData); } } }
// 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.Linq; using Xunit; namespace System.IO.Tests { public class Directory_CreateDirectory : FileSystemTest { #region Utilities public virtual DirectoryInfo Create(string path) { return Directory.CreateDirectory(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Theory, MemberData(nameof(PathsWithInvalidCharacters))] public void PathWithInvalidCharactersAsPath_ThrowsArgumentException(string invalidPath) { if (invalidPath.Equals(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization()) AssertExtensions.ThrowsAny<IOException, UnauthorizedAccessException>(() => Create(invalidPath)); else if (invalidPath.Contains(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization()) Assert.Throws<DirectoryNotFoundException>(() => Create(invalidPath)); else Assert.Throws<ArgumentException>(() => Create(invalidPath)); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Throws<IOException>(() => Create(path)); Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { DirectoryInfo testDir = Create(GetTestFilePath()); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName); } finally { testDir.Attributes = original; } } [Fact] public void RootPath() { string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory()); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFilePath(); DirectoryInfo result = Create(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName); result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName); } [Fact] public void CreateCurrentDirectory() { DirectoryInfo result = Create(Directory.GetCurrentDirectory()); Assert.Equal(Directory.GetCurrentDirectory(), result.FullName); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); } [ConditionalFact(nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // trailing slash public void ValidExtendedPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); }); } [Fact] public void ValidPathWithoutTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = testDir.FullName + Path.DirectorySeparatorChar + component; DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void AllowedSymbols() { string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreated() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent); Assert.All(path.SubPaths, (subpath) => { DirectoryInfo result = Create(subpath); Assert.Equal(subpath, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException() { // While paths themselves can be up to 260 characters including trailing null, file systems // limit each components of the path to a total of 255 characters. var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent(); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } #endregion #region PlatformSpecific [Theory, MemberData(nameof(PathsWithInvalidColons))] [PlatformSpecific(TestPlatforms.Windows)] // invalid colons throws ArgumentException [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Versions of netfx older than 4.6.2 throw an ArgumentException instead of NotSupportedException. Until all of our machines run netfx against the actual latest version, these will fail.")] public void PathWithInvalidColons_ThrowsNotSupportedException(string invalidPath) { Assert.Throws<NotSupportedException>(() => Create(invalidPath)); } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds public void DirectoryLongerThanMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()); Assert.All(paths, (path) => { DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // long directory path throws PathTooLongException public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax throws PathTooLongException public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax succeeds public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.True(Create(path).Exists); }); } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath()); Assert.All(paths, (path) => { var result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // long directory path allowed public void UnixPathLongerThan256_Allowed() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // deeply nested directories allowed public void UnixPathWithDeeplyNestedDirectories() { DirectoryInfo parent = Create(GetTestFilePath()); for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories { parent = Create(Path.Combine(parent.FullName, "dir" + i)); Assert.True(Directory.Exists(parent.FullName)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // whitespace as path throws ArgumentException on Windows public void WindowsWhiteSpaceAsPath_ThrowsArgumentException() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Assert.Throws<ArgumentException>(() => Create(path)); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed public void UnixWhiteSpaceAsPath_Allowed() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Create(Path.Combine(TestDirectory, path)); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows public void WindowsTrailingWhiteSpace() { // Windows will remove all non-significant whitespace in a path DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [ConditionalFact(nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace public void WindowsExtendedSyntaxWhiteSpace() { var paths = IOInputs.GetSimpleWhiteSpace(); foreach (var path in paths) { string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath), extendedPath); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix public void UnixNonSignificantTrailingWhiteSpace() { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // alternate data streams public void PathWithAlternateDataStreams_ThrowsNotSupportedException() { var paths = IOInputs.GetPathsWithAlternativeDataStreams(); Assert.All(paths, (path) => { Assert.Throws<NotSupportedException>(() => Create(path)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException() { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path var paths = IOInputs.GetPathsWithReservedDeviceNames(); Assert.All(paths, (path) => { Assert.Throws<DirectoryNotFoundException>(() => Create(path)); }); } [ConditionalFact(nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsExtendedPath() { var paths = IOInputs.GetReservedDeviceNames(); Assert.All(paths, (path) => { Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UncPathWithoutShareNameAsPath_ThrowsArgumentException() { var paths = IOInputs.GetUncPathsWithoutShareName(); foreach (var path in paths) { Assert.Throws<ArgumentException>(() => Create(path)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { Assert.Throws<ArgumentException>(() => Create("//")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // drive labels [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] public void CDriveCase() { DirectoryInfo dir = Create("c:\\"); DirectoryInfo dir2 = Create("C:\\"); Assert.NotEqual(dir.FullName, dir2.FullName); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // drive letters public void DriveLetter_Windows() { // On Windows, DirectoryInfo will replace "<DriveLetter>:" with "." var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":"); var current = Create("."); Assert.Equal(current.Name, driveLetter.Name); Assert.Equal(current.FullName, driveLetter.FullName); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // drive letters casing public void DriveLetter_Unix() { // On Unix, there's no special casing for drive letters. These may or may not be valid names, depending // on the file system underlying the current directory. Unix file systems typically allow these, but, // for example, these names are not allowed if running on a file system mounted from a Windows machine. DirectoryInfo driveLetter; try { driveLetter = Create("C:"); } catch (IOException) { return; } var current = Create("."); Assert.Equal("C:", driveLetter.Name); Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName); try { // If this test is inherited then it's possible this call will fail due to the "C:" directory // being deleted in that other test before this call. What we care about testing (proper path // handling) is unaffected by this race condition. Directory.Delete("C:"); } catch (DirectoryNotFoundException) { } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(IOServices.GetNonExistentDrive()); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory")); }); } [Fact] [ActiveIssue(1221)] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException() { // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } Assert.Throws<DirectoryNotFoundException>(() => { Create(drive); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels [ActiveIssue(1221)] public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException() { var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } // 'Device is not ready' Assert.Throws<IOException>(() => { Create(Path.Combine(drive, "Subdirectory")); }); } #if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL /* [Fact] public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); using (CurrentDirectoryContext context = new CurrentDirectoryContext(root)) { DirectoryInfo result = Create(".."); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(root, result.FullName); } } */ #endif #endregion } }
// // UnixListener.cs // // Authors: // Joe Shaw (joeshaw@novell.com) // // Copyright (C) 2004-2005 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 System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; namespace Mono.Unix { public class UnixClient : IDisposable { NetworkStream stream; Socket client; bool disposed; public UnixClient () { if (client != null) { client.Close (); client = null; } client = new Socket (AddressFamily.Unix, SocketType.Stream, 0); } public UnixClient (string path) : this () { if (path == null) throw new ArgumentNullException ("ep"); Connect (path); } public UnixClient (UnixEndPoint ep) : this () { if (ep == null) throw new ArgumentNullException ("ep"); Connect (ep); } // UnixListener uses this when accepting a connection. internal UnixClient (Socket sock) { Client = sock; } protected Socket Client { get { return client; } set { client = value; stream = null; } } public PeerCred PeerCredential { get { CheckDisposed (); return new PeerCred (client); } } public LingerOption LingerState { get { CheckDisposed (); return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger); } set { CheckDisposed (); client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, value); } } public int ReceiveBufferSize { get { CheckDisposed (); return (int) client.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); } set { CheckDisposed (); client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } } public int ReceiveTimeout { get { CheckDisposed (); return (int) client.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { CheckDisposed (); client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } public int SendBufferSize { get { CheckDisposed (); return (int) client.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer); } set { CheckDisposed (); client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } } public int SendTimeout { get { CheckDisposed (); return (int) client.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout); } set { CheckDisposed (); client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } public void Close () { CheckDisposed (); Dispose (); } public void Connect (UnixEndPoint remoteEndPoint) { CheckDisposed (); client.Connect (remoteEndPoint); stream = new NetworkStream (client, true); } public void Connect (string path) { CheckDisposed (); Connect (new UnixEndPoint (path)); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (disposed) return; if (disposing) { // release managed resources NetworkStream s = stream; stream = null; if (s != null) { // This closes the socket as well, as the NetworkStream // owns the socket. s.Close(); s = null; } else if (client != null){ client.Close (); } client = null; } disposed = true; } public NetworkStream GetStream () { CheckDisposed (); if (stream == null) stream = new NetworkStream (client, true); return stream; } void CheckDisposed () { if (disposed) throw new ObjectDisposedException (GetType().FullName); } ~UnixClient () { Dispose (false); } } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Security.Cryptography; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { /// <summary> /// Asset bundle build report. /// </summary> public class AssetBundleBuildReport { private class AssetBundleBuildReportManager { private List<AssetBundleBuildReport> m_buildReports; private List<ExportReport> m_exportReports; public List<AssetBundleBuildReport> BuildReports { get { return m_buildReports; } } public List<ExportReport> ExportReports { get { return m_exportReports; } } public AssetBundleBuildReportManager() { m_buildReports = new List<AssetBundleBuildReport>(); m_exportReports = new List<ExportReport>(); } } private static AssetBundleBuildReportManager s_mgr; private static AssetBundleBuildReportManager Manager { get { if(s_mgr == null) { s_mgr = new AssetBundleBuildReportManager(); } return s_mgr; } } static public void ClearReports() { Manager.BuildReports.Clear(); Manager.ExportReports.Clear(); } static public void AddBuildReport(AssetBundleBuildReport r) { Manager.BuildReports.Add(r); } static public void AddExportReport(ExportReport r) { Manager.ExportReports.Add(r); } static public IEnumerable<AssetBundleBuildReport> BuildReports { get { return Manager.BuildReports; } } static public IEnumerable<ExportReport> ExportReports { get { return Manager.ExportReports; } } private Model.NodeData m_node; private AssetBundleManifest m_manifest; private string m_manifestFileName; private AssetBundleBuild[] m_bundleBuild; private List<AssetReference> m_builtBundles; private Dictionary<string, List<AssetReference>> m_assetGroups; private Dictionary<string, List<string>> m_bundleNamesAndVariants; /// <summary> /// Gets the node. /// </summary> /// <value>The node.</value> public Model.NodeData Node { get { return m_node; } } /// <summary> /// Gets the manifest. /// </summary> /// <value>The manifest.</value> public AssetBundleManifest Manifest { get { return m_manifest; } } /// <summary> /// Gets the name of the manifest file. /// </summary> /// <value>The name of the manifest file.</value> public string ManifestFileName { get { return m_manifestFileName; } } /// <summary> /// Gets the bundle build. /// </summary> /// <value>The bundle build.</value> public AssetBundleBuild[] BundleBuild { get { return m_bundleBuild; } } /// <summary> /// Gets the built bundle files. /// </summary> /// <value>The built bundle files.</value> public List<AssetReference> BuiltBundleFiles { get { return m_builtBundles; } } /// <summary> /// Gets the asset groups. /// </summary> /// <value>The asset groups.</value> public Dictionary<string, List<AssetReference>> AssetGroups { get { return m_assetGroups; } } /// <summary> /// Gets the bundle names. /// </summary> /// <value>The bundle names.</value> public IEnumerable<string> BundleNames { get { return m_bundleNamesAndVariants.Keys; } } /// <summary> /// Gets the variant names. /// </summary> /// <returns>The variant names.</returns> /// <param name="bundleName">Bundle name.</param> public List<string> GetVariantNames(string bundleName) { if(m_bundleNamesAndVariants.ContainsKey(bundleName)) { return m_bundleNamesAndVariants[bundleName]; } return null; } public AssetBundleBuildReport( Model.NodeData node, AssetBundleManifest m, string manifestFileName, AssetBundleBuild[] bb, List<AssetReference> builtBundles, Dictionary<string, List<AssetReference>> ag, Dictionary<string, List<string>> names) { m_node = node; m_manifest = m; m_manifestFileName = manifestFileName; m_bundleBuild = bb; m_builtBundles = builtBundles; m_assetGroups = ag; m_bundleNamesAndVariants = names; } } /// <summary> /// Export report. /// </summary> public class ExportReport { /// <summary> /// Entry. /// </summary> public class Entry { /// <summary> /// The source. /// </summary> public string source; /// <summary> /// The destination. /// </summary> public string destination; public Entry(string src, string dst) { source = src; destination = dst; } } /// <summary> /// Error entry. /// </summary> public class ErrorEntry { /// <summary> /// The source. /// </summary> public string source; /// <summary> /// The destination. /// </summary> public string destination; /// <summary> /// The reason. /// </summary> public string reason; public ErrorEntry(string src, string dst, string r) { source = src; destination = dst; reason = r; } } private Model.NodeData m_nodeData; private List<Entry> m_exportedItems; private List<ErrorEntry> m_failedItems; /// <summary> /// Gets the exported items. /// </summary> /// <value>The exported items.</value> public List<Entry> ExportedItems { get { return m_exportedItems; } } /// <summary> /// Gets the errors. /// </summary> /// <value>The errors.</value> public List<ErrorEntry> Errors { get { return m_failedItems; } } /// <summary> /// Gets the node. /// </summary> /// <value>The node.</value> public Model.NodeData Node { get { return m_nodeData; } } public ExportReport(Model.NodeData node) { m_nodeData = node; m_exportedItems = new List<Entry>(); m_failedItems = new List<ErrorEntry> (); } public void AddExportedEntry(string src, string dst) { m_exportedItems.Add(new Entry(src, dst)); } public void AddErrorEntry(string src, string dst, string reason) { m_failedItems.Add(new ErrorEntry(src, dst, reason)); } } }