context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ProductsListView.ascx.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // The shopping cart view. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.layouts.Ecommerce.CheckOutProcess { using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Analytics.Components; using DomainModel.Carts; using DomainModel.Configurations; using DomainModel.Orders; using DomainModel.Products; using Examples.CheckOutProcess; using Utils; using DomainModel.Currencies; /// <summary> /// The shopping cart view. /// </summary> public partial class ProductsListView : UserControl { /// <summary> /// Data source. /// </summary> private object productLines; #region Public properties /// <summary> /// Gets the general settings. /// </summary> /// <value>The general settings.</value> public static GeneralSettings GeneralSettings { get { return Sitecore.Ecommerce.Context.Entity.GetConfiguration<GeneralSettings>(); } } /// <summary> /// Gets the ShoppingCart settings. /// </summary> public static ShoppingCartSettings ShoppingCartSettings { get { return Sitecore.Ecommerce.Context.Entity.GetConfiguration<ShoppingCartSettings>(); } } /// <summary> /// Gets or sets the currency. /// </summary> /// <value>The currency.</value> public Currency Currency { get; set; } /// <summary> /// Gets or sets DisplayMode. /// </summary> public OrderDisplayMode DisplayMode { get; set; } /// <summary> /// Gets or sets the data source. /// </summary> /// <value>The data source.</value> public object ProductLines { get { if (this.productLines == null) { DomainModel.Carts.ShoppingCart shoppingCart = Sitecore.Ecommerce.Context.Entity.GetInstance<DomainModel.Carts.ShoppingCart>(); this.productLines = shoppingCart.ShoppingCartLines; } return this.productLines; } set { this.productLines = value; } } /// <summary> /// Gets the products. /// </summary> /// <returns>Returns collection pairs of product code and quantity</returns> public IEnumerable<KeyValuePair<string, uint>> GetProducts() { foreach (RepeaterItem item in this.repProductsList.Items) { TextBox txtQuantity = item.FindControl("txtQuantity") as TextBox; LinkButton btnDelete = item.FindControl("btnDelete") as LinkButton; if (btnDelete == null || txtQuantity == null) { continue; } string quantity = txtQuantity.Text; string productCode = btnDelete.CommandArgument; string[] productArgsArray = productCode.Split('|'); if (productArgsArray.Length > 1) { productCode = productArgsArray[0]; } uint quant; if (!uint.TryParse(quantity, out quant)) { continue; } yield return new KeyValuePair<string, uint>(productCode, quant); } } #endregion #region Protected methods /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="System.EventArgs"/> instance containing the event data. /// </param> protected void Page_Load(object sender, EventArgs e) { this.repProductsList.DataSource = this.ProductLines; if (!this.IsPostBack) { this.DataBind(); } } /// <summary> /// Handles the ItemDataBound event of the repProductsList control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs"/> instance containing the event data. /// </param> protected void repShoppingCartList_ItemDataBound(object sender, RepeaterItemEventArgs e) { // Initialize OrderDisplayMode - start Control liHeader = e.Item.FindControl("liHeader"); Control divImage = e.Item.FindControl("divImage"); Control divNumber = e.Item.FindControl("divNumber"); HtmlGenericControl divText = e.Item.FindControl("divText") as HtmlGenericControl; Control tdCommands = e.Item.FindControl("tdCommands"); Control divCountEdit = e.Item.FindControl("divCountEdit"); Control divCountDisplay = e.Item.FindControl("divCountDisplay"); Literal litPrice = e.Item.FindControl("litPrice") as Literal; Literal litTotalPrice = e.Item.FindControl("litTotalPrice") as Literal; LinkButton btnDelete = e.Item.FindControl("btnDelete") as LinkButton; ProductLine productLine = e.Item.DataItem as ProductLine; const string attributeClass = "class"; const string classColImageText = "colImageText"; switch (this.DisplayMode) { case OrderDisplayMode.OrderConfirmation: { if (liHeader != null) { liHeader.Visible = false; } if (tdCommands != null) { tdCommands.Visible = false; } if (divImage != null) { divImage.Visible = false; } if (divNumber != null) { if (productLine != null) { if (!string.IsNullOrEmpty(productLine.Product.Code)) { divNumber.Visible = true; } else { if (divText != null) { divText.Attributes.Add(attributeClass, classColImageText); } } if (litPrice != null && litTotalPrice != null) { if (ShoppingCartSettings.ShowPriceIncVAT) { litPrice.Text = this.FormatPrice(productLine.Totals.PriceIncVat); litTotalPrice.Text = this.FormatPrice(productLine.Totals.TotalPriceIncVat); } else { litPrice.Text = this.FormatPrice(productLine.Totals.PriceExVat); litTotalPrice.Text = this.FormatPrice(productLine.Totals.TotalPriceExVat); } } } } if (divCountEdit != null) { divCountEdit.Visible = false; } break; } case OrderDisplayMode.ShoppingCart: { if (!ShoppingCartSettings.ShowImage) { if (divImage != null) { divImage.Visible = false; } if (divNumber != null) { if (productLine != null) { if (!string.IsNullOrEmpty(productLine.Product.Code)) { divNumber.Visible = true; } else { if (divText != null) { divText.Attributes.Add(attributeClass, classColImageText); } } } } } if (productLine != null) { if (btnDelete != null) { btnDelete.CommandArgument = productLine.Product.Code; } if (litPrice != null && litTotalPrice != null) { if (ShoppingCartSettings.ShowPriceIncVAT) { litPrice.Text = this.FormatPrice(productLine.Totals.PriceIncVat); litTotalPrice.Text = this.FormatPrice(productLine.Totals.TotalPriceIncVat); } else { litPrice.Text = this.FormatPrice(productLine.Totals.PriceExVat); litTotalPrice.Text = this.FormatPrice(productLine.Totals.TotalPriceExVat); } } } if (divCountDisplay != null) { divCountDisplay.Visible = false; } break; } } } /// <summary> /// Gets the Friendly Url /// </summary> /// <param name="dataItem"> /// The data item. /// </param> /// <returns> /// Shopping cart item friendly url. /// </returns> protected string ShoppingCartLineFriendlyUrl(object dataItem) { string friendlyUrl; if (this.DisplayMode == OrderDisplayMode.ShoppingCart) { ShoppingCartLine shoppingCartItem = (ShoppingCartLine)dataItem; friendlyUrl = shoppingCartItem.FriendlyUrl; } else { OrderLine orderLine = (OrderLine)dataItem; friendlyUrl = orderLine.FriendlyUrl; } return AnalyticsUtil.AddFollowListToQueryString(friendlyUrl, this.DisplayMode.ToString()); } /// <summary> /// Formats the price. /// </summary> /// <param name="price">The price.</param> /// <returns>Returns formated price.</returns> protected virtual string FormatPrice(object price) { return MainUtil.FormatPrice(price, GeneralSettings.DisplayCurrencyOnPrices, ShoppingCartSettings.PriceFormatString, this.Currency.Code); } #endregion } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Query; using Microsoft.Xrm.Sdk.Messages; using Adxstudio.Xrm.Resources; namespace Adxstudio.Xrm.Commerce { public class CommerceQuote { private OrganizationServiceContext _context; public Entity Entity { get; private set; } public Guid Id { get; private set; } public CommerceQuote(Entity quote, OrganizationServiceContext context) { if (quote == null) { throw new ArgumentNullException("quote"); } if (quote.LogicalName != "quote") { throw new ArgumentException(string.Format("Value must have logical name {0}.", quote.LogicalName), "quote"); } Entity = quote; Id = quote.Id; _context = context; } public CommerceQuote(Dictionary<string, string> values, IPortalContext xrm, string paymentProvider) { if (paymentProvider == "PayPal") { CreateQuotePayPal(values, xrm); } } public T GetAttributeValue<T>(string attributeName) { return Entity.GetAttributeValue<T>(attributeName); } private void CreateQuotePayPal(Dictionary<string, string> values, IPortalContext xrm) { _context = xrm.ServiceContext; if (!values.ContainsKey("invoice")) { throw new Exception("no invoice found"); } var shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault( q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"])); var quote = new Entity("quote"); var orderGuid = Guid.NewGuid(); quote.Attributes["quoteid"] = orderGuid; quote.Id = orderGuid; quote.Attributes["name"] = "quote created by: " + shoppingCart.GetAttributeValue<string>("adx_name"); quote.Attributes["adx_shoppingcartid"] = shoppingCart.ToEntityReference(); //Ensure that there is a customer var customer = GetQuoteCustomer(values, _context, shoppingCart); if (!_context.IsAttached(shoppingCart)) { _context.Attach(shoppingCart); } shoppingCart.Attributes["adx_contactid"] = customer.ToEntityReference(); quote.Attributes["customerid"] = customer.ToEntityReference(); var priceLevel = _context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web"); if (priceLevel == null) { throw new Exception("price level null"); } //Set the price level var priceLevelReference = priceLevel.ToEntityReference(); quote.Attributes["pricelevelid"] = priceLevelReference; //Set the address for the order SetQuoteAddresses(values, quote, customer); //order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber"); //order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null; _context.AddObject(quote); _context.UpdateObject(shoppingCart); _context.SaveChanges(); //Set the products of the order SetQuoteProducts(shoppingCart, _context, orderGuid); //Deactivate the shopping Cart shoppingCart = _context.CreateQuery("adx_shoppingcart").FirstOrDefault( q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"])); try { _context.SetState(1, 2, shoppingCart); _context.SaveChanges(); } catch { //Unlikely that there is an issue, most likely it has already been deactiveated. } Entity = _context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue<Guid>("quoteid") == orderGuid); Id = Entity.Id; } private static void SetQuoteProducts(Entity shoppingCart, OrganizationServiceContext context, Guid quoteGuid) { var cartItems = context.CreateQuery("adx_shoppingcartitem") .Where( qp => qp.GetAttributeValue<EntityReference>("adx_shoppingcartid").Id == shoppingCart.GetAttributeValue<Guid>("adx_shoppingcartid")).ToList(); foreach (var item in cartItems) { var invoiceOrder = context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue<Guid>("quoteid") == quoteGuid); var orderProduct = new Entity("quotedetail"); var detailGuid = Guid.NewGuid(); orderProduct.Attributes["quotedetailid"] = detailGuid; orderProduct.Id = detailGuid; var product = context.CreateQuery("product") .FirstOrDefault( p => p.GetAttributeValue<Guid>("productid") == item.GetAttributeValue<EntityReference>("adx_productid").Id); var unit = context.CreateQuery("uom") .FirstOrDefault( uom => uom.GetAttributeValue<Guid>("uomid") == product.GetAttributeValue<EntityReference>("defaultuomid").Id); /*var unit = context.CreateQuery("uom") .FirstOrDefault( uom => uom.GetAttributeValue<Guid>("uomid") == item.GetAttributeValue<EntityReference>("adx_uomid").Id);*/ orderProduct.Attributes["productid"] = product.ToEntityReference(); orderProduct.Attributes["uomid"] = unit.ToEntityReference(); orderProduct.Attributes["ispriceoverridden"] = true; orderProduct.Attributes["priceperunit"] = item.GetAttributeValue<Money>("adx_quotedprice"); orderProduct.Attributes["quantity"] = item.GetAttributeValue<decimal>("adx_quantity"); orderProduct.Attributes["quoteid"] = invoiceOrder.ToEntityReference(); context.AddObject(orderProduct); //context.UpdateObject(invoiceOrder); context.SaveChanges(); var detail = context.CreateQuery("quotedetail").FirstOrDefault(sod => sod.GetAttributeValue<Guid>("quotedetailid") == detailGuid); } } private static void SetQuoteAddresses(Dictionary<string, string> values, Entity quote, Entity customer) { quote.Attributes["billto_line1"] = customer.GetAttributeValue<string>("address1_line1"); quote.Attributes["billto_city"] = customer.GetAttributeValue<string>("address1_city"); quote.Attributes["billto_country"] = customer.GetAttributeValue<string>("address1_country"); quote.Attributes["billto_stateorprovince"] = customer.GetAttributeValue<string>("address1_stateorprovince"); quote.Attributes["billto_postalcode"] = customer.GetAttributeValue<string>("address1_postalcode"); quote.Attributes["shipto_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ?? (values.ContainsKey("address1") ? values["address1"] : null) ?? customer.GetAttributeValue<string>("address1_line1"); quote.Attributes["shipto_city"] = (values.ContainsKey("address_street") ? values["address_city"] : null) ?? (values.ContainsKey("city") ? values["city"] : null) ?? customer.GetAttributeValue<string>("address1_city"); quote.Attributes["shipto_country"] = (values.ContainsKey("address_street") ? values["address_country"] : null) ?? (values.ContainsKey("country") ? values["country"] : null) ?? customer.GetAttributeValue<string>("address1_country"); quote.Attributes["shipto_stateorprovince"] = (values.ContainsKey("address_street") ? values["address_state"] : null) ?? (values.ContainsKey("state") ? values["state"] : null) ?? customer.GetAttributeValue<string>("address1_stateorprovince"); quote.Attributes["shipto_postalcode"] = (values.ContainsKey("address_street") ? values["address_zip"] : null) ?? (values.ContainsKey("zip") ? values["zip"] : null) ?? customer.GetAttributeValue<string>("address1_postalcode"); } private static Entity GetQuoteCustomer(Dictionary<string, string> values, OrganizationServiceContext context, Entity shoppingCart) { Guid customerID; Entity customer; if (shoppingCart.GetAttributeValue<EntityReference>("adx_contactid") != null) { customerID = shoppingCart.GetAttributeValue<EntityReference>("adx_contactid").Id; } else //Probably will not be used { customer = new Entity("contact"); customerID = Guid.NewGuid(); customer.Attributes["contactid"] = customerID; customer.Id = customerID; var firstName = (values.ContainsKey("first_name") ? values["first_name"] : null) ?? "Tim"; customer.Attributes["firstname"] = firstName; customer.Attributes["lastname"] = (values.ContainsKey("last_name") ? values["last_name"] : null) ?? "Sample"; customer.Attributes["telephone1"] = (values.ContainsKey("contact_phone") ? values["contact_phone"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "555-9765" : null); customer.Attributes["address1_line1"] = (values.ContainsKey("address_street") ? values["address_street"] : null) ?? (values.ContainsKey("address1") ? values["address1"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "123 easy street" : null); customer.Attributes["address1_city"] = (values.ContainsKey("address_city") ? values["address_city"] : null) ?? (values.ContainsKey("city") ? values["city"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "Anytown" : null); customer.Attributes["address1_country"] = (values.ContainsKey("address_country") ? values["address_country"] : null) ?? (values.ContainsKey("country") ? values["country"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "USA" : null); customer.Attributes["address1_stateorprovince"] = (values.ContainsKey("address_state") ? values["address_state"] : null) ?? (values.ContainsKey("state") ? values["state"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "NY" : null); customer.Attributes["address1_postalcode"] = (values.ContainsKey("address_zip") ? values["address_zip"] : null) ?? (values.ContainsKey("zip") ? values["zip"] : null) ?? ((string.IsNullOrEmpty(firstName)) ? "91210" : null); context.AddObject(customer); context.SaveChanges(); } customer = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == customerID); return customer; } public Entity CreateOrder() { var shoppingCartReference = GetAttributeValue<EntityReference>("adx_shoppingcartid"); ConvertQuoteToOrder(_context, Entity); var orderCreated = _context.CreateQuery("salesorder").FirstOrDefault(so => so.GetAttributeValue<EntityReference>("quoteid").Id == Entity.GetAttributeValue<Guid>("quoteid")); orderCreated.Attributes["adx_shoppingcartid"] = shoppingCartReference; _context.UpdateObject(orderCreated); _context.SaveChanges(); orderCreated = _context.CreateQuery("salesorder").FirstOrDefault(so => so.GetAttributeValue<Guid>("salesorderid") == orderCreated.GetAttributeValue<Guid>("salesorderid")); return orderCreated; } /***** Currently unable to get this function working. * Soemthing about the WinQuoteRequest and CloseQuoteRequest does not fuction as expected * error: "cannot close the entity because it is not in the correct state" always occurs * ******************/ private static void ConvertQuoteToOrder(Microsoft.Xrm.Sdk.Client.OrganizationServiceContext context, Microsoft.Xrm.Sdk.Entity myQuote) { // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = myQuote.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(2) }; context.Execute(activateQuote); //Console.WriteLine("Quote activated."); Guid quoteId = myQuote.GetAttributeValue<Guid>("quoteid"); var quoteClose = new Entity("quoteclose"); quoteClose.Attributes["quoteid"] = myQuote.ToEntityReference(); quoteClose.Attributes["subject"] = "Won The Quote"; WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = quoteClose, Status = new OptionSetValue(-1) //2? -1?? }; var winQuoteResponse = (WinQuoteResponse)context.Execute(winQuoteRequest); ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); var convertOrderRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = quoteId, ColumnSet = salesOrderColumns }; var convertOrderResponse = (ConvertQuoteToSalesOrderResponse)context.Execute(convertOrderRequest); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.RibbonCommandsWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Xsl; using System.Net; namespace XmlNotepad { public partial class XsltViewer : UserControl { Uri baseUri; XslCompiledTransform defaultss; XslCompiledTransform xslt; Uri xsltUri; DateTime loaded; XsltSettings settings; XmlUrlResolver resolver; ISite site; XmlCache model; XmlDocument doc; bool showFileStrip = true; string defaultSSResource = "XmlNotepad.DefaultSS.xslt"; IDictionary<Uri, bool> trusted = new Dictionary<Uri, bool>(); int stripHeight; string html; public XsltViewer() { this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); InitializeComponent(); stripHeight = this.WebBrowser1.Top; xslt = new XslCompiledTransform(); settings = new XsltSettings(true, true); resolver = new XmlUrlResolver(); toolTip1.SetToolTip(this.BrowseButton, SR.BrowseButtonTooltip); toolTip1.SetToolTip(this.SourceFileName, SR.XslFileNameTooltip); toolTip1.SetToolTip(this.TransformButton, SR.TransformButtonTooltip); BrowseButton.Click += new EventHandler(BrowseButton_Click); this.SourceFileName.KeyDown += new KeyEventHandler(OnSourceFileNameKeyDown); this.WebBrowser1.ScriptErrorsSuppressed = true; this.WebBrowser1.WebBrowserShortcutsEnabled = true; } public string DefaultStylesheetResource { get { return this.defaultSSResource; } set { this.defaultSSResource = value; } } public bool ShowFileStrip { get { return this.showFileStrip; } set { if (value != this.showFileStrip) { this.showFileStrip = value; if (value) { AnchorStyles saved = this.WebBrowser1.Anchor; this.WebBrowser1.Anchor = AnchorStyles.None; this.WebBrowser1.Location = new Point(0, stripHeight); this.WebBrowser1.Height = this.Height - stripHeight; this.WebBrowser1.Anchor = saved; this.panel1.Controls.Remove(this.tableLayoutPanel1); this.panel1.Controls.SetChildIndex(this.tableLayoutPanel1, 0); } else { AnchorStyles saved = this.WebBrowser1.Anchor; this.WebBrowser1.Location = new Point(0, 0); this.WebBrowser1.Height = this.Height; this.WebBrowser1.Anchor = saved; this.panel1.Controls.Add(this.tableLayoutPanel1); } this.TransformButton.Visible = value; this.BrowseButton.Visible = value; this.SourceFileName.Visible = value; } } } void OnSourceFileNameKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.DisplayXsltResults(); } } XslCompiledTransform GetDefaultStylesheet() { if (defaultss != null) { return defaultss; } using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(this.defaultSSResource)) { if (null != stream) { using (XmlReader reader = XmlReader.Create(stream)) { XslCompiledTransform t = new XslCompiledTransform(); t.Load(reader); defaultss = t; } } } return defaultss; } protected override void OnPaint(PaintEventArgs e) { if (this.showFileStrip && this.WebBrowser1.Top > 0 && this.Width > 0) { Graphics g = e.Graphics; Rectangle r = new Rectangle(0, 0, this.Width, this.WebBrowser1.Top); Color c1 = Color.FromArgb(250, 249, 245); Color c2 = Color.FromArgb(192, 192, 168); Color s1 = SystemColors.ControlLight; using (LinearGradientBrush brush = new LinearGradientBrush(r, c1, c2, LinearGradientMode.Vertical)) { g.FillRectangle(brush, r); } } } public void SetSite(ISite site) { this.site = site; IServiceProvider sp = (IServiceProvider)site; this.resolver = new XmlProxyResolver(sp); this.model = (XmlCache)site.GetService(typeof(XmlCache)); this.model.ModelChanged -= new EventHandler<ModelChangedEventArgs>(OnModelChanged); this.model.ModelChanged += new EventHandler<ModelChangedEventArgs>(OnModelChanged); } void OnModelChanged(object sender, ModelChangedEventArgs e) { OnModelChanged(); } void OnModelChanged() { this.doc = model.Document; try { if (!string.IsNullOrEmpty(model.FileName)) { this.baseUri = new Uri(model.FileName); } this.SourceFileName.Text = model.XsltFileName; } catch (Exception) { } } Uri GetBaseUri() { if (this.baseUri == null) { OnModelChanged(); if (this.baseUri == null) { this.baseUri = new Uri(Application.StartupPath + "/"); } } return this.baseUri; } protected override void OnLayout(LayoutEventArgs e) { base.OnLayout(e); if (showFileStrip) { this.WebBrowser1.Top = this.tableLayoutPanel1.Bottom; this.WebBrowser1.Height = this.Height - this.tableLayoutPanel1.Height; } else { this.WebBrowser1.Top = 0; this.WebBrowser1.Height = this.Height; } } public void DisplayXsltResults() { DisplayXsltResults(doc); } public void DisplayXsltResults(XmlDocument context) { Uri resolved = null; try { XslCompiledTransform transform; string path = null; if (this.showFileStrip) { path = this.SourceFileName.Text.Trim(); } if (string.IsNullOrEmpty(path)) { transform = GetDefaultStylesheet(); } else { resolved = new Uri(baseUri, path); if (resolved != this.xsltUri || IsModified()) { this.loaded = DateTime.Now; settings.EnableScript = (trusted.ContainsKey(resolved)); XmlReaderSettings rs = new XmlReaderSettings(); rs.ProhibitDtd = false; rs.XmlResolver = resolver; using (XmlReader r = XmlReader.Create(resolved.AbsoluteUri, rs)) { xslt.Load(r, settings, resolver); } } transform = xslt; } if (null != transform) { StringWriter writer = new StringWriter(); XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = new XmlProxyResolver(this.site); settings.ProhibitDtd = false; transform.Transform(XmlIncludeReader.CreateIncludeReader(context, settings, GetBaseUri().AbsoluteUri), null, writer); this.xsltUri = resolved; Display(writer.ToString()); } } catch (System.Xml.Xsl.XsltException x) { if (x.Message.Contains("XsltSettings")) { if (!trusted.ContainsKey(resolved) && MessageBox.Show(this, SR.XslScriptCodePrompt, SR.XslScriptCodeCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { trusted[resolved] = true; DisplayXsltResults(); return; } } WriteError(x); } catch (Exception x) { WriteError(x); } } bool IsModified() { if (this.xsltUri.IsFile) { string path = this.xsltUri.LocalPath; DateTime lastWrite = File.GetLastWriteTime(path); return this.loaded < lastWrite; } return false; } private void WriteError(Exception e) { StringWriter writer = new StringWriter(); writer.WriteLine("<html><body><h3>"); writer.WriteLine(SR.TransformErrorCaption); writer.WriteLine("</h3></body></html>"); while (e != null) { writer.WriteLine(e.Message); e = e.InnerException; } Display(writer.ToString()); } private void Display(string content) { if (content != this.html) { this.WebBrowser1.DocumentText = content; this.html = content; } } private void BrowseButton_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = SR.XSLFileFilter; if (ofd.ShowDialog(this) == DialogResult.OK) { this.SourceFileName.Text = ofd.FileName; } } private void TransformButton_Click(object sender, EventArgs e) { this.DisplayXsltResults(); } private Guid cmdGuid = new Guid("ED016940-BD5B-11CF-BA4E-00C04FD70816"); private enum OLECMDEXECOPT { OLECMDEXECOPT_DODEFAULT = 0, OLECMDEXECOPT_PROMPTUSER = 1, OLECMDEXECOPT_DONTPROMPTUSER = 2, OLECMDEXECOPT_SHOWHELP = 3 } private enum MiscCommandTarget { Find = 1, ViewSource, Options } private mshtml.HTMLDocument GetDocument() { try { mshtml.HTMLDocument htm = (mshtml.HTMLDocument)this.WebBrowser1.Document.DomDocument; return htm; } catch { throw (new Exception("Cannot retrieve the document from the WebBrowser control")); } } public void ViewSource() { IOleCommandTarget cmdt; Object o = new object(); try { cmdt = (IOleCommandTarget)GetDocument(); cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.ViewSource, (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } } public void Find() { IOleCommandTarget cmdt; Object o = new object(); try { cmdt = (IOleCommandTarget)GetDocument(); cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.Find, (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } } } [CLSCompliant(false), StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct OLECMDTEXT { public uint cmdtextf; public uint cwActual; public uint cwBuf; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] public char rgwz; } [CLSCompliant(false), StructLayout(LayoutKind.Sequential)] public struct OLECMD { public uint cmdID; public uint cmdf; } // Interop definition for IOleCommandTarget. [CLSCompliant(false), ComImport, Guid("b722bccb-4e68-101b-a2bc-00aa00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IOleCommandTarget { //IMPORTANT: The order of the methods is critical here. You //perform early binding in most cases, so the order of the methods //here MUST match the order of their vtable layout (which is determined //by their layout in IDL). The interop calls key off the vtable ordering, //not the symbolic names. Therefore, if you switched these method declarations //and tried to call the Exec method on an IOleCommandTarget interface from your //application, it would translate into a call to the QueryStatus method instead. void QueryStatus(ref Guid pguidCmdGroup, UInt32 cCmds, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] OLECMD[] prgCmds, ref OLECMDTEXT CmdText); void Exec(ref Guid pguidCmdGroup, uint nCmdId, uint nCmdExecOpt, ref object pvaIn, ref object pvaOut); } }
/* * Copyright (c) 2007-2008, openmetaverse.org * 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.org 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.Net; using System.IO; using System.Threading; namespace OpenMetaverse.Capabilities { public class CapsBase { #region Callback Data Classes public class OpenWriteCompletedEventArgs { public Stream Result; public Exception Error; public bool Cancelled; public object UserState; public OpenWriteCompletedEventArgs(Stream result, Exception error, bool cancelled, object userState) { Result = result; Error = error; Cancelled = cancelled; UserState = userState; } } public class UploadDataCompletedEventArgs { public byte[] Result; public Exception Error; public bool Cancelled; public object UserState; public UploadDataCompletedEventArgs(byte[] result, Exception error, bool cancelled, object userState) { Result = result; Error = error; Cancelled = cancelled; UserState = userState; } } public class DownloadDataCompletedEventArgs { public byte[] Result; public Exception Error; public bool Cancelled; public object UserState; } public class DownloadStringCompletedEventArgs { public Uri Address; public string Result; public Exception Error; public bool Cancelled; public object UserState; public DownloadStringCompletedEventArgs(Uri address, string result, Exception error, bool cancelled, object userState) { Address = address; Result = result; Error = error; Cancelled = cancelled; UserState = userState; } } public class DownloadProgressChangedEventArgs { public long BytesReceived; public int ProgressPercentage; public long TotalBytesToReceive; public object UserState; public DownloadProgressChangedEventArgs(long bytesReceived, long totalBytesToReceive, object userToken) { BytesReceived = bytesReceived; ProgressPercentage = (int)(((float)bytesReceived / (float)totalBytesToReceive) * 100f); TotalBytesToReceive = totalBytesToReceive; UserState = userToken; } } public class UploadProgressChangedEventArgs { public long BytesReceived; public long BytesSent; public int ProgressPercentage; public long TotalBytesToReceive; public long TotalBytesToSend; public object UserState; public UploadProgressChangedEventArgs(long bytesReceived, long totalBytesToReceive, long bytesSent, long totalBytesToSend, object userState) { BytesReceived = bytesReceived; TotalBytesToReceive = totalBytesToReceive; ProgressPercentage = (int)(((float)bytesSent / (float)totalBytesToSend) * 100f); BytesSent = bytesSent; TotalBytesToSend = totalBytesToSend; UserState = userState; } } #endregion Callback Data Classes public delegate void OpenWriteCompletedEventHandler(object sender, OpenWriteCompletedEventArgs e); public delegate void UploadDataCompletedEventHandler(object sender, UploadDataCompletedEventArgs e); public delegate void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs e); public delegate void DownloadProgressChangedEventHandler(object sender, DownloadProgressChangedEventArgs e); public delegate void UploadProgressChangedEventHandler(object sender, UploadProgressChangedEventArgs e); public event OpenWriteCompletedEventHandler OpenWriteCompleted; public event UploadDataCompletedEventHandler UploadDataCompleted; public event DownloadStringCompletedEventHandler DownloadStringCompleted; public event DownloadProgressChangedEventHandler DownloadProgressChanged; public event UploadProgressChangedEventHandler UploadProgressChanged; public WebHeaderCollection Headers = new WebHeaderCollection(); public IWebProxy Proxy; public Uri Location { get { return location; } } public bool IsBusy { get { return isBusy; } } public WebHeaderCollection ResponseHeaders { get { return responseHeaders; } } protected WebHeaderCollection responseHeaders; protected Uri location; protected bool isBusy; protected Thread asyncThread; protected System.Text.Encoding encoding = System.Text.Encoding.Default; public CapsBase(Uri location) { this.location = location; } public void OpenWriteAsync(Uri address) { OpenWriteAsync(address, null, null); } public void OpenWriteAsync(Uri address, string method) { OpenWriteAsync(address, method, null); } public void OpenWriteAsync(Uri address, string method, object userToken) { if (address == null) throw new ArgumentNullException("address"); SetBusy(); asyncThread = new Thread(delegate(object state) { object[] args = (object[])state; WebRequest request = null; try { request = SetupRequest((Uri)args[0]); Stream stream = request.GetRequestStream(); OnOpenWriteCompleted(new OpenWriteCompletedEventArgs( stream, null, false, args[2])); } catch (ThreadInterruptedException) { if (request != null) request.Abort(); OnOpenWriteCompleted(new OpenWriteCompletedEventArgs( null, null, true, args[2])); } catch (Exception e) { OnOpenWriteCompleted(new OpenWriteCompletedEventArgs( null, e, false, args[2])); } }); object[] cbArgs = new object[] { address, method, userToken }; asyncThread.Start(cbArgs); } public void UploadDataAsync(Uri address, byte[] data) { UploadDataAsync(address, null, data, null); } public void UploadDataAsync(Uri address, string method, byte[] data) { UploadDataAsync(address, method, data, null); } public void UploadDataAsync(Uri address, string method, byte[] data, object userToken) { if (address == null) throw new ArgumentNullException("address"); if (data == null) throw new ArgumentNullException("data"); SetBusy(); asyncThread = new Thread(delegate(object state) { object[] args = (object[])state; byte[] data2; try { data2 = UploadDataCore((Uri)args[0], (string)args[1], (byte[])args[2], args[3]); OnUploadDataCompleted( new UploadDataCompletedEventArgs(data2, null, false, args[3])); } catch (ThreadInterruptedException) { OnUploadDataCompleted( new UploadDataCompletedEventArgs(null, null, true, args[3])); } catch (Exception e) { OnUploadDataCompleted( new UploadDataCompletedEventArgs(null, e, false, args[3])); } }); object[] cbArgs = new object[] { address, method, data, userToken }; asyncThread.Start(cbArgs); } public void DownloadStringAsync(Uri address) { DownloadStringAsync(address, null); } public void DownloadStringAsync(Uri address, object userToken) { if (address == null) throw new ArgumentNullException("address"); SetBusy(); asyncThread = new Thread(delegate(object state) { object[] args = (object[])state; try { string data = encoding.GetString(DownloadDataCore((Uri)args[0], args[1])); OnDownloadStringCompleted( new DownloadStringCompletedEventArgs(location, data, null, false, args[1])); } catch (ThreadInterruptedException) { OnDownloadStringCompleted( new DownloadStringCompletedEventArgs(location, null, null, true, args[1])); } catch (Exception e) { OnDownloadStringCompleted( new DownloadStringCompletedEventArgs(location, null, e, false, args[1])); } }); object[] cbArgs = new object[] { address, userToken }; asyncThread.Start(cbArgs); } public void CancelAsync() { if (asyncThread == null) return; Thread t = asyncThread; CompleteAsync(); t.Interrupt(); } protected void CompleteAsync() { isBusy = false; asyncThread = null; } protected void SetBusy() { CheckBusy(); isBusy = true; } protected void CheckBusy() { if (isBusy) throw new NotSupportedException("CapsBase does not support concurrent I/O operations."); } protected Stream ProcessResponse(WebResponse response) { responseHeaders = response.Headers; return response.GetResponseStream(); } protected byte[] ReadAll(Stream stream, int length, object userToken, bool uploading) { MemoryStream ms = null; bool nolength = (length == -1); int size = ((nolength) ? 8192 : length); if (nolength) ms = new MemoryStream(); long total = 0; int nread = 0; int offset = 0; byte[] buffer = new byte[size]; while ((nread = stream.Read(buffer, offset, size)) != 0) { if (nolength) { ms.Write(buffer, 0, nread); } else { offset += nread; size -= nread; } if (uploading) { if (UploadProgressChanged != null) { total += nread; UploadProgressChanged(this, new UploadProgressChangedEventArgs(nread, length, 0, 0, userToken)); } } else { if (DownloadProgressChanged != null) { total += nread; DownloadProgressChanged(this, new DownloadProgressChangedEventArgs(nread, length, userToken)); } } } if (nolength) return ms.ToArray(); return buffer; } protected WebRequest SetupRequest(Uri uri) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); if (request == null) throw new ArgumentException("Could not create an HttpWebRequest from the given Uri", "address"); location = uri; if (Proxy != null) request.Proxy = Proxy; request.Method = "POST"; if (Headers != null && Headers.Count != 0) { string expect = Headers["Expect"]; string contentType = Headers["Content-Type"]; string accept = Headers["Accept"]; string connection = Headers["Connection"]; string userAgent = Headers["User-Agent"]; string referer = Headers["Referer"]; if (!String.IsNullOrEmpty(expect)) request.Expect = expect; if (!String.IsNullOrEmpty(accept)) request.Accept = accept; if (!String.IsNullOrEmpty(contentType)) request.ContentType = contentType; if (!String.IsNullOrEmpty(connection)) request.Connection = connection; if (!String.IsNullOrEmpty(userAgent)) request.UserAgent = userAgent; if (!String.IsNullOrEmpty(referer)) request.Referer = referer; } // Disable keep-alive by default request.KeepAlive = false; // Set the closed connection (idle) time to one second request.ServicePoint.MaxIdleTime = 1000; // Disable stupid Expect-100: Continue header request.ServicePoint.Expect100Continue = false; // Crank up the max number of connections (default is 2!) request.ServicePoint.ConnectionLimit = 20; return request; } protected WebRequest SetupRequest(Uri uri, string method) { WebRequest request = SetupRequest(uri); request.Method = method; return request; } protected byte[] UploadDataCore(Uri address, string method, byte[] data, object userToken) { HttpWebRequest request = (HttpWebRequest)SetupRequest(address); // Mono insists that if you have Content-Length set, Keep-Alive must be true. // Otherwise the unhelpful exception of "Content-Length not set" will be thrown. // The Linden Lab event queue server breaks HTTP 1.1 by always replying with a // Connection: Close header, which will confuse the Windows .NET runtime and throw // a "Connection unexpectedly closed" exception. This is our cross-platform hack if (Utils.GetRunningRuntime() == Utils.Runtime.Mono) request.KeepAlive = true; try { // Content-Length int contentLength = data.Length; request.ContentLength = contentLength; using (Stream stream = request.GetRequestStream()) { // Most uploads are very small chunks of data, use an optimized path for these if (contentLength < 4096) { stream.Write(data, 0, contentLength); } else { // Upload chunks directly instead of buffering to memory request.AllowWriteStreamBuffering = false; MemoryStream ms = new MemoryStream(data); byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)contentLength))]; int bytesRead = 0; while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); if (UploadProgressChanged != null) { UploadProgressChanged(this, new UploadProgressChangedEventArgs(0, 0, bytesRead, contentLength, userToken)); } } ms.Close(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream st = ProcessResponse(response); contentLength = (int)response.ContentLength; return ReadAll(st, contentLength, userToken, true); } catch (ThreadInterruptedException) { if (request != null) request.Abort(); throw; } } protected byte[] DownloadDataCore(Uri address, object userToken) { WebRequest request = null; try { request = SetupRequest(address, "GET"); WebResponse response = request.GetResponse(); Stream st = ProcessResponse(response); return ReadAll(st, (int)response.ContentLength, userToken, false); } catch (ThreadInterruptedException) { if (request != null) request.Abort(); throw; } catch (Exception ex) { throw new WebException("An error occurred performing a WebClient request.", ex); } } protected virtual void OnOpenWriteCompleted(OpenWriteCompletedEventArgs args) { CompleteAsync(); if (OpenWriteCompleted != null) OpenWriteCompleted(this, args); } protected virtual void OnUploadDataCompleted(UploadDataCompletedEventArgs args) { CompleteAsync(); if (UploadDataCompleted != null) UploadDataCompleted(this, args); } protected virtual void OnDownloadStringCompleted(DownloadStringCompletedEventArgs args) { CompleteAsync(); if (DownloadStringCompleted != null) DownloadStringCompleted(this, args); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // #define DACTABLEGEN_DEBUG using System; using System.IO; using System.Text.RegularExpressions; using System.Collections; using System.Globalization; /*************************************************************************************** * ***************************************************************************************/ public class MapSymbolProvider : SymbolProvider { public MapSymbolProvider(String symbolFilename) { mf = new MapFile(symbolFilename); } public override UInt32 GetGlobalRVA(String symbolName, SymType symType) { return GetRVA(symbolName); } public override UInt32 GetVTableRVA(String symbolName, String keyBaseName) { if (keyBaseName != null) { return GetRVA(symbolName + "__" + keyBaseName); } else { return GetRVA(symbolName); } } UInt32 GetRVA(String symbolName) { SymbolInfo si = mf.FindSymbol(symbolName); if (si == null) { // Ideally this would throw an exception and // cause the whole process to fail but // currently it's too complicated to get // all the ifdef'ing right for all the // mix of debug/checked/free multiplied by // x86/AMD64/IA64/etc. return UInt32.MaxValue; } return mf.GetRVA(si); } MapFile mf = null; } public class SymbolInfo { public SymbolInfo(int Segment, UInt32 Address) { m_Segment = Segment; m_Address = Address; m_dupFound = false; } public int Segment { get { return m_Segment; } } public UInt32 Address { get { return m_Address; } } public bool dupFound { get { return m_dupFound; } set { m_dupFound = value; } } int m_Segment; // The segment index. (Used only in Windows MAP file.) UInt32 m_Address; bool m_dupFound; // Have we found a duplicated entry for this key? } public class MapFile { const String Reg_ExWhiteSpaces = @"\s+"; // // These are regular expression strings for Windows MAP file. // const String Reg_MapAddress = @"^ (?<addrPart1>[0-9a-f]{4}):(?<addrPart2>[0-9a-f]{8})"; enum WindowsSymbolTypes { ModuleNameClassNameFieldName, ClassNameFieldName, GlobalVarName, GlobalVarName2, GlobalVarName3, SingleVtAddr, MultiVtAddr, }; readonly String[] RegExps_WindowsMapfile = { // ModuleNameClassNameFieldName // Example: ?ephemeral_heap_segment@gc_heap@WKS@@ Reg_MapAddress + Reg_ExWhiteSpaces + @"\?(?<fieldName>[^\?@]+)@(?<className>[^\?@]+)@(?<moduleName>[^\?@]+)@@", // ClassNameFieldName // Example: ?m_RangeTree@ExecutionManager@@ Reg_MapAddress + Reg_ExWhiteSpaces + @"\?(?<fieldName>[^\?@]+)@(?<className>[^\?@]+)@@", // GlobalVarName // Example: ?g_pNotificationTable@@ // (or) ?JIT_LMul@@ Reg_MapAddress + Reg_ExWhiteSpaces + @"\?(?<globalVarName>[^\?@]+)@@", // GlobalVarName2 // Example: @JIT_WriteBarrier@ // (or) _JIT_FltRem@ // (or) _JIT_Dbl2Lng@ // (or) _JIT_LLsh@ Reg_MapAddress + Reg_ExWhiteSpaces + @"[@_](?<globalVarName>[^\?@]+)@", // GlobalVarName3 // Example: _g_card_table 795e53a4 Reg_MapAddress + Reg_ExWhiteSpaces + @"_(?<globalVarName>[^\s@]+)" + Reg_ExWhiteSpaces + @"[0-9a-f]{8}", // Single-inheritance VtAddr // Example: ??_7Thread@@6B@ Reg_MapAddress + Reg_ExWhiteSpaces + @"\?\?_7(?<FunctionName>[^\?@]+)@@6B@", // Multiple-inheritance VtAddr // Example: ??_7CompilationDomain@@6BAppDomain@@@ Reg_MapAddress + Reg_ExWhiteSpaces + @"\?\?_7(?<FunctionName>[^\?@]+)@@6B(?<BaseName>[^@]+)@@@" }; const String Reg_Length = @"(?<length>[0-9a-f]{8})H"; const String Reg_SegmentInfo = Reg_MapAddress + " " + Reg_Length; // // These are regular expression strings for Unix NM file. // const String Reg_NmAddress = @"^(?<address>[0-9a-f]{8})"; const String Reg_TypeChar = @"[a-zA-Z]"; enum UnixSymbolTypes { CxxFieldName, CxxFunctionName, CGlobal, VtAddr, }; // Rather than try and encode a particular C++ mangling format here, we rely on the nm output // having been unmanagled through the c++filt tool. readonly String[] RegExps_UnixNmfile = { // C++ field name // Examples: // d WKS::gc_heap::ephemeral_heap_segment // d WKS::GCHeap::hEventFinalizer // s ExecutionManager::m_CodeRangeList // d ExecutionManager::m_dwReaderCount Reg_NmAddress + " " + Reg_TypeChar + " " + @"(?<symName>\w+(::\w+)+)$", // C++ function/method name // Note: may have duplicates due to overloading by argument types // Examples: // t JIT_LMulOvf(int, int, int, long long, long long) // t ThreadpoolMgr::AsyncCallbackCompletion(void*) // // Counter-examples we don't want to include: // b JIT_NewFast(int, int, CORINFO_CLASS_STRUCT_*)::__haveCheckedRestoreState // Reg_NmAddress + " " + Reg_TypeChar + " " + @"(?<symName>\w+(::\w+)*)\(.*\)$", // C global variable / function name // Examples: // s _g_pNotificationTable // t _JIT_LLsh Reg_NmAddress + " " + Reg_TypeChar + " " + @"_(?<symName>\w+)$", // VtAddr // Examples: // s vtable for Thread // // Note that at the moment we don't have any multiple-inheritance vtables that we need // on UNIX (CompilationDomain is the only one which is only present on FEATURE_PREJIT). // It looks like classes with multiple inheritance only list a single vtable in nm output // (eg. RegMeta). // We also don't support nested classes here because there is currently no syntax for them // for daccess.i. // Reg_NmAddress + " " + Reg_TypeChar + " " + @"vtable for (?<symName>\w+)$", }; public UInt32 GetRVA(SymbolInfo si) { UInt32 addr = si.Address; if (bIsWindowsMapfile) { addr += (UInt32)SegmentBase[si.Segment]; } return addr; } public MapFile(String symdumpFile) { m_symdumpFile = symdumpFile; loadDataFromMapFile(); } void ReadMapHeader(StreamReader strm) { Regex regExNmFile = new Regex("^[0-9a-f]{8} "); Regex regEx = new Regex(Reg_SegmentInfo); Regex regHeaderSection = new Regex(@"\s*Address\s*Publics by Value\s*Rva\+Base\s*Lib:Object", RegexOptions.IgnoreCase); Regex regnonNMHeader = new Regex(@"\s*Start\s*Length\s*Name\s*Class", RegexOptions.IgnoreCase); Match match = null; UInt32 lastSegmentIndex = 0; UInt32 segmentIndex; UInt32 sectionStart = 0; UInt32 sectionLength = 0; String line; bool bInSegmentDecl = false; const UInt32 baseOfCode = 0x1000; SegmentBase.Add((UInt32)baseOfCode); for (;;) { line = strm.ReadLine(); if (bInSegmentDecl) { if (regHeaderSection.IsMatch(line)) { // Header section ends. break; } #if DACTABLEGEN_DEBUG Console.WriteLine("SegmentDecl: " + line); #endif match = regEx.Match(line); if (match.Success) { segmentIndex = UInt32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); if (segmentIndex != lastSegmentIndex) { // Enter the new segment. Record what we have. // Note, SegmentBase[i] is built upon SegmentBase[i-1] SegmentBase.Add((UInt32)SegmentBase[SegmentBase.Count-1] + (sectionStart + sectionLength + (UInt32)0xFFF) & (~((UInt32)0xFFF))); lastSegmentIndex = segmentIndex; } sectionStart = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); sectionLength = UInt32.Parse(match.Groups["length"].ToString(), NumberStyles.AllowHexSpecifier); } if (line == null) { throw new InvalidOperationException("Invalid MAP header format."); } } else { if (!regnonNMHeader.IsMatch(line)) { match = regExNmFile.Match(line); if (match.Success) { // It's a nm file format. There is no header for it. break; } continue; } bInSegmentDecl = true; bIsWindowsMapfile = true; } } if (bIsWindowsMapfile) { // // Only Windows map file has SegmentBase // for (int i=1 ; i<= lastSegmentIndex; i++) { #if DACTABLEGEN_DEBUG Console.WriteLine("SegmentBase[{0}] = {1:x8}", i, SegmentBase[i]); #endif } } } public void loadDataFromMapFile() { StreamReader strm = new StreamReader(m_symdumpFile, System.Text.Encoding.ASCII); String line; int i; String[] RegExps; // Read the head of the symbol dump file and // determind the format of it. ReadMapHeader(strm); // // Scan through the symbol dump file looking // for the globals structure. // if (bIsWindowsMapfile) { RegExps = RegExps_WindowsMapfile; } else { RegExps = RegExps_UnixNmfile; } Console.WriteLine("It is a {0} file.", (bIsWindowsMapfile)?"Windows MAP":"Unix NM"); Regex[] RegExs = new Regex[RegExps.Length]; for (i = 0; i < RegExps.Length; i++) { #if DACTABLEGEN_DEBUG Console.WriteLine("RegEx[{0}]: {1}", i, RegExps[i]); #endif RegExs[i] = new Regex(RegExps[i]); } Match match = null; SymbolInfo si; String key; int segment; UInt32 address; for (;;) { line = strm.ReadLine(); if (line == null) { // No more to read. break; } // Console.WriteLine(">{0}", line); for (i = 0; i < RegExps.Length; i++) { match = RegExs[i].Match(line); if (match.Success) { // Console.WriteLine(line); segment = 0; address = 0; if (bIsWindowsMapfile) { switch ((WindowsSymbolTypes)i) { case WindowsSymbolTypes.ModuleNameClassNameFieldName: key = match.Groups["moduleName"].ToString() + "::" + match.Groups["className"].ToString() + "::" + match.Groups["fieldName"]; segment = Int32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); address = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); break; case WindowsSymbolTypes.ClassNameFieldName: key = match.Groups["className"].ToString() + "::" + match.Groups["fieldName"]; segment = Int32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); address = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); break; case WindowsSymbolTypes.GlobalVarName: case WindowsSymbolTypes.GlobalVarName2: case WindowsSymbolTypes.GlobalVarName3: key = match.Groups["globalVarName"].ToString(); segment = Int32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); address = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); break; case WindowsSymbolTypes.SingleVtAddr: key = match.Groups["FunctionName"].ToString(); segment = Int32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); address = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); break; case WindowsSymbolTypes.MultiVtAddr: key = match.Groups["FunctionName"].ToString() + "__" + match.Groups["BaseName"].ToString(); segment = Int32.Parse(match.Groups["addrPart1"].ToString(), NumberStyles.AllowHexSpecifier); address = UInt32.Parse(match.Groups["addrPart2"].ToString(), NumberStyles.AllowHexSpecifier); break; default: throw new ApplicationException("Unknown symbolType" + i); } } else { // We've got a UNIX nm file // The full unmanaged symbol name is already included in the RegEx // We could consider treating VTable's differently (a vt-specific key or different // hash), but we want to be consistent with the windows map case here. key = match.Groups["symName"].ToString(); address = UInt32.Parse(match.Groups["address"].ToString(), NumberStyles.AllowHexSpecifier); if (i == (int)UnixSymbolTypes.VtAddr) { // For VTables, what we really want is the vtAddr used at offset zero of objects. // GCC has the vtAddr point to the 3rd slot of the VTable (in contrast to MSVC where // the vtAddr points to the base of the VTable). // Slot 0 appears to typically be NULL // Slot 1 points to the run-time type info for the type // Slot 2 is the first virtual method // Fix up the symbol address here to match the value used in object headers. // Note that we don't know a lot about the target here (eg. what platform it's // running on), so it might be better to do this adjustment in DAC itself. But // for now doing it here is simpler and more reliable (only one place to update // to make it consistent). address += 2 * 4; // assumes 32-bit } } si = (SymbolInfo)SymbolHash[key]; if (si != null) { // Some duplicates are expected (eg. functions with overloads), but we should never // actually care about the address of such symbols. Record that this is a dup // so that we can warn/fail if we try to use it. si.dupFound = true; } else { si = new SymbolInfo(segment, address); // Console.WriteLine("{0:x8} {1}", si.Segment, si.Address, key); SymbolHash.Add(key, si); } } } } strm.Close(); } public SymbolInfo FindSymbol(String key) { SymbolInfo si = (SymbolInfo)SymbolHash[key]; if (si != null) { if (si.dupFound) { Console.WriteLine("Warning: Symbol " + key + " has duplicated entry in the symbol dump file."); } } return si; } bool bIsWindowsMapfile = false; String m_symdumpFile; Hashtable SymbolHash = new Hashtable(); ArrayList SegmentBase = new ArrayList(); }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Instructions.Reflection; using FlatRedBall.Instructions.Interpolation; namespace FlatRedBall.Instructions { #region GenericInstruction abstract class #region XML Docs /// <summary> /// Base class for typed Instructions. This type can be used /// to identify if an Instruction is a generic Instruction. /// </summary> #endregion public abstract class GenericInstruction : Instruction { /// <summary> /// Returns the FullName of the Type that this GenericInstruction operates on. /// </summary> public abstract string TypeAsString { get; } /// <summary> /// The Name of the member (such as "X" or "Width") that this instruction modifies. /// </summary> public abstract string Member { get; internal set; } /// <summary> /// /// </summary> public abstract Type MemberType { get; } /// <summary> /// The FullName of the type of the Member that is being modified. For example, this would return "System.String" for a float member like X. /// </summary> public abstract string MemberTypeAsString { get; } /// <summary> /// Returns a ToString() representation of the member. /// </summary> public abstract string MemberValueAsString { get; } /// <summary> /// Returns the value of the member casted as an object. /// </summary> public abstract object MemberValueAsObject { get; set; } /// <summary> /// Sets the object which this instruction operates on. /// </summary> /// <param name="target">The object that this instruction operates on.</param> internal abstract void SetTarget(object target); public abstract void InterpolateBetweenAndExecute(GenericInstruction otherInstruction, float thisRatio); } #endregion /// <summary> /// Generic method of setting a particular variable at a given time. /// </summary> /// <typeparam name="TargetType">The type of object to operate on (ex. PositionedObject)</typeparam> /// <typeparam name="ValueType">The type of the value. For example, the X value in PositionedObject is float.</typeparam> public class Instruction<TargetType, ValueType> : GenericInstruction// where T:class { #region Fields private TargetType mTarget; private ValueType mValue; private string mMember; #endregion #region Properties public override object Target { get { return mTarget; } set { mTarget = (TargetType)value; } } public override string TypeAsString { get { return typeof(TargetType).FullName; } } public override string Member { get { return mMember; } internal set { mMember = value; } } public override Type MemberType { get{ return typeof(ValueType);} } public override string MemberTypeAsString { get { return typeof(ValueType).FullName; } } public override string MemberValueAsString { get { if (mValue != null) { if (mValue is bool) return mValue.ToString().ToLower(); else return mValue.ToString(); } else return "null"; } } public override object MemberValueAsObject { get { return mValue; } set { mValue = ((ValueType) value) ; } } public ValueType Value { get { return mValue; } set { mValue = value; } } #endregion #region Methods #region Constructors #region XML Docs /// <summary> /// Used when deserializing .istx files. Not to be called otherwise. /// </summary> #endregion public Instruction() { } /// <summary> /// To be used when inheriting from this class since you won't need the property's name /// </summary> /// <param name="targetObject">The object to operate on (ex. a PositionedObject)</param> /// <param name="value">The value to set to the property when the instruction is executed</param> /// <param name="timeToExecute">Absolute time to executing this instruction</param> protected Instruction(TargetType targetObject, ValueType value, double timeToExecute) : this(targetObject, null, value, timeToExecute) { } /// <param name="targetObject">The object to operate on (ex. a PositionedObject)</param> /// <param name="member">The name of the property to set</param> /// <param name="value">The value to set to the property when the instruction is executed</param> /// <param name="timeToExecute">Absolute time to executing this instruction</param> public Instruction(TargetType targetObject, string member, ValueType value, double timeToExecute) { mTarget = targetObject; mMember = member; mValue = value; mTimeToExecute = timeToExecute; } #endregion #region Public Methods /// <summary> /// Uses reflection to set the target object's property. /// </summary> /// <remarks>If you need more performance out of a section, you can simply /// inherit from this generic class and override the Execute method to avoid /// delegating the call to the late binder class.</remarks> public override void Execute() { LateBinder<TargetType>.Instance.SetValue(mTarget, mMember, mValue); } public override void ExecuteOn(object target) { if (target is TargetType) { LateBinder<TargetType>.Instance.SetProperty<ValueType>((TargetType)target, mMember, mValue); } else { throw new System.ArgumentException("The target passed to ExecuteOn is not " + typeof(TargetType).Name); } } public override void InterpolateBetweenAndExecute(GenericInstruction otherInstruction, float thisRatio) { IInterpolator<ValueType> interpolator = InstructionManager.GetInterpolator(mValue.GetType(), mMember) as IInterpolator<ValueType>; ValueType interpolatedValue = interpolator.Interpolate(mValue, ((ValueType)otherInstruction.MemberValueAsObject), thisRatio); LateBinder<TargetType>.Instance.SetProperty<ValueType>(mTarget, mMember, interpolatedValue); } internal override void SetTarget(object target) { mTarget = (TargetType)target; } public override string ToString() { return mMember + " = " + mValue + ", Time = " + mTimeToExecute; } #endregion #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Resources; using System.ComponentModel; using System.Globalization; using System.Text; using System.Threading; namespace System.Management.Automation { /// <summary> /// EventLogLogProvider is a class to implement Msh Provider interface using EventLog technology. /// /// EventLogLogProvider will be the provider to use if Monad is running in early windows releases /// from 2000 to 2003. /// /// EventLogLogProvider will be packaged in the same dll as Msh Log Engine since EventLog should /// always be available. /// /// </summary> internal class EventLogLogProvider : LogProvider { /// <summary> /// Constructor. /// </summary> /// <returns></returns> internal EventLogLogProvider(string shellId) { string source = SetupEventSource(shellId); _eventLog = new EventLog(); _eventLog.Source = source; _resourceManager = new ResourceManager("System.Management.Automation.resources.Logging", System.Reflection.Assembly.GetExecutingAssembly()); } internal string SetupEventSource(string shellId) { string source; // In case shellId == null, use the "Default" source. if (String.IsNullOrEmpty(shellId)) { source = "Default"; } else { int index = shellId.LastIndexOf('.'); if (index < 0) source = shellId; else source = shellId.Substring(index + 1); // There may be a situation where ShellId ends with a '.'. // In that case, use the default source. if (String.IsNullOrEmpty(source)) source = "Default"; } if (EventLog.SourceExists(source)) { return source; } string message = String.Format(Thread.CurrentThread.CurrentCulture, "Event source '{0}' is not registered", source); throw new InvalidOperationException(message); } /// <summary> /// This represent a handle to EventLog /// </summary> private EventLog _eventLog; private ResourceManager _resourceManager; #region Log Provider Api private const int EngineHealthCategoryId = 1; private const int CommandHealthCategoryId = 2; private const int ProviderHealthCategoryId = 3; private const int EngineLifecycleCategoryId = 4; private const int CommandLifecycleCategoryId = 5; private const int ProviderLifecycleCategoryId = 6; private const int SettingsCategoryId = 7; private const int PipelineExecutionDetailCategoryId = 8; /// <summary> /// Log engine health event /// </summary> /// <param name="logContext"></param> /// <param name="eventId"></param> /// <param name="exception"></param> /// <param name="additionalInfo"></param> internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary<String, String> additionalInfo) { Hashtable mapArgs = new Hashtable(); IContainsErrorRecord icer = exception as IContainsErrorRecord; if (null != icer && null != icer.ErrorRecord) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; if (icer.ErrorRecord.ErrorDetails != null) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; } else { mapArgs["ErrorMessage"] = exception.Message; } } else { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = ""; mapArgs["ErrorId"] = ""; mapArgs["ErrorMessage"] = exception.Message; } FillEventArgs(mapArgs, logContext); FillEventArgs(mapArgs, additionalInfo); EventInstance entry = new EventInstance(eventId, EngineHealthCategoryId); entry.EntryType = GetEventLogEntryType(logContext); string detail = GetEventDetail("EngineHealthContext", mapArgs); LogEvent(entry, mapArgs["ErrorMessage"], detail); } private static EventLogEntryType GetEventLogEntryType(LogContext logContext) { switch (logContext.Severity) { case "Critical": case "Error": return EventLogEntryType.Error; case "Warning": return EventLogEntryType.Warning; default: return EventLogEntryType.Information; } } /// <summary> /// Log engine lifecycle event /// </summary> /// <param name="logContext"></param> /// <param name="newState"></param> /// <param name="previousState"></param> internal override void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState) { int eventId = GetEngineLifecycleEventId(newState); if (eventId == _invalidEventId) return; Hashtable mapArgs = new Hashtable(); mapArgs["NewEngineState"] = newState.ToString(); mapArgs["PreviousEngineState"] = previousState.ToString(); FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, EngineLifecycleCategoryId); entry.EntryType = EventLogEntryType.Information; string detail = GetEventDetail("EngineLifecycleContext", mapArgs); LogEvent(entry, newState, previousState, detail); } private const int _baseEngineLifecycleEventId = 400; private const int _invalidEventId = -1; /// <summary> /// Get engine lifecycle event id based on engine state /// </summary> /// <param name="engineState"></param> /// <returns></returns> private static int GetEngineLifecycleEventId(EngineState engineState) { switch (engineState) { case EngineState.None: return _invalidEventId; case EngineState.Available: return _baseEngineLifecycleEventId; case EngineState.Degraded: return _baseEngineLifecycleEventId + 1; case EngineState.OutOfService: return _baseEngineLifecycleEventId + 2; case EngineState.Stopped: return _baseEngineLifecycleEventId + 3; } return _invalidEventId; } private const int _commandHealthEventId = 200; /// <summary> /// Provider interface function for logging command health event /// </summary> /// <param name="logContext"></param> /// <param name="exception"></param> /// internal override void LogCommandHealthEvent(LogContext logContext, Exception exception) { int eventId = _commandHealthEventId; Hashtable mapArgs = new Hashtable(); IContainsErrorRecord icer = exception as IContainsErrorRecord; if (null != icer && null != icer.ErrorRecord) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; if (icer.ErrorRecord.ErrorDetails != null) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; } else { mapArgs["ErrorMessage"] = exception.Message; } } else { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = ""; mapArgs["ErrorId"] = ""; mapArgs["ErrorMessage"] = exception.Message; } FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, CommandHealthCategoryId); entry.EntryType = GetEventLogEntryType(logContext); string detail = GetEventDetail("CommandHealthContext", mapArgs); LogEvent(entry, mapArgs["ErrorMessage"], detail); } /// <summary> /// Log command life cycle event. /// </summary> /// <param name="getLogContext"></param> /// <param name="newState"></param> internal override void LogCommandLifecycleEvent(Func<LogContext> getLogContext, CommandState newState) { LogContext logContext = getLogContext(); int eventId = GetCommandLifecycleEventId(newState); if (eventId == _invalidEventId) return; Hashtable mapArgs = new Hashtable(); mapArgs["NewCommandState"] = newState.ToString(); FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, CommandLifecycleCategoryId); entry.EntryType = EventLogEntryType.Information; string detail = GetEventDetail("CommandLifecycleContext", mapArgs); LogEvent(entry, logContext.CommandName, newState, detail); } private const int _baseCommandLifecycleEventId = 500; /// <summary> /// Get command lifecycle event id based on command state /// </summary> /// <param name="commandState"></param> /// <returns></returns> private static int GetCommandLifecycleEventId(CommandState commandState) { switch (commandState) { case CommandState.Started: return _baseCommandLifecycleEventId; case CommandState.Stopped: return _baseCommandLifecycleEventId + 1; case CommandState.Terminated: return _baseCommandLifecycleEventId + 2; } return _invalidEventId; } private const int _pipelineExecutionDetailEventId = 800; /// <summary> /// Log pipeline execution detail event. /// /// This may end of logging more than one event if the detail string is too long to be fit in 64K. /// </summary> /// <param name="logContext"></param> /// <param name="pipelineExecutionDetail"></param> internal override void LogPipelineExecutionDetailEvent(LogContext logContext, List<String> pipelineExecutionDetail) { List<String> details = GroupMessages(pipelineExecutionDetail); for (int i = 0; i < details.Count; i++) { LogPipelineExecutionDetailEvent(logContext, details[i], i + 1, details.Count); } } private const int MaxLength = 16000; private List<String> GroupMessages(List<String> messages) { List<String> result = new List<string>(); if (messages == null || messages.Count == 0) return result; StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.Count; i++) { if (sb.Length + messages[i].Length < MaxLength) { sb.AppendLine(messages[i]); continue; } result.Add(sb.ToString()); sb = new StringBuilder(); sb.AppendLine(messages[i]); } result.Add(sb.ToString()); return result; } /// <summary> /// Log one pipeline execution detail event. Detail message is already chopped up so that it will /// fit in 64K. /// </summary> /// <param name="logContext"></param> /// <param name="pipelineExecutionDetail"></param> /// <param name="detailSequence"></param> /// <param name="detailTotal"></param> private void LogPipelineExecutionDetailEvent(LogContext logContext, String pipelineExecutionDetail, int detailSequence, int detailTotal) { int eventId = _pipelineExecutionDetailEventId; Hashtable mapArgs = new Hashtable(); mapArgs["PipelineExecutionDetail"] = pipelineExecutionDetail; mapArgs["DetailSequence"] = detailSequence; mapArgs["DetailTotal"] = detailTotal; FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, PipelineExecutionDetailCategoryId); entry.EntryType = EventLogEntryType.Information; string pipelineInfo = GetEventDetail("PipelineExecutionDetailContext", mapArgs); LogEvent(entry, logContext.CommandLine, pipelineInfo, pipelineExecutionDetail); } private const int _providerHealthEventId = 300; /// <summary> /// Provider interface function for logging provider health event /// </summary> /// <param name="logContext"></param> /// <param name="providerName"></param> /// <param name="exception"></param> /// internal override void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception) { int eventId = _providerHealthEventId; Hashtable mapArgs = new Hashtable(); mapArgs["ProviderName"] = providerName; IContainsErrorRecord icer = exception as IContainsErrorRecord; if (null != icer && null != icer.ErrorRecord) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; if (icer.ErrorRecord.ErrorDetails != null && !String.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message)) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; } else { mapArgs["ErrorMessage"] = exception.Message; } } else { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = ""; mapArgs["ErrorId"] = ""; mapArgs["ErrorMessage"] = exception.Message; } FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, ProviderHealthCategoryId); entry.EntryType = GetEventLogEntryType(logContext); string detail = GetEventDetail("ProviderHealthContext", mapArgs); LogEvent(entry, mapArgs["ErrorMessage"], detail); } /// <summary> /// Log provider lifecycle event. /// </summary> /// <param name="logContext"></param> /// <param name="providerName"></param> /// <param name="newState"></param> internal override void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState) { int eventId = GetProviderLifecycleEventId(newState); if (eventId == _invalidEventId) return; Hashtable mapArgs = new Hashtable(); mapArgs["ProviderName"] = providerName; mapArgs["NewProviderState"] = newState.ToString(); FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, ProviderLifecycleCategoryId); entry.EntryType = EventLogEntryType.Information; string detail = GetEventDetail("ProviderLifecycleContext", mapArgs); LogEvent(entry, providerName, newState, detail); } private const int _baseProviderLifecycleEventId = 600; /// <summary> /// Get provider lifecycle event id based on provider state. /// </summary> /// <param name="providerState"></param> /// <returns></returns> private static int GetProviderLifecycleEventId(ProviderState providerState) { switch (providerState) { case ProviderState.Started: return _baseProviderLifecycleEventId; case ProviderState.Stopped: return _baseProviderLifecycleEventId + 1; } return _invalidEventId; } private const int _settingsEventId = 700; /// <summary> /// Log settings event. /// </summary> /// <param name="logContext"></param> /// <param name="variableName"></param> /// <param name="value"></param> /// <param name="previousValue"></param> internal override void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue) { int eventId = _settingsEventId; Hashtable mapArgs = new Hashtable(); mapArgs["VariableName"] = variableName; mapArgs["NewValue"] = value; mapArgs["PreviousValue"] = previousValue; FillEventArgs(mapArgs, logContext); EventInstance entry = new EventInstance(eventId, SettingsCategoryId); entry.EntryType = EventLogEntryType.Information; string detail = GetEventDetail("SettingsContext", mapArgs); LogEvent(entry, variableName, value, previousValue, detail); } #endregion Log Provider Api #region EventLog helper functions /// <summary> /// This is the helper function for logging an event with localizable message /// to event log. It will trace all exception thrown by eventlog. /// </summary> /// <param name="entry"></param> /// <param name="args"></param> private void LogEvent(EventInstance entry, params object[] args) { try { _eventLog.WriteEvent(entry, args); } catch (ArgumentException) { return; } catch (InvalidOperationException) { return; } catch (Win32Exception) { return; } } #endregion #region Event Arguments /// <summary> /// Fill event arguments with logContext info. /// /// In EventLog Api, arguments are passed in as an array of objects. /// </summary> /// <param name="mapArgs">An ArrayList to contain the event arguments</param> /// <param name="logContext">The log context containing the info to fill in</param> private static void FillEventArgs(Hashtable mapArgs, LogContext logContext) { mapArgs["Severity"] = logContext.Severity; mapArgs["SequenceNumber"] = logContext.SequenceNumber; mapArgs["HostName"] = logContext.HostName; mapArgs["HostVersion"] = logContext.HostVersion; mapArgs["HostId"] = logContext.HostId; mapArgs["HostApplication"] = logContext.HostApplication; mapArgs["EngineVersion"] = logContext.EngineVersion; mapArgs["RunspaceId"] = logContext.RunspaceId; mapArgs["PipelineId"] = logContext.PipelineId; mapArgs["CommandName"] = logContext.CommandName; mapArgs["CommandType"] = logContext.CommandType; mapArgs["ScriptName"] = logContext.ScriptName; mapArgs["CommandPath"] = logContext.CommandPath; mapArgs["CommandLine"] = logContext.CommandLine; mapArgs["User"] = logContext.User; mapArgs["Time"] = logContext.Time; } /// <summary> /// Fill event arguments with additionalInfo stored in a string dictionary. /// </summary> /// <param name="mapArgs">An arraylist to contain the event arguments</param> /// <param name="additionalInfo">A string dictionary to fill in</param> private static void FillEventArgs(Hashtable mapArgs, Dictionary<String, String> additionalInfo) { if (additionalInfo == null) { for (int i = 0; i < 3; i++) { string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture); mapArgs["AdditionalInfo_Name" + id] = ""; mapArgs["AdditionalInfo_Value" + id] = ""; } return; } string[] keys = new string[additionalInfo.Count]; string[] values = new string[additionalInfo.Count]; additionalInfo.Keys.CopyTo(keys, 0); additionalInfo.Values.CopyTo(values, 0); for (int i = 0; i < 3; i++) { string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture); if (i < keys.Length) { mapArgs["AdditionalInfo_Name" + id] = keys[i]; mapArgs["AdditionalInfo_Value" + id] = values[i]; } else { mapArgs["AdditionalInfo_Name" + id] = ""; mapArgs["AdditionalInfo_Value" + id] = ""; } } return; } #endregion Event Arguments #region Event Message private string GetEventDetail(string contextId, Hashtable mapArgs) { return GetMessage(contextId, mapArgs); } private string GetMessage(string messageId, Hashtable mapArgs) { if (_resourceManager == null) return ""; string messageTemplate = _resourceManager.GetString(messageId); if (String.IsNullOrEmpty(messageTemplate)) return ""; return FillMessageTemplate(messageTemplate, mapArgs); } private static string FillMessageTemplate(string messageTemplate, Hashtable mapArgs) { StringBuilder message = new StringBuilder(); int cursor = 0; while (true) { int startIndex = messageTemplate.IndexOf('[', cursor); if (startIndex < 0) { message.Append(messageTemplate.Substring(cursor)); return message.ToString(); } int endIndex = messageTemplate.IndexOf(']', startIndex + 1); if (endIndex < 0) { message.Append(messageTemplate.Substring(cursor)); return message.ToString(); } message.Append(messageTemplate.Substring(cursor, startIndex - cursor)); cursor = startIndex; string placeHolder = messageTemplate.Substring(startIndex + 1, endIndex - startIndex - 1); if (mapArgs.Contains(placeHolder)) { message.Append(mapArgs[placeHolder]); cursor = endIndex + 1; } else { message.Append("["); cursor++; } } } #endregion Event Message } }
// 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 Microsoft.DotNet.RemoteExecutor; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.IO.Tests { public class Directory_CreateDirectory : FileSystemTest { public static TheoryData ReservedDeviceNames = IOInputs.GetReservedDeviceNames().ToTheoryData(); #region Utilities public virtual DirectoryInfo Create(string path) { return Directory.CreateDirectory(path); } public virtual bool IsDirectoryCreate => true; #endregion #region UniversalTests [Fact] public void FileNameIsToString_NotFullPath() { // We're checking that we're maintaining the original path RemoteExecutor.Invoke(() => { Environment.CurrentDirectory = TestDirectory; string subdir = Path.GetRandomFileName(); DirectoryInfo info = Create(subdir); Assert.Equal(subdir, info.ToString()); }).Dispose(); } [Fact] public void FileNameIsToString_FullPath() { string subdir = Path.GetRandomFileName(); string fullPath = Path.Combine(TestDirectory, subdir); DirectoryInfo info = Create(fullPath); Assert.Equal(fullPath, info.ToString()); } [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_Core(string invalidPath) { if (invalidPath.Contains('\0')) Assert.Throws<ArgumentException>("path", () => Create(invalidPath)); else Assert.Throws<IOException>(() => 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; } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // Can't read root in appcontainer public void RootPath_AppContainer() { string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory()); Assert.Throws<DirectoryNotFoundException>(() => Create(dirName)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't read root in appcontainer 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); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(ValidPathComponentNames))] [PlatformSpecific(TestPlatforms.Windows)] // trailing slash public void ValidExtendedPathWithTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithoutTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); 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_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Theory, MemberData(nameof(PathsWithComponentLongerThanMaxComponent))] public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsException(string path) { AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException, PathTooLongException>(() => Create(path)); } #endregion #region PlatformSpecific [Theory, MemberData(nameof(PathsWithInvalidColons))] [PlatformSpecific(TestPlatforms.Windows)] public void PathsWithInvalidColons_ThrowIOException_Core(string invalidPath) { // You can't actually create a directory with a colon in it. It was a preemptive // check, now we let the OS give us failures on usage. Assert.ThrowsAny<IOException>(() => Create(invalidPath)); } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [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))] [PlatformSpecific(TestPlatforms.Windows)] public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, path => AssertExtensions.ThrowsAny<PathTooLongException, DirectoryNotFoundException>(() => Create(path))); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] [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))] [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()); string path = IOServices.GetPath(testDir.FullName, 257); DirectoryInfo result = Create(path); Assert.Equal(path, 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)); } } [Theory, MemberData(nameof(SimpleWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] public void WindowsSimpleWhiteSpaceAsPath_ThrowsArgumentException(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Theory, MemberData(nameof(ControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] public void WindowsWhiteSpaceAsPath_ThrowsIOException_Core(string path) { Assert.Throws<IOException>(() => Create(path)); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed public void UnixWhiteSpaceAsPath_Allowed(string path) { Create(Path.Combine(TestDirectory, path)); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); } [Theory, MemberData(nameof(NonControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows public void TrailingWhiteSpace_NotTrimmed(string component) { // In CoreFX we don't trim anything other than space (' ') DirectoryInfo testDir = Create(GetTestFilePath() + component); string path = IOServices.RemoveTrailingSlash(testDir.FullName); DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [Theory, MemberData(nameof(SimpleWhiteSpace))] //*Just Spaces* [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows public void TrailingSpace_NotTrimmed(string component) { DirectoryInfo testDir = Create(GetTestFilePath()); 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)); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(SimpleWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace public void WindowsExtendedSyntaxWhiteSpace(string path) { string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath), extendedPath); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix public void UnixNonSignificantTrailingWhiteSpace(string component) { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Create(GetTestFilePath()); 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)); } [Theory, MemberData(nameof(PathsWithColons))] [PlatformSpecific(TestPlatforms.Windows)] // alternate data streams public void PathWithColons_ThrowsIOException_Core(string path) { if (PlatformDetection.IsInAppContainer) { AssertExtensions.ThrowsAny<DirectoryNotFoundException, IOException, UnauthorizedAccessException>(() => Create(Path.Combine(TestDirectory, path))); } else { Assert.ThrowsAny<IOException>(() => Create(Path.Combine(TestDirectory, path))); } } [Theory, MemberData(nameof(PathsWithReservedDeviceNames))] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException(string path) { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path Assert.Throws<DirectoryNotFoundException>(() => Create(path)); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(ReservedDeviceNames))] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsExtendedPath(string path) { Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path); } [Theory, MemberData(nameof(UncPathsWithoutShareName))] [PlatformSpecific(TestPlatforms.Windows)] public void UncPathWithoutShareNameAsPath_ThrowsIOException_Core(string path) { Assert.ThrowsAny<IOException>(() => Create(path)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void UNCPathWithOnlySlashes_Core() { Assert.ThrowsAny<IOException>(() => Create("//")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // drive labels 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 } }
/* * 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 OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.CoreModules.Framework.InterfaceCommander { /// <summary> /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s. /// Used for console commands and script API generation /// </summary> public class Command : ICommand { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<CommandArgument> m_args = new List<CommandArgument>(); private Action<object[]> m_command; private string m_help; private string m_name; private CommandIntentions m_intentions; //A permission type system could implement this and know what a command intends on doing. public Command(string name, CommandIntentions intention, Action<Object[]> command, string help) { m_name = name; m_command = command; m_help = help; m_intentions = intention; } #region ICommand Members public void AddArgument(string name, string helptext, string type) { m_args.Add(new CommandArgument(name, helptext, type)); } public string Name { get { return m_name; } } public CommandIntentions Intentions { get { return m_intentions; } } public string Help { get { return m_help; } } public Dictionary<string, string> Arguments { get { Dictionary<string, string> tmp = new Dictionary<string, string>(); foreach (CommandArgument arg in m_args) { tmp.Add(arg.Name, arg.ArgumentType); } return tmp; } } public string ShortHelp() { string help = m_name; foreach (CommandArgument arg in m_args) { help += " <" + arg.Name + ">"; } return help; } public void ShowConsoleHelp() { Console.WriteLine("== " + Name + " =="); Console.WriteLine(m_help); Console.WriteLine("= Parameters ="); foreach (CommandArgument arg in m_args) { Console.WriteLine("* " + arg.Name + " (" + arg.ArgumentType + ")"); Console.WriteLine("\t" + arg.HelpText); } } public void Run(Object[] args) { Object[] cleanArgs = new Object[m_args.Count]; if (args.Length < cleanArgs.Length) { Console.WriteLine("ERROR: Missing " + (cleanArgs.Length - args.Length) + " argument(s)"); ShowConsoleHelp(); return; } if (args.Length > cleanArgs.Length) { Console.WriteLine("ERROR: Too many arguments for this command. Type '<module> <command> help' for help."); return; } int i = 0; foreach (Object arg in args) { if (string.IsNullOrEmpty(arg.ToString())) { Console.WriteLine("ERROR: Empty arguments are not allowed"); return; } try { switch (m_args[i].ArgumentType) { case "String": m_args[i].ArgumentValue = arg.ToString(); break; case "Integer": m_args[i].ArgumentValue = Int32.Parse(arg.ToString()); break; case "Double": m_args[i].ArgumentValue = Double.Parse(arg.ToString(), OpenSim.Framework.Culture.NumberFormatInfo); break; case "Boolean": m_args[i].ArgumentValue = Boolean.Parse(arg.ToString()); break; default: Console.WriteLine("ERROR: Unknown desired type for argument " + m_args[i].Name + " on command " + m_name); break; } } catch (FormatException) { Console.WriteLine("ERROR: Argument number " + (i + 1) + " (" + m_args[i].Name + ") must be a valid " + m_args[i].ArgumentType.ToLower() + "."); return; } cleanArgs[i] = m_args[i].ArgumentValue; i++; } m_command.Invoke(cleanArgs); } #endregion } /// <summary> /// A single command argument, contains name, type and at runtime, value. /// </summary> public class CommandArgument { private string m_help; private string m_name; private string m_type; private Object m_val; public CommandArgument(string name, string help, string type) { m_name = name; m_help = help; m_type = type; } public string Name { get { return m_name; } } public string HelpText { get { return m_help; } } public string ArgumentType { get { return m_type; } } public Object ArgumentValue { get { return m_val; } set { m_val = value; } } } }
using System; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; using UnityWeld.Binding; using UnityWeld.Binding.Internal; namespace UnityWeld_Editor { /// <summary> /// A base editor for Unity-Weld bindings. /// </summary> public class BaseBindingEditor : Editor { /// <summary> /// Sets the specified value and sets dirty to true if it doesn't match the old value. /// </summary> protected void UpdateProperty<TValue>(Action<TValue> setter, TValue oldValue, TValue newValue, string undoActionName) where TValue : class { if (newValue == oldValue) { return; } Undo.RecordObject(target, undoActionName); setter(newValue); InspectorUtils.MarkSceneDirty(((Component)target).gameObject); } /// <summary> /// Display the adapters popup menu. /// </summary> protected static void ShowAdapterMenu( GUIContent label, string[] adapterTypeNames, string curValue, Action<string> valueUpdated ) { var adapterMenu = new[] { "None" } .Concat(adapterTypeNames) .Select(typeName => new GUIContent(typeName)) .ToArray(); var curSelectionIndex = Array.IndexOf(adapterTypeNames, curValue) + 1; // +1 to account for 'None'. var newSelectionIndex = EditorGUILayout.Popup( label, curSelectionIndex, adapterMenu ); if (newSelectionIndex == curSelectionIndex) { return; } if (newSelectionIndex == 0) { valueUpdated(null); // No adapter selected. } else { valueUpdated(adapterTypeNames[newSelectionIndex - 1]); // -1 to account for 'None'. } } /// <summary> /// Display a popup menu for selecting a property from a view-model. /// </summary> protected void ShowViewModelPropertyMenu( GUIContent label, BindableMember<PropertyInfo>[] bindableProperties, Action<string> propertyValueSetter, string curPropertyValue, Func<PropertyInfo, bool> menuEnabled ) { InspectorUtils.DoPopup( new GUIContent(curPropertyValue), label, prop => string.Concat(prop.ViewModelType, "/", prop.MemberName, " : ", prop.Member.PropertyType.Name), prop => menuEnabled(prop.Member), prop => prop.ToString() == curPropertyValue, prop => { UpdateProperty( propertyValueSetter, curPropertyValue, prop.ToString(), "Set view-model property" ); }, bindableProperties .OrderBy(property => property.ViewModelTypeName) .ThenBy(property => property.MemberName) .ToArray() ); } /// <summary> /// Class used to wrap property infos /// </summary> private class OptionInfo { public OptionInfo(string menuName, BindableMember<PropertyInfo> property) { this.MenuName = menuName; this.Property = property; } public string MenuName { get; private set; } public BindableMember<PropertyInfo> Property { get; private set; } } /// <summary> /// The string used to show that no option is selected in the property menu. /// </summary> private static readonly string NoneOptionString = "None"; /// <summary> /// Display a popup menu for selecting a property from a view-model. /// </summary> protected void ShowViewModelPropertyMenuWithNone( GUIContent label, BindableMember<PropertyInfo>[] bindableProperties, Action<string> propertyValueSetter, string curPropertyValue, Func<PropertyInfo, bool> menuEnabled ) { var options = bindableProperties .Select(prop => new OptionInfo( string.Concat(prop.ViewModelType, "/", prop.MemberName, " : ", prop.Member.PropertyType.Name), prop )) .OrderBy(option => option.Property.ViewModelTypeName) .ThenBy(option => option.Property.MemberName); var noneOption = new OptionInfo(NoneOptionString, null); InspectorUtils.DoPopup( new GUIContent(string.IsNullOrEmpty(curPropertyValue) ? NoneOptionString : curPropertyValue), label, option => option.MenuName, option => option.MenuName == NoneOptionString ? true : menuEnabled(option.Property.Member), option => { if (option == noneOption) { return string.IsNullOrEmpty(curPropertyValue); } return option.ToString() == curPropertyValue; }, option => UpdateProperty( propertyValueSetter, curPropertyValue, option.Property == null ? string.Empty : option.ToString(), "Set view-model property" ), new[] { noneOption } .Concat(options) .ToArray() ); } /// <summary> /// Shows a dropdown for selecting a property in the UI to bind to. /// </summary> protected void ShowViewPropertyMenu( GUIContent label, BindableMember<PropertyInfo>[] properties, Action<string> propertyValueSetter, string curPropertyValue, out Type selectedPropertyType ) { var propertyNames = properties .Select(m => m.ToString()) .ToArray(); var selectedIndex = Array.IndexOf(propertyNames, curPropertyValue); var content = properties.Select(prop => new GUIContent(string.Concat( prop.ViewModelTypeName, "/", prop.MemberName, " : ", prop.Member.PropertyType.Name ))) .ToArray(); var newSelectedIndex = EditorGUILayout.Popup(label, selectedIndex, content); if (newSelectedIndex != selectedIndex) { var newSelectedProperty = properties[newSelectedIndex]; UpdateProperty( propertyValueSetter, curPropertyValue, newSelectedProperty.ToString(), "Set view property" ); selectedPropertyType = newSelectedProperty.Member.PropertyType; } else { if (selectedIndex < 0) { selectedPropertyType = null; return; } selectedPropertyType = properties[selectedIndex].Member.PropertyType; } } /// <summary> /// Show dropdown for selecting a UnityEvent to bind to. /// </summary> protected void ShowEventMenu( BindableEvent[] events, Action<string> propertyValueSetter, string curPropertyValue ) { var eventNames = events .Select(BindableEventToString) .ToArray(); var selectedIndex = Array.IndexOf(eventNames, curPropertyValue); var content = events .Select(evt => new GUIContent(evt.ComponentType.Name + "." + evt.Name)) .ToArray(); var newSelectedIndex = EditorGUILayout.Popup( new GUIContent("View event", "Event on the view to bind to."), selectedIndex, content ); if (newSelectedIndex == selectedIndex) { return; } var selectedEvent = events[newSelectedIndex]; UpdateProperty( propertyValueSetter, curPropertyValue, BindableEventToString(selectedEvent), "Set bound event" ); } /// <summary> /// Returns whether or not we should show an adapter options selector for the specified /// adapter type and finds the type for the specified type name. /// </summary> protected static bool ShouldShowAdapterOptions(string adapterTypeName, out Type adapterType) { // Don't show selector until an adapter has been selected. if (string.IsNullOrEmpty(adapterTypeName)) { adapterType = null; return false; } var adapterAttribute = FindAdapterAttribute(adapterTypeName); if (adapterAttribute == null) { adapterType = null; return false; } adapterType = adapterAttribute.OptionsType; // Don't show selector unless the current adapter has its own overridden // adapter options type. return adapterType != typeof(AdapterOptions); } /// <summary> /// Show a field for selecting an AdapterOptions object matching the specified type of adapter. /// </summary> protected void ShowAdapterOptionsMenu( string label, Type adapterOptionsType, Action<AdapterOptions> propertyValueSetter, AdapterOptions currentPropertyValue, float fadeAmount ) { if (EditorGUILayout.BeginFadeGroup(fadeAmount)) { EditorGUI.indentLevel++; var newAdapterOptions = (AdapterOptions)EditorGUILayout.ObjectField( label, currentPropertyValue, adapterOptionsType, false ); EditorGUI.indentLevel--; UpdateProperty( propertyValueSetter, currentPropertyValue, newAdapterOptions, "Set adapter options" ); } EditorGUILayout.EndFadeGroup(); } /// <summary> /// Displays helpbox in inspector if the editor is playing, and returns the same thing /// </summary> protected static bool CannotModifyInPlayMode() { if (EditorApplication.isPlaying) { EditorGUILayout.HelpBox("Exit play mode to make changes.", MessageType.Info); return true; } return false; } /// <summary> /// Find the adapter attribute for a named adapter type. /// </summary> protected static AdapterAttribute FindAdapterAttribute(string adapterName) { if (!string.IsNullOrEmpty(adapterName)) { var adapterType = TypeResolver.FindAdapterType(adapterName); if (adapterType != null) { return TypeResolver.FindAdapterAttribute(adapterType); } } return null; } /// <summary> /// Pass a type through an adapter and get the result. /// </summary> protected static Type AdaptTypeBackward(Type inputType, string adapterName) { var adapterAttribute = FindAdapterAttribute(adapterName); return adapterAttribute != null ? adapterAttribute.InputType : inputType; } /// <summary> /// Pass a type through an adapter and get the result. /// </summary> protected static Type AdaptTypeForward(Type inputType, string adapterName) { var adapterAttribute = FindAdapterAttribute(adapterName); return adapterAttribute != null ? adapterAttribute.OutputType : inputType; } /// <summary> /// Convert a BindableEvent to a uniquely identifiable string. /// </summary> private static string BindableEventToString(BindableEvent evt) { return string.Concat(evt.ComponentType.ToString(), ".", evt.Name); } /// <summary> /// Returns an array of all the names of adapter types that match the /// provided prediate function. /// </summary> protected static string[] GetAdapterTypeNames(Func<Type, bool> adapterSelectionPredicate) { return TypeResolver.TypesWithAdapterAttribute .Where(adapterSelectionPredicate) .Select(type => type.ToString()) .ToArray(); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { /// <summary> /// A revolute joint rains to bodies to share a common point while they /// are free to rotate about the point. The relative rotation about the shared /// point is the joint angle. You can limit the relative rotation with /// a joint limit that specifies a lower and upper angle. You can use a motor /// to drive the relative rotation about the shared point. A maximum motor torque /// is provided so that infinite forces are not generated. /// </summary> public class RevoluteJoint : Joint { public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; private bool _enableLimit; private bool _enableMotor; private Vector3 _impulse; private LimitState _limitState; private float _lowerAngle; private Mat33 _mass; // effective mass for point-to-point constraint. private float _maxMotorTorque; private float _motorImpulse; private float _motorMass; // effective mass for motor/limit angular constraint. private float _motorSpeed; private float _referenceAngle; private float _tmpFloat1; private Vector2 _tmpVector1, _tmpVector2; private float _upperAngle; internal RevoluteJoint() { JointType = JointType.Revolute; } /// <summary> /// Initialize the bodies and local anchor. /// This requires defining an /// anchor point where the bodies are joined. The definition /// uses local anchor points so that the initial configuration /// can violate the constraint slightly. You also need to /// specify the initial relative angle for joint limits. This /// helps when saving and loading a game. /// The local anchor points are measured from the body's origin /// rather than the center of mass because: /// 1. you might not know where the center of mass will be. /// 2. if you add/remove shapes from a body and recompute the mass, /// the joints will be broken. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="localAnchorA">The first body anchor.</param> /// <param name="localAnchorB">The second anchor.</param> public RevoluteJoint(Body bodyA, Body bodyB, Vector2 localAnchorA, Vector2 localAnchorB) : base(bodyA, bodyB) { JointType = JointType.Revolute; // Changed to local coordinates. LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; ReferenceAngle = BodyB.Rotation - BodyA.Rotation; _impulse = Vector3.Zero; _limitState = LimitState.Inactive; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public float ReferenceAngle { get { return _referenceAngle; } set { WakeBodies(); _referenceAngle = value; } } /// <summary> /// Get the current joint angle in radians. /// </summary> /// <value></value> public float JointAngle { get { return BodyB.Sweep.A - BodyA.Sweep.A - ReferenceAngle; } } /// <summary> /// Get the current joint angle speed in radians per second. /// </summary> /// <value></value> public float JointSpeed { get { return BodyB.AngularVelocityInternal - BodyA.AngularVelocityInternal; } } /// <summary> /// Is the joint limit enabled? /// </summary> /// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value> public bool LimitEnabled { get { return _enableLimit; } set { WakeBodies(); _enableLimit = value; } } /// <summary> /// Get the lower joint limit in radians. /// </summary> /// <value></value> public float LowerLimit { get { return _lowerAngle; } set { WakeBodies(); _lowerAngle = value; } } /// <summary> /// Get the upper joint limit in radians. /// </summary> /// <value></value> public float UpperLimit { get { return _upperAngle; } set { WakeBodies(); _upperAngle = value; } } /// <summary> /// Is the joint motor enabled? /// </summary> /// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value> public bool MotorEnabled { get { return _enableMotor; } set { WakeBodies(); _enableMotor = value; } } /// <summary> /// Set the motor speed in radians per second. /// </summary> /// <value>The speed.</value> public float MotorSpeed { set { WakeBodies(); _motorSpeed = value; } get { return _motorSpeed; } } /// <summary> /// Set the maximum motor torque, usually in N-m. /// </summary> /// <value>The torque.</value> public float MaxMotorTorque { set { WakeBodies(); _maxMotorTorque = value; } get { return _maxMotorTorque; } } /// <summary> /// Get the current motor torque, usually in N-m. /// </summary> /// <value></value> public float MotorTorque { get { return _motorImpulse; } set { WakeBodies(); _motorImpulse = value; } } public override Vector2 GetReactionForce(float inv_dt) { Vector2 P = new Vector2(_impulse.X, _impulse.Y); return inv_dt * P; } public override float GetReactionTorque(float inv_dt) { return inv_dt * _impulse.Z; } internal override void InitVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; if (_enableMotor || _enableLimit) { // You cannot create a rotation limit between bodies that // both have fixed rotation. Debug.Assert(b1.InvI > 0.0f || b2.InvI > 0.0f); } // Compute the effective mass matrix. /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ m1+r1y^2*i1+m2+r2y^2*i2, -r1y*i1*r1x-r2y*i2*r2x, -r1y*i1-r2y*i2] // [ -r1y*i1*r1x-r2y*i2*r2x, m1+r1x^2*i1+m2+r2x^2*i2, r1x*i1+r2x*i2] // [ -r1y*i1-r2y*i2, r1x*i1+r2x*i2, i1+i2] float m1 = b1.InvMass, m2 = b2.InvMass; float i1 = b1.InvI, i2 = b2.InvI; _mass.Col1.X = m1 + m2 + r1.Y * r1.Y * i1 + r2.Y * r2.Y * i2; _mass.Col2.X = -r1.Y * r1.X * i1 - r2.Y * r2.X * i2; _mass.Col3.X = -r1.Y * i1 - r2.Y * i2; _mass.Col1.Y = _mass.Col2.X; _mass.Col2.Y = m1 + m2 + r1.X * r1.X * i1 + r2.X * r2.X * i2; _mass.Col3.Y = r1.X * i1 + r2.X * i2; _mass.Col1.Z = _mass.Col3.X; _mass.Col2.Z = _mass.Col3.Y; _mass.Col3.Z = i1 + i2; _motorMass = i1 + i2; if (_motorMass > 0.0f) { _motorMass = 1.0f / _motorMass; } if (_enableMotor == false) { _motorImpulse = 0.0f; } if (_enableLimit) { float jointAngle = b2.Sweep.A - b1.Sweep.A - ReferenceAngle; if (Math.Abs(_upperAngle - _lowerAngle) < 2.0f * Settings.AngularSlop) { _limitState = LimitState.Equal; } else if (jointAngle <= _lowerAngle) { if (_limitState != LimitState.AtLower) { _impulse.Z = 0.0f; } _limitState = LimitState.AtLower; } else if (jointAngle >= _upperAngle) { if (_limitState != LimitState.AtUpper) { _impulse.Z = 0.0f; } _limitState = LimitState.AtUpper; } else { _limitState = LimitState.Inactive; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; } if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _impulse *= step.dtRatio; _motorImpulse *= step.dtRatio; Vector2 P = new Vector2(_impulse.X, _impulse.Y); b1.LinearVelocityInternal -= m1 * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); b1.AngularVelocityInternal -= i1 * ( /* r1 x P */_tmpFloat1 + _motorImpulse + _impulse.Z); b2.LinearVelocityInternal += m2 * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); b2.AngularVelocityInternal += i2 * ( /* r2 x P */_tmpFloat1 + _motorImpulse + _impulse.Z); } else { _impulse = Vector3.Zero; _motorImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; Vector2 v1 = b1.LinearVelocityInternal; float w1 = b1.AngularVelocityInternal; Vector2 v2 = b2.LinearVelocityInternal; float w2 = b2.AngularVelocityInternal; float m1 = b1.InvMass, m2 = b2.InvMass; float i1 = b1.InvI, i2 = b2.InvI; // Solve motor constraint. if (_enableMotor && _limitState != LimitState.Equal) { float Cdot = w2 - w1 - _motorSpeed; float impulse = _motorMass * (-Cdot); float oldImpulse = _motorImpulse; float maxImpulse = step.dt * _maxMotorTorque; _motorImpulse = MathHelper.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; w1 -= i1 * impulse; w2 += i2 * impulse; } // Solve limit constraint. if (_enableLimit && _limitState != LimitState.Inactive) { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); // Solve point-to-point constraint MathUtils.Cross(w2, ref r2, out _tmpVector2); MathUtils.Cross(w1, ref r1, out _tmpVector1); Vector2 Cdot1 = v2 + /* w2 x r2 */ _tmpVector2 - v1 - /* w1 x r1 */ _tmpVector1; float Cdot2 = w2 - w1; Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2); Vector3 impulse = _mass.Solve33(-Cdot); if (_limitState == LimitState.Equal) { _impulse += impulse; } else if (_limitState == LimitState.AtLower) { float newImpulse = _impulse.Z + impulse.Z; if (newImpulse < 0.0f) { Vector2 reduced = _mass.Solve22(-Cdot1); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } } else if (_limitState == LimitState.AtUpper) { float newImpulse = _impulse.Z + impulse.Z; if (newImpulse > 0.0f) { Vector2 reduced = _mass.Solve22(-Cdot1); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } } Vector2 P = new Vector2(impulse.X, impulse.Y); v1 -= m1 * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); w1 -= i1 * ( /* r1 x P */_tmpFloat1 + impulse.Z); v2 += m2 * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); w2 += i2 * ( /* r2 x P */_tmpFloat1 + impulse.Z); } else { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ _tmpVector1 = LocalAnchorA - b1.LocalCenter; _tmpVector2 = LocalAnchorB - b2.LocalCenter; Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, ref _tmpVector1); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, ref _tmpVector2); // Solve point-to-point constraint MathUtils.Cross(w2, ref r2, out _tmpVector2); MathUtils.Cross(w1, ref r1, out _tmpVector1); Vector2 Cdot = v2 + /* w2 x r2 */ _tmpVector2 - v1 - /* w1 x r1 */ _tmpVector1; Vector2 impulse = _mass.Solve22(-Cdot); _impulse.X += impulse.X; _impulse.Y += impulse.Y; v1 -= m1 * impulse; MathUtils.Cross(ref r1, ref impulse, out _tmpFloat1); w1 -= i1 * /* r1 x impulse */ _tmpFloat1; v2 += m2 * impulse; MathUtils.Cross(ref r2, ref impulse, out _tmpFloat1); w2 += i2 * /* r2 x impulse */ _tmpFloat1; } b1.LinearVelocityInternal = v1; b1.AngularVelocityInternal = w1; b2.LinearVelocityInternal = v2; b2.AngularVelocityInternal = w2; } internal override bool SolvePositionConstraints() { // TODO_ERIN block solve with limit. COME ON ERIN Body b1 = BodyA; Body b2 = BodyB; float angularError = 0.0f; float positionError; // Solve angular limit constraint. if (_enableLimit && _limitState != LimitState.Inactive) { float angle = b2.Sweep.A - b1.Sweep.A - ReferenceAngle; float limitImpulse = 0.0f; if (_limitState == LimitState.Equal) { // Prevent large angular corrections float C = MathHelper.Clamp(angle - _lowerAngle, -Settings.MaxAngularCorrection, Settings.MaxAngularCorrection); limitImpulse = -_motorMass * C; angularError = Math.Abs(C); } else if (_limitState == LimitState.AtLower) { float C = angle - _lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = MathHelper.Clamp(C + Settings.AngularSlop, -Settings.MaxAngularCorrection, 0.0f); limitImpulse = -_motorMass * C; } else if (_limitState == LimitState.AtUpper) { float C = angle - _upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = MathHelper.Clamp(C - Settings.AngularSlop, 0.0f, Settings.MaxAngularCorrection); limitImpulse = -_motorMass * C; } b1.Sweep.A -= b1.InvI * limitImpulse; b2.Sweep.A += b2.InvI * limitImpulse; b1.SynchronizeTransform(); b2.SynchronizeTransform(); } // Solve point-to-point constraint. { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); Vector2 C = b2.Sweep.C + r2 - b1.Sweep.C - r1; positionError = C.Length(); float invMass1 = b1.InvMass, invMass2 = b2.InvMass; float invI1 = b1.InvI, invI2 = b2.InvI; // Handle large detachment. const float k_allowedStretch = 10.0f * Settings.LinearSlop; if (C.LengthSquared() > k_allowedStretch * k_allowedStretch) { // Use a particle solution (no rotation). Vector2 u = C; u.Normalize(); float k = invMass1 + invMass2; Debug.Assert(k > Settings.Epsilon); float m = 1.0f / k; Vector2 impulse2 = m * (-C); const float k_beta = 0.5f; b1.Sweep.C -= k_beta * invMass1 * impulse2; b2.Sweep.C += k_beta * invMass2 * impulse2; C = b2.Sweep.C + r2 - b1.Sweep.C - r1; } Mat22 K1 = new Mat22(new Vector2(invMass1 + invMass2, 0.0f), new Vector2(0.0f, invMass1 + invMass2)); Mat22 K2 = new Mat22(new Vector2(invI1 * r1.Y * r1.Y, -invI1 * r1.X * r1.Y), new Vector2(-invI1 * r1.X * r1.Y, invI1 * r1.X * r1.X)); Mat22 K3 = new Mat22(new Vector2(invI2 * r2.Y * r2.Y, -invI2 * r2.X * r2.Y), new Vector2(-invI2 * r2.X * r2.Y, invI2 * r2.X * r2.X)); Mat22 Ka; Mat22.Add(ref K1, ref K2, out Ka); Mat22 K; Mat22.Add(ref Ka, ref K3, out K); Vector2 impulse = K.Solve(-C); b1.Sweep.C -= b1.InvMass * impulse; MathUtils.Cross(ref r1, ref impulse, out _tmpFloat1); b1.Sweep.A -= b1.InvI * /* r1 x impulse */ _tmpFloat1; b2.Sweep.C += b2.InvMass * impulse; MathUtils.Cross(ref r2, ref impulse, out _tmpFloat1); b2.Sweep.A += b2.InvI * /* r2 x impulse */ _tmpFloat1; b1.SynchronizeTransform(); b2.SynchronizeTransform(); } return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop; } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace NetGore.Tests.NetGore { [TestFixture] public class IEnumerableTests { static readonly SafeRandom rnd = new SafeRandom(); #region Unit tests [Test] public void ContainsSameElementsTest01() { var a = new int[] { }; var b = new int[] { }; Assert.IsTrue(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest02() { var a = new int[] { 0 }; var b = new int[] { }; Assert.IsFalse(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest03() { var a = new int[] { }; var b = new int[] { 0 }; Assert.IsFalse(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest04() { var a = new int[] { 0 }; var b = new int[] { 0 }; Assert.IsTrue(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest05() { var a = new int[] { 4, 3, 2, 1 }; var b = new int[] { 1, 3, 2, 4 }; Assert.IsTrue(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest06() { var a = new int[] { 4, 3, 2, 1, 4 }; var b = new int[] { 1, 3, 2, 4 }; Assert.IsFalse(a.ContainSameElements(b)); } [Test] public void ContainsSameElementsTest07() { var a = new int[] { 4, 4, 3, 3 }; var b = new int[] { 4, 4, 4, 3 }; Assert.IsFalse(a.ContainSameElements(b)); } [Test] public void HasDuplicatesTest01() { var a = new int[] { 0, 1, 2, 3 }; Assert.IsFalse(a.HasDuplicates()); } [Test] public void HasDuplicatesTest02() { var a = new int[] { 0 }; Assert.IsFalse(a.HasDuplicates()); } [Test] public void HasDuplicatesTest03() { var a = new int[] { 0, 0 }; Assert.IsTrue(a.HasDuplicates()); } [Test] public void HasDuplicatesTest04() { var a = new int[] { 0, 0, 1 }; Assert.IsTrue(a.HasDuplicates()); } [Test] public void HasDuplicatesTest05() { var a = new int[] { 0, 1, 2, 0 }; Assert.IsTrue(a.HasDuplicates()); } [Test] public void HasDuplicatesTest06() { var a = new int[] { 0, 1, 2, 0, 2, 2 }; Assert.IsTrue(a.HasDuplicates()); } [Test] public void ImplodeSplitWithCharTest() { var l = new List<int>(50); for (var i = 0; i < 50; i++) { l.Add(rnd.Next(0, 100)); } var implode = l.Implode(','); var elements = implode.Split(','); Assert.AreEqual(l.Count, elements.Length); for (var i = 0; i < l.Count; i++) { Assert.AreEqual(l[i].ToString(), elements[i]); } } [Test] public void ImplodeSplitWithStringTest() { var l = new List<int>(50); for (var i = 0; i < 50; i++) { l.Add(rnd.Next(0, 100)); } var implode = l.Implode(","); var elements = implode.Split(','); Assert.AreEqual(l.Count, elements.Length); for (var i = 0; i < l.Count; i++) { Assert.AreEqual(l[i].ToString(), elements[i]); } } [Test] public void ImplodeStringsSplitWithCharTest() { var l = new List<string>(50); for (var i = 0; i < 50; i++) { l.Add(Parser.Current.ToString(rnd.Next(0, 100))); } var implode = l.Implode(','); var elements = implode.Split(','); Assert.AreEqual(l.Count, elements.Length); for (var i = 0; i < l.Count; i++) { Assert.AreEqual(l[i], elements[i]); } } [Test] public void ImplodeStringsSplitWithStringTest() { var l = new List<string>(50); for (var i = 0; i < 50; i++) { l.Add(Parser.Current.ToString(rnd.Next(0, 100))); } var implode = l.Implode(","); var elements = implode.Split(','); Assert.AreEqual(l.Count, elements.Length); for (var i = 0; i < l.Count; i++) { Assert.AreEqual(l[i], elements[i]); } } [Test] public void IsEmptyOnEmptyCollectionsTest() { Assert.IsTrue(new List<int>().IsEmpty()); Assert.IsTrue(new int[0].IsEmpty()); Assert.IsTrue(string.Empty.IsEmpty()); Assert.IsTrue(new Dictionary<int, int>().IsEmpty()); Assert.IsTrue(new HashSet<int>().IsEmpty()); Assert.IsTrue(new Stack<int>().IsEmpty()); Assert.IsTrue(new Queue<int>().IsEmpty()); } [Test] public void IsEmptyOnNonEmptyCollectionsTest() { Assert.IsFalse(new List<int> { 1, 2, 3 }.IsEmpty()); Assert.IsFalse(new int[] { 1, 2, 3 }.IsEmpty()); Assert.IsFalse("asdlkfjasldkfj".IsEmpty()); Assert.IsFalse(new Dictionary<int, int> { { 5, 1 }, { 3, 4 } }.IsEmpty()); Assert.IsFalse(new HashSet<int> { 1, 2, 3, 4, 5 }.IsEmpty()); } [Test] public void IsEmptyOnNullTest() { const List<int> l = null; Assert.IsTrue(l.IsEmpty()); } [Test] public void MaxElementEmptyTest() { var s = new string[0]; Assert.Throws<ArgumentException>(() => s.MaxElement(x => x.Length)); Assert.IsNull(s.MaxElementOrDefault(x => x.Length)); } [Test] public void MaxElementTest() { var s = new string[] { "asdf", "f", "asfkdljas", "sdf" }; var r = s.MaxElement(x => x.Length); Assert.AreEqual("asfkdljas", r); } [Test] public void MinElementEmptyTest() { var s = new string[0]; Assert.Throws<ArgumentException>(() => s.MinElement(x => x.Length)); Assert.IsNull(s.MinElementOrDefault(x => x.Length)); } [Test] public void MinElementTest() { var s = new string[] { "asdf", "f", "asfkdljas", "sdf" }; var r = s.MinElement(x => x.Length); Assert.AreEqual("f", r); } [Test] public void NextFreeValueEmptyTestA() { var values = new int[0]; Assert.AreEqual(0, values.NextFreeValue()); } [Test] public void NextFreeValueEmptyTestB() { var values = new int[0]; Assert.AreEqual(10, values.NextFreeValue(10)); } [Test] public void NextFreeValueTestA() { var values = new int[] { 0, 1, 2, 3, 4, 5, 6 }; Assert.AreEqual(7, values.NextFreeValue()); } [Test] public void NextFreeValueTestB() { var values = new int[] { 1, 2, 3, 4, 5, 6 }; Assert.AreEqual(0, values.NextFreeValue()); } [Test] public void NextFreeValueTestC() { var values = new int[] { 1, 2, 3, 4, 5, 6 }; Assert.AreEqual(7, values.NextFreeValue(1)); } [Test] public void NextFreeValueTestD() { var values = new int[] { 1, 2, 3, 4, 5, 6 }; Assert.AreEqual(10, values.NextFreeValue(10)); } [Test] public void NextFreeValueTestE() { var values = new int[] { 0, 1, 2, 3, 4, 5, 6 }; Assert.AreEqual(-10, values.NextFreeValue(-10)); } [Test] public void NextFreeValueTestF() { var values = new int[] { 0, 1, 2, 4, 5, 6 }; Assert.AreEqual(3, values.NextFreeValue()); } [Test] public void NextFreeValueTestG() { var values = new int[] { 0, 1, 2, 4, 6 }; Assert.AreEqual(3, values.NextFreeValue()); } [Test] public void NextFreeValueTestH() { var values = new int[] { 0, 1, 2, 3, 4, 5 }; Assert.AreEqual(6, values.NextFreeValue()); } [Test] public void NextFreeValueTestI() { var values = new int[] { 0, 0, 0, 0, 1, 1, 1, 2, 5, 6 }; Assert.AreEqual(3, values.NextFreeValue()); } [Test] public void NextFreeValueTestJ() { var values = new int[] { 0, 0, 0, 2 }; Assert.AreEqual(1, values.NextFreeValue()); } [Test] public void NextFreeValueTestK() { var values = new int[] { 0, 1, 1, 1, 3, 3, 3 }; Assert.AreEqual(2, values.NextFreeValue()); } [Test] public void NextFreeValueTestL() { var values = new int[] { 0, 1, 1, 1, 3 }; Assert.AreEqual(2, values.NextFreeValue()); } [Test] public void NextFreeValueTestM() { var values = new int[] { 0, 1, 1, 1 }; Assert.AreEqual(2, values.NextFreeValue()); } [Test] public void NextFreeValueTestN() { var values = new int[] { 5, 4, 3, 2, 1, 0 }; Assert.AreEqual(6, values.NextFreeValue()); } [Test] public void ToImmutableTest() { var i = new List<int> { 1, 2, 3 }; var e = i.ToImmutable(); i[0] = 50; Assert.AreEqual(1, e.ToArray()[0]); Assert.AreEqual(2, e.ToArray()[1]); Assert.AreEqual(3, e.ToArray()[2]); Assert.AreEqual(50, i[0]); i[2] = 22; Assert.AreEqual(1, e.ToArray()[0]); Assert.AreEqual(2, e.ToArray()[1]); Assert.AreEqual(3, e.ToArray()[2]); Assert.AreEqual(22, i[2]); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Luis.MasteringExtJs.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Drawing.Internal; using System.Globalization; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing.Drawing2D { public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable { internal IntPtr _nativePath; public GraphicsPath() : this(FillMode.Alternate) { } public GraphicsPath(FillMode fillMode) { Gdip.CheckStatus(Gdip.GdipCreatePath(unchecked((int)fillMode), out IntPtr nativePath)); _nativePath = nativePath; } public GraphicsPath(PointF[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } public unsafe GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode) { if (pts == null) throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw Gdip.StatusException(Gdip.InvalidParameter); fixed (PointF* p = pts) fixed (byte* t = types) { Gdip.CheckStatus(Gdip.GdipCreatePath2( p, t, types.Length, (int)fillMode, out IntPtr nativePath)); _nativePath = nativePath; } } public GraphicsPath(Point[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } public unsafe GraphicsPath(Point[] pts, byte[] types, FillMode fillMode) { if (pts == null) throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw Gdip.StatusException(Gdip.InvalidParameter); fixed (byte* t = types) fixed (Point* p = pts) { Gdip.CheckStatus(Gdip.GdipCreatePath2I( p, t, types.Length, unchecked((int)fillMode), out IntPtr nativePath)); _nativePath = nativePath; } } public object Clone() { Gdip.CheckStatus(Gdip.GdipClonePath(new HandleRef(this, _nativePath), out IntPtr clonedPath)); return new GraphicsPath(clonedPath, 0); } private GraphicsPath(IntPtr nativePath, int extra) { if (nativePath == IntPtr.Zero) throw new ArgumentNullException(nameof(nativePath)); _nativePath = nativePath; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (_nativePath != IntPtr.Zero) { try { #if DEBUG int status = #endif Gdip.GdipDeletePath(new HandleRef(this, _nativePath)); #if DEBUG Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during Dispose: " + ex.ToString()); } finally { _nativePath = IntPtr.Zero; } } } ~GraphicsPath() => Dispose(false); public void Reset() { Gdip.CheckStatus(Gdip.GdipResetPath(new HandleRef(this, _nativePath))); } public FillMode FillMode { get { Gdip.CheckStatus(Gdip.GdipGetPathFillMode(new HandleRef(this, _nativePath), out FillMode fillmode)); return fillmode; } set { if (value < FillMode.Alternate || value > FillMode.Winding) throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(FillMode)); Gdip.CheckStatus(Gdip.GdipSetPathFillMode(new HandleRef(this, _nativePath), value)); } } private unsafe PathData _GetPathData() { int count = PointCount; PathData pathData = new PathData() { Types = new byte[count], Points = new PointF[count] }; if (count == 0) return pathData; fixed (byte* t = pathData.Types) fixed (PointF* p = pathData.Points) { GpPathData data = new GpPathData { Count = count, Points = p, Types = t }; Gdip.CheckStatus(Gdip.GdipGetPathData(new HandleRef(this, _nativePath), &data)); } return pathData; } public PathData PathData => _GetPathData(); public void StartFigure() { Gdip.CheckStatus(Gdip.GdipStartPathFigure(new HandleRef(this, _nativePath))); } public void CloseFigure() { Gdip.CheckStatus(Gdip.GdipClosePathFigure(new HandleRef(this, _nativePath))); } public void CloseAllFigures() { Gdip.CheckStatus(Gdip.GdipClosePathFigures(new HandleRef(this, _nativePath))); } public void SetMarkers() { Gdip.CheckStatus(Gdip.GdipSetPathMarker(new HandleRef(this, _nativePath))); } public void ClearMarkers() { Gdip.CheckStatus(Gdip.GdipClearPathMarkers(new HandleRef(this, _nativePath))); } public void Reverse() { Gdip.CheckStatus(Gdip.GdipReversePath(new HandleRef(this, _nativePath))); } public PointF GetLastPoint() { Gdip.CheckStatus(Gdip.GdipGetPathLastPoint(new HandleRef(this, _nativePath), out PointF point)); return point; } public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y), null); public bool IsVisible(PointF point) => IsVisible(point, null); public bool IsVisible(float x, float y, Graphics graphics) => IsVisible(new PointF(x, y), graphics); public bool IsVisible(PointF pt, Graphics graphics) { Gdip.CheckStatus(Gdip.GdipIsVisiblePathPoint( new HandleRef(this, _nativePath), pt.X, pt.Y, new HandleRef(graphics, graphics?.NativeGraphics ?? IntPtr.Zero), out bool isVisible)); return isVisible; } public bool IsVisible(int x, int y) => IsVisible(new Point(x, y), null); public bool IsVisible(Point point) => IsVisible(point, null); public bool IsVisible(int x, int y, Graphics graphics) => IsVisible(new Point(x, y), graphics); public bool IsVisible(Point pt, Graphics graphics) { Gdip.CheckStatus(Gdip.GdipIsVisiblePathPointI( new HandleRef(this, _nativePath), pt.X, pt.Y, new HandleRef(graphics, graphics?.NativeGraphics ?? IntPtr.Zero), out bool isVisible)); return isVisible; } public bool IsOutlineVisible(float x, float y, Pen pen) => IsOutlineVisible(new PointF(x, y), pen, null); public bool IsOutlineVisible(PointF point, Pen pen) => IsOutlineVisible(point, pen, null); public bool IsOutlineVisible(float x, float y, Pen pen, Graphics graphics) { return IsOutlineVisible(new PointF(x, y), pen, graphics); } public bool IsOutlineVisible(PointF pt, Pen pen, Graphics graphics) { if (pen == null) throw new ArgumentNullException(nameof(pen)); Gdip.CheckStatus(Gdip.GdipIsOutlineVisiblePathPoint( new HandleRef(this, _nativePath), pt.X, pt.Y, new HandleRef(pen, pen.NativePen), new HandleRef(graphics, graphics?.NativeGraphics ?? IntPtr.Zero), out bool isVisible)); return isVisible; } public bool IsOutlineVisible(int x, int y, Pen pen) => IsOutlineVisible(new Point(x, y), pen, null); public bool IsOutlineVisible(Point point, Pen pen) => IsOutlineVisible(point, pen, null); public bool IsOutlineVisible(int x, int y, Pen pen, Graphics graphics) => IsOutlineVisible(new Point(x, y), pen, graphics); public bool IsOutlineVisible(Point pt, Pen pen, Graphics graphics) { if (pen == null) throw new ArgumentNullException(nameof(pen)); Gdip.CheckStatus(Gdip.GdipIsOutlineVisiblePathPointI( new HandleRef(this, _nativePath), pt.X, pt.Y, new HandleRef(pen, pen.NativePen), new HandleRef(graphics, graphics?.NativeGraphics ?? IntPtr.Zero), out bool isVisible)); return isVisible; } public void AddLine(PointF pt1, PointF pt2) => AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y); public void AddLine(float x1, float y1, float x2, float y2) { Gdip.CheckStatus(Gdip.GdipAddPathLine(new HandleRef(this, _nativePath), x1, y1, x2, y2)); } public unsafe void AddLines(PointF[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathLine2(new HandleRef(this, _nativePath), p, points.Length)); } } public void AddLine(Point pt1, Point pt2) => AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y); public void AddLine(int x1, int y1, int x2, int y2) { Gdip.CheckStatus(Gdip.GdipAddPathLineI(new HandleRef(this, _nativePath), x1, y1, x2, y2)); } public unsafe void AddLines(Point[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathLine2I(new HandleRef(this, _nativePath), p, points.Length)); } } public void AddArc(RectangleF rect, float startAngle, float sweepAngle) { AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle) { Gdip.CheckStatus(Gdip.GdipAddPathArc( new HandleRef(this, _nativePath), x, y, width, height, startAngle, sweepAngle)); } public void AddArc(Rectangle rect, float startAngle, float sweepAngle) { AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } public void AddArc(int x, int y, int width, int height, float startAngle, float sweepAngle) { Gdip.CheckStatus(Gdip.GdipAddPathArcI( new HandleRef(this, _nativePath), x, y, width, height, startAngle, sweepAngle)); } public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4) { AddBezier(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); } public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { Gdip.CheckStatus(Gdip.GdipAddPathBezier( new HandleRef(this, _nativePath), x1, y1, x2, y2, x3, y3, x4, y4)); } public unsafe void AddBeziers(PointF[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathBeziers(new HandleRef(this, _nativePath), p, points.Length)); } } public void AddBezier(Point pt1, Point pt2, Point pt3, Point pt4) { AddBezier(pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); } public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { Gdip.CheckStatus(Gdip.GdipAddPathBezierI( new HandleRef(this, _nativePath), x1, y1, x2, y2, x3, y3, x4, y4)); } public unsafe void AddBeziers(params Point[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); if (points.Length == 0) return; fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathBeziersI(new HandleRef(this, _nativePath), p, points.Length)); } } /// <summary> /// Add cardinal splines to the path object /// </summary> public unsafe void AddCurve(PointF[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve(new HandleRef(this, _nativePath), p, points.Length)); } } public unsafe void AddCurve(PointF[] points, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); if (points.Length == 0) return; fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve2(new HandleRef(this, _nativePath), p, points.Length, tension)); } } public unsafe void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve3( new HandleRef(this, _nativePath), p, points.Length, offset, numberOfSegments, tension)); } } public unsafe void AddCurve(Point[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurveI(new HandleRef(this, _nativePath), p, points.Length)); } } public unsafe void AddCurve(Point[] points, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve2I( new HandleRef(this, _nativePath), p, points.Length, tension)); } } public unsafe void AddCurve(Point[] points, int offset, int numberOfSegments, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve3I( new HandleRef(this, _nativePath), p, points.Length, offset, numberOfSegments, tension)); } } public unsafe void AddClosedCurve(PointF[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve( new HandleRef(this, _nativePath), p, points.Length)); } } public unsafe void AddClosedCurve(PointF[] points, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve2(new HandleRef(this, _nativePath), p, points.Length, tension)); } } public unsafe void AddClosedCurve(Point[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurveI(new HandleRef(this, _nativePath), p, points.Length)); } } public unsafe void AddClosedCurve(Point[] points, float tension) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve2I(new HandleRef(this, _nativePath), p, points.Length, tension)); } } public void AddRectangle(RectangleF rect) { Gdip.CheckStatus(Gdip.GdipAddPathRectangle( new HandleRef(this, _nativePath), rect.X, rect.Y, rect.Width, rect.Height)); } public unsafe void AddRectangles(RectangleF[] rects) { if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (RectangleF* r = rects) { Gdip.CheckStatus(Gdip.GdipAddPathRectangles( new HandleRef(this, _nativePath), r, rects.Length)); } } public void AddRectangle(Rectangle rect) { Gdip.CheckStatus(Gdip.GdipAddPathRectangleI( new HandleRef(this, _nativePath), rect.X, rect.Y, rect.Width, rect.Height)); } public unsafe void AddRectangles(Rectangle[] rects) { if (rects == null) throw new ArgumentNullException(nameof(rects)); fixed (Rectangle* r = rects) { Gdip.CheckStatus(Gdip.GdipAddPathRectanglesI( new HandleRef(this, _nativePath), r, rects.Length)); } } public void AddEllipse(RectangleF rect) { AddEllipse(rect.X, rect.Y, rect.Width, rect.Height); } public void AddEllipse(float x, float y, float width, float height) { Gdip.CheckStatus(Gdip.GdipAddPathEllipse(new HandleRef(this, _nativePath), x, y, width, height)); } public void AddEllipse(Rectangle rect) => AddEllipse(rect.X, rect.Y, rect.Width, rect.Height); public void AddEllipse(int x, int y, int width, int height) { Gdip.CheckStatus(Gdip.GdipAddPathEllipseI(new HandleRef(this, _nativePath), x, y, width, height)); } public void AddPie(Rectangle rect, float startAngle, float sweepAngle) { AddPie(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } public void AddPie(float x, float y, float width, float height, float startAngle, float sweepAngle) { Gdip.CheckStatus(Gdip.GdipAddPathPie( new HandleRef(this, _nativePath), x, y, width, height, startAngle, sweepAngle)); } public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle) { Gdip.CheckStatus(Gdip.GdipAddPathPieI( new HandleRef(this, _nativePath), x, y, width, height, startAngle, sweepAngle)); } public unsafe void AddPolygon(PointF[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathPolygon(new HandleRef(this, _nativePath), p, points.Length)); } } /// <summary> /// Adds a polygon to the current figure. /// </summary> public unsafe void AddPolygon(Point[] points) { if (points == null) throw new ArgumentNullException(nameof(points)); fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathPolygonI(new HandleRef(this, _nativePath), p, points.Length)); } } public void AddPath(GraphicsPath addingPath, bool connect) { if (addingPath == null) throw new ArgumentNullException(nameof(addingPath)); Gdip.CheckStatus(Gdip.GdipAddPathPath( new HandleRef(this, _nativePath), new HandleRef(addingPath, addingPath._nativePath), connect)); } public void AddString(string s, FontFamily family, int style, float emSize, PointF origin, StringFormat format) { AddString(s, family, style, emSize, new RectangleF(origin.X, origin.Y, 0, 0), format); } public void AddString(string s, FontFamily family, int style, float emSize, Point origin, StringFormat format) { AddString(s, family, style, emSize, new Rectangle(origin.X, origin.Y, 0, 0), format); } public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat format) { Gdip.CheckStatus(Gdip.GdipAddPathString( new HandleRef(this, _nativePath), s, s.Length, new HandleRef(family, family?.NativeFamily ?? IntPtr.Zero), style, emSize, ref layoutRect, new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero))); } public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat format) { Gdip.CheckStatus(Gdip.GdipAddPathStringI( new HandleRef(this, _nativePath), s, s.Length, new HandleRef(family, family?.NativeFamily ?? IntPtr.Zero), style, emSize, ref layoutRect, new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero))); } public void Transform(Matrix matrix) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); if (matrix.NativeMatrix == IntPtr.Zero) return; Gdip.CheckStatus(Gdip.GdipTransformPath( new HandleRef(this, _nativePath), new HandleRef(matrix, matrix.NativeMatrix))); } public RectangleF GetBounds() => GetBounds(null); public RectangleF GetBounds(Matrix matrix) => GetBounds(matrix, null); public RectangleF GetBounds(Matrix matrix, Pen pen) { Gdip.CheckStatus(Gdip.GdipGetPathWorldBounds( new HandleRef(this, _nativePath), out RectangleF bounds, new HandleRef(matrix, matrix?.NativeMatrix ?? IntPtr.Zero), new HandleRef(pen, pen?.NativePen ?? IntPtr.Zero))); return bounds; } public void Flatten() => Flatten(null); public void Flatten(Matrix matrix) => Flatten(matrix, 0.25f); public void Flatten(Matrix matrix, float flatness) { Gdip.CheckStatus(Gdip.GdipFlattenPath( new HandleRef(this, _nativePath), new HandleRef(matrix, matrix?.NativeMatrix ?? IntPtr.Zero), flatness)); } public void Widen(Pen pen) { const float flatness = (float)2.0 / (float)3.0; Widen(pen, null, flatness); } public void Widen(Pen pen, Matrix matrix) { const float flatness = (float)2.0 / (float)3.0; Widen(pen, matrix, flatness); } public void Widen(Pen pen, Matrix matrix, float flatness) { if (pen == null) throw new ArgumentNullException(nameof(pen)); // GDI+ wrongly returns an out of memory status when there is nothing in the path, so we have to check // before calling the widen method and do nothing if we dont have anything in the path. if (PointCount == 0) return; Gdip.CheckStatus(Gdip.GdipWidenPath( new HandleRef(this, _nativePath), new HandleRef(pen, pen.NativePen), new HandleRef(matrix, matrix?.NativeMatrix ?? IntPtr.Zero), flatness)); } public void Warp(PointF[] destPoints, RectangleF srcRect) => Warp(destPoints, srcRect, null); public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix) => Warp(destPoints, srcRect, matrix, WarpMode.Perspective); public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode) { Warp(destPoints, srcRect, matrix, warpMode, 0.25f); } public unsafe void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode, float flatness) { if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); fixed (PointF* p = destPoints) { Gdip.CheckStatus(Gdip.GdipWarpPath( new HandleRef(this, _nativePath), new HandleRef(matrix, matrix?.NativeMatrix ?? IntPtr.Zero), p, destPoints.Length, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness)); } } public int PointCount { get { Gdip.CheckStatus(Gdip.GdipGetPointCount(new HandleRef(this, _nativePath), out int count)); return count; } } public byte[] PathTypes { get { byte[] types = new byte[PointCount]; Gdip.CheckStatus(Gdip.GdipGetPathTypes(new HandleRef(this, _nativePath), types, types.Length)); return types; } } public unsafe PointF[] PathPoints { get { PointF[] points = new PointF[PointCount]; fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipGetPathPoints(new HandleRef(this, _nativePath), p, points.Length)); } return points; } } } }
// 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! namespace Google.Cloud.Gaming.V1Beta.Snippets { using Google.Api.Gax; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedGameServerConfigsServiceClientSnippets { /// <summary>Snippet for ListGameServerConfigs</summary> public void ListGameServerConfigsRequestObject() { // Snippet: ListGameServerConfigs(ListGameServerConfigsRequest, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) ListGameServerConfigsRequest request = new ListGameServerConfigsRequest { ParentAsGameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigs(request); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerConfigsAsync</summary> public async Task ListGameServerConfigsRequestObjectAsync() { // Snippet: ListGameServerConfigsAsync(ListGameServerConfigsRequest, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) ListGameServerConfigsRequest request = new ListGameServerConfigsRequest { ParentAsGameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerConfigs</summary> public void ListGameServerConfigs() { // Snippet: ListGameServerConfigs(string, string, int?, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request PagedEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerConfigsAsync</summary> public async Task ListGameServerConfigsAsync() { // Snippet: ListGameServerConfigsAsync(string, string, int?, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request PagedAsyncEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerConfigs</summary> public void ListGameServerConfigsResourceNames() { // Snippet: ListGameServerConfigs(GameServerDeploymentName, string, int?, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentName parent = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request PagedEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerConfig item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerConfigsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerConfigsAsync</summary> public async Task ListGameServerConfigsResourceNamesAsync() { // Snippet: ListGameServerConfigsAsync(GameServerDeploymentName, string, int?, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentName parent = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request PagedAsyncEnumerable<ListGameServerConfigsResponse, GameServerConfig> response = gameServerConfigsServiceClient.ListGameServerConfigsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerConfig item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerConfigsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerConfig item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerConfig> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerConfig item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetGameServerConfig</summary> public void GetGameServerConfigRequestObject() { // Snippet: GetGameServerConfig(GetGameServerConfigRequest, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; // Make the request GameServerConfig response = gameServerConfigsServiceClient.GetGameServerConfig(request); // End snippet } /// <summary>Snippet for GetGameServerConfigAsync</summary> public async Task GetGameServerConfigRequestObjectAsync() { // Snippet: GetGameServerConfigAsync(GetGameServerConfigRequest, CallSettings) // Additional: GetGameServerConfigAsync(GetGameServerConfigRequest, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GetGameServerConfigRequest request = new GetGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; // Make the request GameServerConfig response = await gameServerConfigsServiceClient.GetGameServerConfigAsync(request); // End snippet } /// <summary>Snippet for GetGameServerConfig</summary> public void GetGameServerConfig() { // Snippet: GetGameServerConfig(string, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]/configs/[CONFIG]"; // Make the request GameServerConfig response = gameServerConfigsServiceClient.GetGameServerConfig(name); // End snippet } /// <summary>Snippet for GetGameServerConfigAsync</summary> public async Task GetGameServerConfigAsync() { // Snippet: GetGameServerConfigAsync(string, CallSettings) // Additional: GetGameServerConfigAsync(string, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]/configs/[CONFIG]"; // Make the request GameServerConfig response = await gameServerConfigsServiceClient.GetGameServerConfigAsync(name); // End snippet } /// <summary>Snippet for GetGameServerConfig</summary> public void GetGameServerConfigResourceNames() { // Snippet: GetGameServerConfig(GameServerConfigName, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) GameServerConfigName name = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"); // Make the request GameServerConfig response = gameServerConfigsServiceClient.GetGameServerConfig(name); // End snippet } /// <summary>Snippet for GetGameServerConfigAsync</summary> public async Task GetGameServerConfigResourceNamesAsync() { // Snippet: GetGameServerConfigAsync(GameServerConfigName, CallSettings) // Additional: GetGameServerConfigAsync(GameServerConfigName, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerConfigName name = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"); // Make the request GameServerConfig response = await gameServerConfigsServiceClient.GetGameServerConfigAsync(name); // End snippet } /// <summary>Snippet for CreateGameServerConfig</summary> public void CreateGameServerConfigRequestObject() { // Snippet: CreateGameServerConfig(CreateGameServerConfigRequest, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) CreateGameServerConfigRequest request = new CreateGameServerConfigRequest { ParentAsGameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), ConfigId = "", GameServerConfig = new GameServerConfig(), }; // Make the request Operation<GameServerConfig, OperationMetadata> response = gameServerConfigsServiceClient.CreateGameServerConfig(request); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceCreateGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerConfigAsync</summary> public async Task CreateGameServerConfigRequestObjectAsync() { // Snippet: CreateGameServerConfigAsync(CreateGameServerConfigRequest, CallSettings) // Additional: CreateGameServerConfigAsync(CreateGameServerConfigRequest, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) CreateGameServerConfigRequest request = new CreateGameServerConfigRequest { ParentAsGameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), ConfigId = "", GameServerConfig = new GameServerConfig(), }; // Make the request Operation<GameServerConfig, OperationMetadata> response = await gameServerConfigsServiceClient.CreateGameServerConfigAsync(request); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceCreateGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerConfig</summary> public void CreateGameServerConfig() { // Snippet: CreateGameServerConfig(string, GameServerConfig, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; GameServerConfig gameServerConfig = new GameServerConfig(); // Make the request Operation<GameServerConfig, OperationMetadata> response = gameServerConfigsServiceClient.CreateGameServerConfig(parent, gameServerConfig); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceCreateGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerConfigAsync</summary> public async Task CreateGameServerConfigAsync() { // Snippet: CreateGameServerConfigAsync(string, GameServerConfig, CallSettings) // Additional: CreateGameServerConfigAsync(string, GameServerConfig, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; GameServerConfig gameServerConfig = new GameServerConfig(); // Make the request Operation<GameServerConfig, OperationMetadata> response = await gameServerConfigsServiceClient.CreateGameServerConfigAsync(parent, gameServerConfig); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceCreateGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerConfig</summary> public void CreateGameServerConfigResourceNames() { // Snippet: CreateGameServerConfig(GameServerDeploymentName, GameServerConfig, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentName parent = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); GameServerConfig gameServerConfig = new GameServerConfig(); // Make the request Operation<GameServerConfig, OperationMetadata> response = gameServerConfigsServiceClient.CreateGameServerConfig(parent, gameServerConfig); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceCreateGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerConfigAsync</summary> public async Task CreateGameServerConfigResourceNamesAsync() { // Snippet: CreateGameServerConfigAsync(GameServerDeploymentName, GameServerConfig, CallSettings) // Additional: CreateGameServerConfigAsync(GameServerDeploymentName, GameServerConfig, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentName parent = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); GameServerConfig gameServerConfig = new GameServerConfig(); // Make the request Operation<GameServerConfig, OperationMetadata> response = await gameServerConfigsServiceClient.CreateGameServerConfigAsync(parent, gameServerConfig); // Poll until the returned long-running operation is complete Operation<GameServerConfig, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerConfig result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerConfig, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceCreateGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerConfig retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfig</summary> public void DeleteGameServerConfigRequestObject() { // Snippet: DeleteGameServerConfig(DeleteGameServerConfigRequest, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) DeleteGameServerConfigRequest request = new DeleteGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; // Make the request Operation<Empty, OperationMetadata> response = gameServerConfigsServiceClient.DeleteGameServerConfig(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceDeleteGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfigAsync</summary> public async Task DeleteGameServerConfigRequestObjectAsync() { // Snippet: DeleteGameServerConfigAsync(DeleteGameServerConfigRequest, CallSettings) // Additional: DeleteGameServerConfigAsync(DeleteGameServerConfigRequest, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) DeleteGameServerConfigRequest request = new DeleteGameServerConfigRequest { GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"), }; // Make the request Operation<Empty, OperationMetadata> response = await gameServerConfigsServiceClient.DeleteGameServerConfigAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceDeleteGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfig</summary> public void DeleteGameServerConfig() { // Snippet: DeleteGameServerConfig(string, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]/configs/[CONFIG]"; // Make the request Operation<Empty, OperationMetadata> response = gameServerConfigsServiceClient.DeleteGameServerConfig(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceDeleteGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfigAsync</summary> public async Task DeleteGameServerConfigAsync() { // Snippet: DeleteGameServerConfigAsync(string, CallSettings) // Additional: DeleteGameServerConfigAsync(string, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]/configs/[CONFIG]"; // Make the request Operation<Empty, OperationMetadata> response = await gameServerConfigsServiceClient.DeleteGameServerConfigAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceDeleteGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfig</summary> public void DeleteGameServerConfigResourceNames() { // Snippet: DeleteGameServerConfig(GameServerConfigName, CallSettings) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = GameServerConfigsServiceClient.Create(); // Initialize request argument(s) GameServerConfigName name = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"); // Make the request Operation<Empty, OperationMetadata> response = gameServerConfigsServiceClient.DeleteGameServerConfig(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerConfigsServiceClient.PollOnceDeleteGameServerConfig(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerConfigAsync</summary> public async Task DeleteGameServerConfigResourceNamesAsync() { // Snippet: DeleteGameServerConfigAsync(GameServerConfigName, CallSettings) // Additional: DeleteGameServerConfigAsync(GameServerConfigName, CancellationToken) // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerConfigName name = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"); // Make the request Operation<Empty, OperationMetadata> response = await gameServerConfigsServiceClient.DeleteGameServerConfigAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerConfigsServiceClient.PollOnceDeleteGameServerConfigAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } } }
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 ArtifactoryDemo.Web.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.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, 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.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using System.Globalization; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitBlockExpression(Expression expr, CompilationFlags flags) { // emit body Emit((BlockExpression)expr, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsDefaultType)); } private void Emit(BlockExpression node, CompilationFlags flags) { int count = node.ExpressionCount; if (count == 0) { return; } EnterScope(node); CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask; for (int index = 0; index < count - 1; index++) { var e = node.GetExpression(index); var next = node.GetExpression(index + 1); CompilationFlags tailCallFlag; if (tailCall != CompilationFlags.EmitAsNoTail) { var g = next as GotoExpression; if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) { // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted // as Ret. Therefore we can emit the current expression with tail call. tailCallFlag = CompilationFlags.EmitAsTail; } else { // In the middle of the block. // We may do better here by marking it as Tail if the following expressions are not going to emit any IL. tailCallFlag = CompilationFlags.EmitAsMiddle; } } else { tailCallFlag = CompilationFlags.EmitAsNoTail; } flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag); EmitExpressionAsVoid(e, flags); } // if the type of Block it means this is not a Comma // so we will force the last expression to emit as void. // We don't need EmitAsType flag anymore, should only pass // the EmitTailCall field in flags to emitting the last expression. if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) { EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall); } else { EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall); } ExitScope(node); } private void EnterScope(object node) { if (HasVariables(node) && (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) { CompilerScope scope; if (!_tree.Scopes.TryGetValue(node, out scope)) { // // Very often, we want to compile nodes as reductions // rather than as IL, but usually they need to allocate // some IL locals. To support this, we allow emitting a // BlockExpression that was not bound by VariableBinder. // This works as long as the variables are only used // locally -- i.e. not closed over. // // User-created blocks will never hit this case; only our // internally reduced nodes will. // scope = new CompilerScope(node, false) { NeedsClosure = _scope.NeedsClosure }; } _scope = scope.Enter(this, _scope); Debug.Assert(_scope.Node == node); } } private static bool HasVariables(object node) { var block = node as BlockExpression; if (block != null) { return block.Variables.Count > 0; } return ((CatchBlock)node).Variable != null; } private void ExitScope(object node) { if (_scope.Node == node) { _scope = _scope.Exit(); } } private void EmitDefaultExpression(Expression expr) { var node = (DefaultExpression)expr; if (node.Type != typeof(void)) { // emit default(T) _ilg.EmitDefault(node.Type); } } private void EmitLoopExpression(Expression expr) { LoopExpression node = (LoopExpression)expr; PushLabelBlock(LabelScopeKind.Statement); LabelInfo breakTarget = DefineLabel(node.BreakLabel); LabelInfo continueTarget = DefineLabel(node.ContinueLabel); continueTarget.MarkWithEmptyStack(); EmitExpressionAsVoid(node.Body); _ilg.Emit(OpCodes.Br, continueTarget.Label); PopLabelBlock(LabelScopeKind.Statement); breakTarget.MarkWithEmptyStack(); } #region SwitchExpression private void EmitSwitchExpression(Expression expr, CompilationFlags flags) { SwitchExpression node = (SwitchExpression)expr; if (node.Cases.Count == 0) { // Emit the switch value in case it has side-effects, but as void // since the value is ignored. EmitExpressionAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. if (node.DefaultBody != null) { EmitExpressionAsType(node.DefaultBody, node.Type, flags); } else { // If there are no cases and no default then the type must be void. // Assert that earlier validation caught any exceptions to that. Debug.Assert(expr.Type == typeof(void)); } return; } // Try to emit it as an IL switch. Works for integer types. if (TryEmitSwitchInstruction(node, flags)) { return; } // Try to emit as a hashtable lookup. Works for strings. if (TryEmitHashtableSwitch(node, flags)) { return; } // // Fall back to a series of tests. We need to IL gen instead of // transform the tree to avoid stack overflow on a big switch. // var switchValue = Expression.Parameter(node.SwitchValue.Type, "switchValue"); var testValue = Expression.Parameter(GetTestValueType(node), "testValue"); _scope.AddLocal(this, switchValue); _scope.AddLocal(this, testValue); EmitExpression(node.SwitchValue); _scope.EmitSet(switchValue); // Emit tests var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; for (int i = 0, n = node.Cases.Count; i < n; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (Expression test in node.Cases[i].TestValues) { // Pull the test out into a temp so it runs on the same // stack as the switch. This simplifies spilling. EmitExpression(test); _scope.EmitSet(testValue); Debug.Assert(TypeUtils.AreReferenceAssignable(testValue.Type, test.Type)); EmitExpressionAndBranch(true, Expression.Equal(switchValue, testValue, false, node.Comparison), labels[i]); } } // Define labels Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the case and default bodies EmitSwitchCases(node, labels, isGoto, @default, end, flags); } /// <summary> /// Gets the common test value type of the SwitchExpression. /// </summary> private static Type GetTestValueType(SwitchExpression node) { if (node.Comparison == null) { // If we have no comparison, all right side types must be the // same. return node.Cases[0].TestValues[0].Type; } // Otherwise, get the type from the method. Type result = node.Comparison.GetParametersCached()[1].ParameterType.GetNonRefType(); if (node.IsLifted) { result = TypeUtils.GetNullableType(result); } return result; } private sealed class SwitchLabel { internal readonly decimal Key; internal readonly Label Label; // Boxed version of Key, preserving the original type. internal readonly object Constant; internal SwitchLabel(decimal key, object @constant, Label label) { Key = key; Constant = @constant; Label = label; } } private sealed class SwitchInfo { internal readonly SwitchExpression Node; internal readonly LocalBuilder Value; internal readonly Label Default; internal readonly Type Type; internal readonly bool IsUnsigned; internal readonly bool Is64BitSwitch; internal SwitchInfo(SwitchExpression node, LocalBuilder value, Label @default) { Node = node; Value = value; Default = @default; Type = Node.SwitchValue.Type; IsUnsigned = TypeUtils.IsUnsigned(Type); var code = Type.GetTypeCode(); Is64BitSwitch = code == TypeCode.UInt64 || code == TypeCode.Int64; } } private static bool FitsInBucket(List<SwitchLabel> buckets, decimal key, int count) { Debug.Assert(key > buckets[buckets.Count - 1].Key); decimal jumpTableSlots = key - buckets[0].Key + 1; if (jumpTableSlots > int.MaxValue) { return false; } // density must be > 50% return (buckets.Count + count) * 2 > jumpTableSlots; } private static void MergeBuckets(List<List<SwitchLabel>> buckets) { while (buckets.Count > 1) { List<SwitchLabel> first = buckets[buckets.Count - 2]; List<SwitchLabel> second = buckets[buckets.Count - 1]; if (!FitsInBucket(first, second[second.Count - 1].Key, second.Count)) { return; } // Merge them first.AddRange(second); buckets.RemoveAt(buckets.Count - 1); } } // Add key to a new or existing bucket private static void AddToBuckets(List<List<SwitchLabel>> buckets, SwitchLabel key) { if (buckets.Count > 0) { List<SwitchLabel> last = buckets[buckets.Count - 1]; if (FitsInBucket(last, key.Key, 1)) { last.Add(key); // we might be able to merge now MergeBuckets(buckets); return; } } // else create a new bucket buckets.Add(new List<SwitchLabel> { key }); } // Determines if the type is an integer we can switch on. private static bool CanOptimizeSwitchType(Type valueType) { // enums & char are allowed switch (valueType.GetTypeCode()) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Char: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } // Tries to emit switch as a jmp table private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) { // If we have a comparison, bail if (node.Comparison != null) { return false; } // Make sure the switch value type and the right side type // are types we can optimize Type type = node.SwitchValue.Type; if (!CanOptimizeSwitchType(type) || !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) { return false; } // Make sure all test values are constant, or we can't emit the // jump table. if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) { return false; } // // We can emit the optimized switch, let's do it. // // Build target labels, collect keys. var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; var uniqueKeys = new HashSet<decimal>(); var keys = new List<SwitchLabel>(); for (int i = 0; i < node.Cases.Count; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (ConstantExpression test in node.Cases[i].TestValues) { // Guaranteed to work thanks to CanOptimizeSwitchType. // // Use decimal because it can hold Int64 or UInt64 without // precision loss or signed/unsigned conversions. decimal key = ConvertSwitchValue(test.Value); // Only add each key once. If it appears twice, it's // allowed, but can't be reached. if (uniqueKeys.Add(key)) { keys.Add(new SwitchLabel(key, test.Value, labels[i])); } } } // Sort the keys, and group them into buckets. keys.Sort((x, y) => Math.Sign(x.Key - y.Key)); var buckets = new List<List<SwitchLabel>>(); foreach (var key in keys) { AddToBuckets(buckets, key); } // Emit the switchValue LocalBuilder value = GetLocal(node.SwitchValue.Type); EmitExpression(node.SwitchValue); _ilg.Emit(OpCodes.Stloc, value); // Create end label, and default label if needed Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the switch var info = new SwitchInfo(node, value, @default); EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1); // Emit the case bodies and default EmitSwitchCases(node, labels, isGoto, @default, end, flags); FreeLocal(value); return true; } private static decimal ConvertSwitchValue(object value) { if (value is char) { return (int)(char)value; } return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } /// <summary> /// Creates the label for this case. /// Optimization: if the body is just a goto, and we can branch /// to it, put the goto target directly in the jump table. /// </summary> private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool isGoto) { var jump = @case.Body as GotoExpression; // if it's a goto with no value if (jump != null && jump.Value == null) { // Reference the label from the switch. This will cause us to // analyze the jump target and determine if it is safe. LabelInfo jumpInfo = ReferenceLabel(jump.Target); // If we have are allowed to emit the "branch" opcode, then we // can jump directly there from the switch's jump table. // (Otherwise, we need to emit the goto later as a "leave".) if (jumpInfo.CanBranch) { label = jumpInfo.Label; isGoto = true; return; } } // otherwise, just define a new label label = _ilg.DefineLabel(); isGoto = false; } private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGoto, Label @default, Label end, CompilationFlags flags) { // Jump to default (to handle the fallthrough case) _ilg.Emit(OpCodes.Br, @default); // Emit the cases for (int i = 0, n = node.Cases.Count; i < n; i++) { // If the body is a goto, we already emitted an optimized // branch directly to it. No need to emit anything else. if (isGoto[i]) { continue; } _ilg.MarkLabel(labels[i]); EmitExpressionAsType(node.Cases[i].Body, node.Type, flags); // Last case doesn't need branch if (node.DefaultBody != null || i < n - 1) { if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { //The switch case is at the tail of the lambda so //it is safe to emit a Ret. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, end); } } } // Default value if (node.DefaultBody != null) { _ilg.MarkLabel(@default); EmitExpressionAsType(node.DefaultBody, node.Type, flags); } _ilg.MarkLabel(end); } private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) { if (first == last) { EmitSwitchBucket(info, buckets[first]); return; } // Split the buckets into two groups, and use an if test to find // the right bucket. This ensures we'll only need O(lg(B)) tests // where B is the number of buckets int mid = (int)(((long)first + last + 1) / 2); if (first == mid - 1) { EmitSwitchBucket(info, buckets[first]); } else { // If the first half contains more than one, we need to emit an // explicit guard Label secondHalf = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(buckets[mid - 1].Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf); EmitSwitchBuckets(info, buckets, first, mid - 1); _ilg.MarkLabel(secondHalf); } EmitSwitchBuckets(info, buckets, mid, last); } private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) { // No need for switch if we only have one value if (bucket.Count == 1) { _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Beq, bucket[0].Label); return; } // // If we're switching off of Int64/UInt64, we need more guards here // because we'll have to narrow the switch value to an Int32, and // we can't do that unless the value is in the right range. // Label? after = null; if (info.Is64BitSwitch) { after = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket.Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value); } _ilg.Emit(OpCodes.Ldloc, info.Value); // Normalize key decimal key = bucket[0].Key; if (key != 0) { _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Sub); } if (info.Is64BitSwitch) { _ilg.Emit(OpCodes.Conv_I4); } // Collect labels int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1); Label[] jmpLabels = new Label[len]; // Initialize all labels to the default int slot = 0; foreach (SwitchLabel label in bucket) { while (key++ != label.Key) { jmpLabels[slot++] = info.Default; } jmpLabels[slot++] = label.Label; } // check we used all keys and filled all slots Debug.Assert(key == bucket[bucket.Count - 1].Key + 1); Debug.Assert(slot == jmpLabels.Length); // Finally, emit the switch instruction _ilg.Emit(OpCodes.Switch, jmpLabels); if (info.Is64BitSwitch) { _ilg.MarkLabel(after.Value); } } private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flags) { // If we have a comparison other than string equality, bail MethodInfo equality = typeof(string).GetMethod("op_Equality", new[] { typeof(string), typeof(string) }); if (!equality.IsStatic) { equality = null; } if (node.Comparison != equality) { return false; } // All test values must be constant. int tests = 0; foreach (SwitchCase c in node.Cases) { foreach (Expression t in c.TestValues) { if (!(t is ConstantExpression)) { return false; } tests++; } } // Must have >= 7 labels for it to be worth it. if (tests < 7) { return false; } // If we're in a DynamicMethod, we could just build the dictionary // immediately. But that would cause the two code paths to be more // different than they really need to be. var initializers = new List<ElementInit>(tests); var cases = new List<SwitchCase>(node.Cases.Count); int nullCase = -1; MethodInfo add = typeof(Dictionary<string, int>).GetMethod("Add", new[] { typeof(string), typeof(int) }); for (int i = 0, n = node.Cases.Count; i < n; i++) { foreach (ConstantExpression t in node.Cases[i].TestValues) { if (t.Value != null) { initializers.Add(Expression.ElementInit(add, t, Expression.Constant(i))); } else { nullCase = i; } } cases.Add(Expression.SwitchCase(node.Cases[i].Body, Expression.Constant(i))); } // Create the field to hold the lazily initialized dictionary MemberExpression dictField = CreateLazyInitializedField<Dictionary<string, int>>("dictionarySwitch"); // If we happen to initialize it twice (multithreaded case), it's // not the end of the world. The C# compiler does better here by // emitting a volatile access to the field. Expression dictInit = Expression.Condition( Expression.Equal(dictField, Expression.Constant(null, dictField.Type)), Expression.Assign( dictField, Expression.ListInit( Expression.New( typeof(Dictionary<string, int>).GetConstructor(new[] { typeof(int) }), Expression.Constant(initializers.Count) ), initializers ) ), dictField ); // // Create a tree like: // // switchValue = switchValueExpression; // if (switchValue == null) { // switchIndex = nullCase; // } else { // if (_dictField == null) { // _dictField = new Dictionary<string, int>(count) { { ... }, ... }; // } // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { // switchIndex = -1; // } // } // switch (switchIndex) { // case 0: ... // case 1: ... // ... // default: // } // var switchValue = Expression.Variable(typeof(string), "switchValue"); var switchIndex = Expression.Variable(typeof(int), "switchIndex"); var reduced = Expression.Block( new[] { switchIndex, switchValue }, Expression.Assign(switchValue, node.SwitchValue), Expression.IfThenElse( Expression.Equal(switchValue, Expression.Constant(null, typeof(string))), Expression.Assign(switchIndex, Expression.Constant(nullCase)), Expression.IfThenElse( Expression.Call(dictInit, "TryGetValue", null, switchValue, switchIndex), Expression.Empty(), Expression.Assign(switchIndex, Expression.Constant(-1)) ) ), Expression.Switch(node.Type, switchIndex, node.DefaultBody, null, cases) ); EmitExpression(reduced, flags); return true; } #endregion private void CheckRethrow() { // Rethrow is only valid inside a catch. for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { return; } else if (j.Kind == LabelScopeKind.Finally) { // Rethrow from inside finally is not verifiable break; } } throw Error.RethrowRequiresCatch(); } #region TryStatement private void CheckTry() { // Try inside a filter is not verifiable for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { throw Error.TryNotAllowedInFilter(); } } } private void EmitSaveExceptionOrPop(CatchBlock cb) { if (cb.Variable != null) { // If the variable is present, store the exception // in the variable. _scope.EmitSet(cb.Variable); } else { // Otherwise, pop it off the stack. _ilg.Emit(OpCodes.Pop); } } private void EmitTryExpression(Expression expr) { var node = (TryExpression)expr; CheckTry(); //****************************************************************** // 1. ENTERING TRY //****************************************************************** PushLabelBlock(LabelScopeKind.Try); _ilg.BeginExceptionBlock(); //****************************************************************** // 2. Emit the try statement body //****************************************************************** EmitExpression(node.Body); Type tryType = expr.Type; LocalBuilder value = null; if (tryType != typeof(void)) { //store the value of the try body value = GetLocal(tryType); _ilg.Emit(OpCodes.Stloc, value); } //****************************************************************** // 3. Emit the catch blocks //****************************************************************** foreach (CatchBlock cb in node.Handlers) { PushLabelBlock(LabelScopeKind.Catch); // Begin the strongly typed exception block if (cb.Filter == null) { _ilg.BeginCatchBlock(cb.Test); } else { _ilg.BeginExceptFilterBlock(); } EnterScope(cb); EmitCatchStart(cb); // // Emit the catch block body // EmitExpression(cb.Body); if (tryType != typeof(void)) { //store the value of the catch block body _ilg.Emit(OpCodes.Stloc, value); } ExitScope(cb); PopLabelBlock(LabelScopeKind.Catch); } //****************************************************************** // 4. Emit the finally block //****************************************************************** if (node.Finally != null || node.Fault != null) { PushLabelBlock(LabelScopeKind.Finally); if (node.Finally != null) { _ilg.BeginFinallyBlock(); } else { _ilg.BeginFaultBlock(); } // Emit the body EmitExpressionAsVoid(node.Finally ?? node.Fault); _ilg.EndExceptionBlock(); PopLabelBlock(LabelScopeKind.Finally); } else { _ilg.EndExceptionBlock(); } if (tryType != typeof(void)) { _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); } PopLabelBlock(LabelScopeKind.Try); } /// <summary> /// Emits the start of a catch block. The exception value that is provided by the /// CLR is stored in the variable specified by the catch block or popped if no /// variable is provided. /// </summary> private void EmitCatchStart(CatchBlock cb) { if (cb.Filter == null) { EmitSaveExceptionOrPop(cb); return; } // emit filter block. Filter blocks are untyped so we need to do // the type check ourselves. Label endFilter = _ilg.DefineLabel(); Label rightType = _ilg.DefineLabel(); // skip if it's not our exception type, but save // the exception if it is so it's available to the // filter _ilg.Emit(OpCodes.Isinst, cb.Test); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue, rightType); _ilg.Emit(OpCodes.Pop); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br, endFilter); // it's our type, save it and emit the filter. _ilg.MarkLabel(rightType); EmitSaveExceptionOrPop(cb); PushLabelBlock(LabelScopeKind.Filter); EmitExpression(cb.Filter); PopLabelBlock(LabelScopeKind.Filter); // begin the catch, clear the exception, we've // already saved it _ilg.MarkLabel(endFilter); _ilg.BeginCatchBlock(null); _ilg.Emit(OpCodes.Pop); } #endregion } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Threading; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents menu item /// </summary> [ContentProperty(nameof(Items))] [TemplatePart(Name = "PART_ResizeVerticalThumb", Type = typeof(Thumb))] [TemplatePart(Name = "PART_ResizeBothThumb", Type = typeof(Thumb))] [TemplatePart(Name = "PART_ScrollViewer", Type = typeof(ScrollViewer))] [TemplatePart(Name = "PART_MenuPanel", Type = typeof(Panel))] public class MenuItem : System.Windows.Controls.MenuItem, IQuickAccessItemProvider, IRibbonControl, IDropDownControl, IToggleButton { #region Fields // Thumb to resize in both directions private Thumb resizeBothThumb; // Thumb to resize vertical private Thumb resizeVerticalThumb; private Panel menuPanel; private ScrollViewer scrollViewer; #endregion #region Properties private bool IsItemsControlMenuBase => (ItemsControlHelper.ItemsControlFromItemContainer(this) ?? VisualTreeHelper.GetParent(this)) is MenuBase; #region Size /// <inheritdoc /> public RibbonControlSize Size { get { return (RibbonControlSize)this.GetValue(SizeProperty); } set { this.SetValue(SizeProperty, value); } } /// <summary>Identifies the <see cref="Size"/> dependency property.</summary> public static readonly DependencyProperty SizeProperty = RibbonProperties.SizeProperty.AddOwner(typeof(MenuItem)); #endregion #region SizeDefinition /// <inheritdoc /> public RibbonControlSizeDefinition SizeDefinition { get { return (RibbonControlSizeDefinition)this.GetValue(SizeDefinitionProperty); } set { this.SetValue(SizeDefinitionProperty, value); } } /// <summary>Identifies the <see cref="SizeDefinition"/> dependency property.</summary> public static readonly DependencyProperty SizeDefinitionProperty = RibbonProperties.SizeDefinitionProperty.AddOwner(typeof(MenuItem)); #endregion #region KeyTip /// <inheritdoc /> public string KeyTip { get { return (string)this.GetValue(KeyTipProperty); } set { this.SetValue(KeyTipProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for Keys. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(MenuItem)); #endregion /// <inheritdoc /> public Popup DropDownPopup { get; private set; } /// <inheritdoc /> public bool IsContextMenuOpened { get; set; } #region Description /// <summary> /// Useless property only used in secon level application menu items /// </summary> public string Description { get { return (string)this.GetValue(DescriptionProperty); } set { this.SetValue(DescriptionProperty, value); } } /// <summary>Identifies the <see cref="Description"/> dependency property.</summary> public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register(nameof(Description), typeof(string), typeof(MenuItem), new PropertyMetadata(default(string))); #endregion #region IsDropDownOpen /// <inheritdoc /> public bool IsDropDownOpen { get { return this.IsSubmenuOpen; } set { this.IsSubmenuOpen = value; } } #endregion #region IsDefinitive /// <summary> /// Gets or sets whether ribbon control click must close backstage /// </summary> public bool IsDefinitive { get { return (bool)this.GetValue(IsDefinitiveProperty); } set { this.SetValue(IsDefinitiveProperty, value); } } /// <summary>Identifies the <see cref="IsDefinitive"/> dependency property.</summary> public static readonly DependencyProperty IsDefinitiveProperty = DependencyProperty.Register(nameof(IsDefinitive), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region ResizeMode /// <summary> /// Gets or sets context menu resize mode /// </summary> public ContextMenuResizeMode ResizeMode { get { return (ContextMenuResizeMode)this.GetValue(ResizeModeProperty); } set { this.SetValue(ResizeModeProperty, value); } } /// <summary>Identifies the <see cref="ResizeMode"/> dependency property.</summary> public static readonly DependencyProperty ResizeModeProperty = DependencyProperty.Register(nameof(ResizeMode), typeof(ContextMenuResizeMode), typeof(MenuItem), new PropertyMetadata(ContextMenuResizeMode.None)); #endregion #region MaxDropDownHeight /// <summary> /// Get or sets max height of drop down popup /// </summary> public double MaxDropDownHeight { get { return (double)this.GetValue(MaxDropDownHeightProperty); } set { this.SetValue(MaxDropDownHeightProperty, value); } } /// <summary>Identifies the <see cref="MaxDropDownHeight"/> dependency property.</summary> public static readonly DependencyProperty MaxDropDownHeightProperty = DependencyProperty.Register(nameof(MaxDropDownHeight), typeof(double), typeof(MenuItem), new PropertyMetadata(SystemParameters.PrimaryScreenHeight / 3.0)); #endregion #region IsSplited /// <summary> /// Gets or sets a value indicating whether menu item is splited /// </summary> public bool IsSplited { get { return (bool)this.GetValue(IsSplitedProperty); } set { this.SetValue(IsSplitedProperty, value); } } /// <summary>Identifies the <see cref="IsSplited"/> dependency property.</summary> public static readonly DependencyProperty IsSplitedProperty = DependencyProperty.Register(nameof(IsSplited), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.FalseBox)); #endregion #region GroupName /// <inheritdoc /> public string GroupName { get { return (string)this.GetValue(GroupNameProperty); } set { this.SetValue(GroupNameProperty, value); } } /// <inheritdoc /> bool? IToggleButton.IsChecked { get { return this.IsChecked; } set { this.IsChecked = value == true; } } /// <summary>Identifies the <see cref="GroupName"/> dependency property.</summary> public static readonly DependencyProperty GroupNameProperty = DependencyProperty.Register(nameof(GroupName), typeof(string), typeof(MenuItem), new PropertyMetadata(ToggleButtonHelper.OnGroupNameChanged)); #endregion #endregion #region Events /// <inheritdoc /> public event EventHandler DropDownOpened; /// <inheritdoc /> public event EventHandler DropDownClosed; #endregion #region Constructors /// <summary> /// Initializes static members of the <see cref="MenuItem"/> class. /// </summary> static MenuItem() { var type = typeof(MenuItem); ToolTipService.Attach(type); //PopupService.Attach(type); ContextMenuService.Attach(type); DefaultStyleKeyProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(type)); IsCheckedProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, ToggleButtonHelper.OnIsCheckedChanged)); IconProperty.OverrideMetadata(typeof(MenuItem), new FrameworkPropertyMetadata(LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); } /// <summary> /// Initializes a new instance of the <see cref="MenuItem"/> class. /// </summary> public MenuItem() { ContextMenuService.Coerce(this); this.MouseWheel += this.OnMenuItemMouseWheel; } // Fix to raise MouseWhele event private void OnMenuItemMouseWheel(object sender, MouseWheelEventArgs e) { (((MenuItem)sender).Parent as ListBox)?.RaiseEvent(e); } #endregion /// <summary>Identifies the <see cref="RecognizesAccessKey"/> dependency property.</summary> public static readonly DependencyProperty RecognizesAccessKeyProperty = DependencyProperty.RegisterAttached( nameof(RecognizesAccessKey), typeof(bool), typeof(MenuItem), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary>Helper for setting <see cref="RecognizesAccessKeyProperty"/> on <paramref name="element"/>.</summary> /// <param name="element"><see cref="DependencyObject"/> to set <see cref="RecognizesAccessKeyProperty"/> on.</param> /// <param name="value">RecognizesAccessKey property value.</param> public static void SetRecognizesAccessKey(DependencyObject element, bool value) { element.SetValue(RecognizesAccessKeyProperty, value); } /// <summary>Helper for getting <see cref="RecognizesAccessKeyProperty"/> from <paramref name="element"/>.</summary> /// <param name="element"><see cref="DependencyObject"/> to read <see cref="RecognizesAccessKeyProperty"/> from.</param> /// <returns>RecognizesAccessKey property value.</returns> public static bool GetRecognizesAccessKey(DependencyObject element) { return (bool)element.GetValue(RecognizesAccessKeyProperty); } /// <summary> /// Defines if access keys should be recognized. /// </summary> public bool RecognizesAccessKey { get { return (bool)this.GetValue(RecognizesAccessKeyProperty); } set { this.SetValue(RecognizesAccessKeyProperty, value); } } #region QuickAccess /// <inheritdoc /> public virtual FrameworkElement CreateQuickAccessItem() { if (this.HasItems) { if (this.IsSplited) { var button = new SplitButton { CanAddButtonToQuickAccessToolBar = false }; RibbonControl.BindQuickAccessItem(this, button); RibbonControl.Bind(this, button, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay); button.DropDownOpened += this.OnQuickAccessOpened; return button; } else { var button = new DropDownButton(); RibbonControl.BindQuickAccessItem(this, button); RibbonControl.Bind(this, button, nameof(this.ResizeMode), ResizeModeProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.MaxDropDownHeight), MaxDropDownHeightProperty, BindingMode.Default); RibbonControl.Bind(this, button, nameof(this.DisplayMemberPath), DisplayMemberPathProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.GroupStyleSelector), GroupStyleSelectorProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemContainerStyle), ItemContainerStyleProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemsPanel), ItemsPanelProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemStringFormat), ItemStringFormatProperty, BindingMode.OneWay); RibbonControl.Bind(this, button, nameof(this.ItemTemplate), ItemTemplateProperty, BindingMode.OneWay); button.DropDownOpened += this.OnQuickAccessOpened; return button; } } else { var button = new Button(); RibbonControl.BindQuickAccessItem(this, button); return button; } } /// <summary> /// Handles quick access button drop down menu opened /// </summary> protected void OnQuickAccessOpened(object sender, EventArgs e) { var buttonInQuickAccess = (DropDownButton)sender; buttonInQuickAccess.DropDownClosed += this.OnQuickAccessMenuClosedOrUnloaded; buttonInQuickAccess.Unloaded += this.OnQuickAccessMenuClosedOrUnloaded; ItemsControlHelper.MoveItemsToDifferentControl(this, buttonInQuickAccess); } /// <summary> /// Handles quick access button drop down menu closed /// </summary> protected void OnQuickAccessMenuClosedOrUnloaded(object sender, EventArgs e) { var buttonInQuickAccess = (DropDownButton)sender; buttonInQuickAccess.DropDownClosed -= this.OnQuickAccessMenuClosedOrUnloaded; buttonInQuickAccess.Unloaded -= this.OnQuickAccessMenuClosedOrUnloaded; ItemsControlHelper.MoveItemsToDifferentControl(buttonInQuickAccess, this); } /// <inheritdoc /> public bool CanAddToQuickAccessToolBar { get { return (bool)this.GetValue(CanAddToQuickAccessToolBarProperty); } set { this.SetValue(CanAddToQuickAccessToolBarProperty, value); } } /// <summary>Identifies the <see cref="CanAddToQuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty CanAddToQuickAccessToolBarProperty = RibbonControl.CanAddToQuickAccessToolBarProperty.AddOwner(typeof(MenuItem)); private bool isContextMenuOpening; #endregion #region Public /// <inheritdoc /> public virtual KeyTipPressedResult OnKeyTipPressed() { if (this.HasItems == false) { this.OnClick(); return KeyTipPressedResult.Empty; } else { Keyboard.Focus(this); this.IsDropDownOpen = true; return new KeyTipPressedResult(true, true); } } /// <inheritdoc /> public void OnKeyTipBack() { this.IsDropDownOpen = false; } #endregion #region Overrides /// <inheritdoc /> protected override DependencyObject GetContainerForItemOverride() { return new MenuItem(); } /// <inheritdoc /> protected override bool IsItemItsOwnContainerOverride(object item) { return item is FrameworkElement; } #region Non MenuBase ItemsControl workarounds /// <summary> /// Returns logical parent; either Parent or ItemsControlFromItemContainer(this). /// </summary> /// <remarks> /// Copied from <see cref="System.Windows.Controls.MenuItem"/>. /// </remarks> public object LogicalParent { get { if (this.Parent != null) { return this.Parent; } return ItemsControlFromItemContainer(this); } } /// <inheritdoc /> protected override void OnIsKeyboardFocusedChanged(DependencyPropertyChangedEventArgs e) { base.OnIsKeyboardFocusedChanged(e); if (this.IsItemsControlMenuBase == false) { this.IsHighlighted = this.IsKeyboardFocused; } } /// <inheritdoc /> protected override void OnMouseEnter(MouseEventArgs e) { base.OnMouseEnter(e); if (this.IsItemsControlMenuBase == false && this.isContextMenuOpening == false) { if (this.HasItems && this.LogicalParent is DropDownButton) { this.IsSubmenuOpen = true; } } } /// <inheritdoc /> protected override void OnMouseLeave(MouseEventArgs e) { base.OnMouseLeave(e); if (this.IsItemsControlMenuBase == false && this.isContextMenuOpening == false) { if (this.HasItems && this.LogicalParent is DropDownButton // prevent too slow close on regular DropDown && this.LogicalParent is ApplicationMenu == false) // prevent eager close on ApplicationMenu { this.IsSubmenuOpen = false; } } } /// <inheritdoc /> protected override void OnContextMenuOpening(ContextMenuEventArgs e) { this.isContextMenuOpening = true; // We have to close the sub menu as soon as the context menu gets opened // but only if it should be opened on ourself if (ReferenceEquals(this, e.Source)) { this.IsSubmenuOpen = false; } base.OnContextMenuOpening(e); } /// <inheritdoc /> protected override void OnContextMenuClosing(ContextMenuEventArgs e) { this.isContextMenuOpening = false; base.OnContextMenuClosing(e); } #endregion Non MenuBase ItemsControl workarounds /// <inheritdoc /> protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { if (e.ClickCount == 1) { if (this.IsSplited) { if (this.GetTemplateChild("PART_ButtonBorder") is Border buttonBorder && PopupService.IsMousePhysicallyOver(buttonBorder)) { this.OnClick(); } } else if (this.HasItems) { this.IsSubmenuOpen = !this.IsSubmenuOpen; } } base.OnMouseLeftButtonUp(e); } /// <inheritdoc /> protected override void OnClick() { // Close popup on click if (this.IsDefinitive && (!this.HasItems || this.IsSplited)) { PopupService.RaiseDismissPopupEventAsync(this, DismissPopupMode.Always); } var revertIsChecked = false; // Rewriting everthing contained in base.OnClick causes a lot of trouble. // In case IsCheckable is true and GroupName is not empty we revert the value for IsChecked back to true to prevent unchecking all items in the group if (this.IsCheckable && string.IsNullOrEmpty(this.GroupName) == false) { // If checked revert the IsChecked value back to true after forwarding the click to base if (this.IsChecked) { revertIsChecked = true; } } base.OnClick(); if (revertIsChecked) { this.RunInDispatcherAsync(() => this.SetCurrentValue(IsCheckedProperty, BooleanBoxes.TrueBox), DispatcherPriority.Background); } } /// <inheritdoc /> public override void OnApplyTemplate() { if (this.DropDownPopup != null) { this.DropDownPopup.Opened -= this.OnDropDownOpened; this.DropDownPopup.Closed -= this.OnDropDownClosed; } this.DropDownPopup = this.GetTemplateChild("PART_Popup") as Popup; if (this.DropDownPopup != null) { this.DropDownPopup.Opened += this.OnDropDownOpened; this.DropDownPopup.Closed += this.OnDropDownClosed; KeyboardNavigation.SetControlTabNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); KeyboardNavigation.SetDirectionalNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); KeyboardNavigation.SetTabNavigation(this.DropDownPopup, KeyboardNavigationMode.Cycle); } if (this.resizeVerticalThumb != null) { this.resizeVerticalThumb.DragDelta -= this.OnResizeVerticalDelta; } this.resizeVerticalThumb = this.GetTemplateChild("PART_ResizeVerticalThumb") as Thumb; if (this.resizeVerticalThumb != null) { this.resizeVerticalThumb.DragDelta += this.OnResizeVerticalDelta; } if (this.resizeBothThumb != null) { this.resizeBothThumb.DragDelta -= this.OnResizeBothDelta; } this.resizeBothThumb = this.GetTemplateChild("PART_ResizeBothThumb") as Thumb; if (this.resizeBothThumb != null) { this.resizeBothThumb.DragDelta += this.OnResizeBothDelta; } this.scrollViewer = this.GetTemplateChild("PART_ScrollViewer") as ScrollViewer; this.menuPanel = this.GetTemplateChild("PART_MenuPanel") as Panel; } /// <inheritdoc /> protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Escape) { if (this.IsSubmenuOpen) { this.IsSubmenuOpen = false; } else { this.CloseParentDropDownOrMenuItem(); } e.Handled = true; } else { #region Non MenuBase ItemsControl workarounds if (this.IsItemsControlMenuBase == false) { var key = e.Key; if (this.FlowDirection == FlowDirection.RightToLeft) { if (key == Key.Right) { key = Key.Left; } else if (key == Key.Left) { key = Key.Right; } } if (key == Key.Right && this.menuPanel != null) { this.IsSubmenuOpen = true; this.menuPanel.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); e.Handled = true; } else if (key == Key.Left) { if (this.IsSubmenuOpen) { this.IsSubmenuOpen = false; } else { var parentMenuItem = UIHelper.GetParent<System.Windows.Controls.MenuItem>(this); if (parentMenuItem != null) { parentMenuItem.IsSubmenuOpen = false; } } e.Handled = true; } if (e.Handled) { return; } } #endregion Non MenuBase ItemsControl workarounds base.OnKeyDown(e); } } private void CloseParentDropDownOrMenuItem() { var parent = UIHelper.GetParent<DependencyObject>(this, x => x is IDropDownControl || x is System.Windows.Controls.MenuItem); if (parent is null) { return; } if (parent is IDropDownControl dropDown) { dropDown.IsDropDownOpen = false; } else { ((System.Windows.Controls.MenuItem)parent).IsSubmenuOpen = false; } } #endregion #region Methods // Handles resize both drag private void OnResizeBothDelta(object sender, DragDeltaEventArgs e) { if (this.scrollViewer != null) { this.scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; } if (this.menuPanel != null) { if (double.IsNaN(this.menuPanel.Width)) { this.menuPanel.Width = this.menuPanel.ActualWidth; } if (double.IsNaN(this.menuPanel.Height)) { this.menuPanel.Height = this.menuPanel.ActualHeight; } this.menuPanel.Width = Math.Max(this.menuPanel.MinWidth, this.menuPanel.Width + e.HorizontalChange); this.menuPanel.Height = Math.Min(Math.Max(this.menuPanel.MinHeight, this.menuPanel.Height + e.VerticalChange), this.MaxDropDownHeight); } } // Handles resize vertical drag private void OnResizeVerticalDelta(object sender, DragDeltaEventArgs e) { if (this.scrollViewer != null) { this.scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; } if (this.menuPanel != null) { if (double.IsNaN(this.menuPanel.Height)) { this.menuPanel.Height = this.menuPanel.ActualHeight; } this.menuPanel.Height = Math.Min(Math.Max(this.menuPanel.MinHeight, this.menuPanel.Height + e.VerticalChange), this.MaxDropDownHeight); } } // Handles drop down opened private void OnDropDownClosed(object sender, EventArgs e) { this.DropDownClosed?.Invoke(this, e); } // Handles drop down closed private void OnDropDownOpened(object sender, EventArgs e) { if (this.scrollViewer != null && this.ResizeMode != ContextMenuResizeMode.None) { this.scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; } if (this.menuPanel != null) { this.menuPanel.Width = double.NaN; this.menuPanel.Height = double.NaN; } this.DropDownOpened?.Invoke(this, e); } #endregion /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } if (this.Icon != null) { yield return this.Icon; } } } } }
//--------------------------------------------------------------------------- // // <copyright file="Automation.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Facade class that groups together the main functionality that clients need to get started. // // History: // 06/02/2003 : BrendanM Ported to WCP // 07/23/2003 : MKarr removed start and includeStart from FindRawElement and FindLogicalElement // //--------------------------------------------------------------------------- // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 using System.Windows.Automation; using System.Windows.Automation.Provider; using System; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Reflection; using System.Diagnostics; using MS.Internal.Automation; using MS.Win32; namespace System.Windows.Automation { /// <summary> /// Class containing client Automation methods that are not specific to a particular element /// </summary> #if (INTERNAL_COMPILE) internal static class Automation #else public static class Automation #endif { //------------------------------------------------------ // // Public Constants / Readonly Fields // //------------------------------------------------------ #region Public Constants and Readonly Fields /// <summary>Condition that describes the Raw view of the UIAutomation tree</summary> public static readonly Condition RawViewCondition = Condition.TrueCondition; /// <summary>Condition that describes the Control view of the UIAutomation tree</summary> public static readonly Condition ControlViewCondition = new NotCondition( new PropertyCondition( AutomationElement.IsControlElementProperty, false) ); // /// <summary>Condition that describes the Content view of the UIAutomation tree</summary> public static readonly Condition ContentViewCondition = new NotCondition( new OrCondition( new PropertyCondition( AutomationElement.IsControlElementProperty, false), new PropertyCondition( AutomationElement.IsContentElementProperty, false))); #endregion Public Constants and Readonly Fields //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods #region Element Comparisons /// <summary> /// Compares two elements, returning true if both refer to the same piece of UI. /// </summary> /// <param name="el1">element to compare</param> /// <param name="el2">element to compare</param> /// <returns>true if el1 and el2 refer to the same underlying UI</returns> /// <remarks>Both el1 and el1 must be non-null</remarks> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static bool Compare(AutomationElement el1, AutomationElement el2) { return Misc.Compare(el1, el2); } /// <summary> /// Compares two integer arrays, returning true if they have the same contents /// </summary> /// <param name="runtimeId1">integer array to compare</param> /// <param name="runtimeId2">integer array to compare</param> /// <returns>true if runtimeId1 and runtimeId2 refer to the same underlying UI</returns> /// <remarks>Both runtimeId1 and runtimeId2 must be non-null. Can be /// used to compare RuntimeIds from elements.</remarks> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static bool Compare(int[] runtimeId1, int[] runtimeId2) { return Misc.Compare(runtimeId1, runtimeId2); } #endregion Element Comparisons #region Misc: Find, Property Names /// <summary> /// Get string describing specified property idenfier /// </summary> /// <param name="property">property to get string for</param> /// <returns>Sting containing human-readable name of specified property</returns> public static string PropertyName( AutomationProperty property ) { Misc.ValidateArgumentNonNull(property, "property"); // Suppress PRESHARP Parameter to this public method must be validated; element is checked above. #pragma warning suppress 56506 string full = property.ProgrammaticName.Split('.')[1]; // remove portion before the ".", leaving just "NameProperty" or similar return full.Substring(0, full.Length - 8); // Slice away "Property" suffix } /// <summary> /// Get string describing specified pattern idenfier /// </summary> /// <param name="pattern">pattern to get string for</param> /// <returns>Sting containing human-readable name of specified pattern</returns> public static string PatternName( AutomationPattern pattern ) { Misc.ValidateArgumentNonNull(pattern, "pattern"); // Suppress PRESHARP Parameter to this public method must be validated; element is checked above. #pragma warning suppress 56506 string full = pattern.ProgrammaticName; return full.Substring(0, full.Length - 26); // Slice away "InvokePatternIdentifiers.Pattern" to get just "Invoke" } #endregion Misc: Find, Property Names #region Events /// <summary> /// Called by a client to add a listener for pattern or custom events. /// </summary> /// <param name="eventId">A control pattern or custom event identifier.</param> /// <param name="element">Element on which to listen for control pattern or custom events.</param> /// <param name="scope">Specifies whether to listen to property changes events on the specified element, and/or its ancestors and children.</param> /// <param name="eventHandler">Delegate to call when the specified event occurs.</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void AddAutomationEventHandler( AutomationEvent eventId, AutomationElement element, TreeScope scope, AutomationEventHandler eventHandler ) { Misc.ValidateArgumentNonNull(element, "element" ); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); Misc.ValidateArgument( eventId != AutomationElement.AutomationFocusChangedEvent, SRID.EventIdMustNotBeAutomationFocusChanged ); Misc.ValidateArgument( eventId != AutomationElement.StructureChangedEvent,SRID.EventIdMustNotBeStructureChanged ); Misc.ValidateArgument( eventId != AutomationElement.AutomationPropertyChangedEvent, SRID.EventIdMustNotBeAutomationPropertyChanged ); if (eventId == WindowPattern.WindowClosedEvent) { // Once a window closes and the hwnd is destroyed we won't be able to determine where it was in the // Automation tree; therefore only support WindowClosed events for all windows (eg. src==root and scope // is descendants) or a specific WindowPattern element (src==root of a Window and scope is the element). // Also handle odd combinations (eg. src==specific element and scope is subtree|ancestors). bool paramsValidated = false; if ( Misc.Compare( element, AutomationElement.RootElement ) ) { // For root element need to have Descendants scope set (Note: Subtree includes Descendants) if ( ( scope & TreeScope.Descendants ) == TreeScope.Descendants ) { paramsValidated = true; } } else { // otherwise non-root elements must have the entire tree (Anscestors, Element and Descendants)... if ( ( scope & ( TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants ) ) == ( TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants ) ) { paramsValidated = true; } else if ( ( scope & TreeScope.Element ) == TreeScope.Element ) { // ...OR Element where the element implements WindowPattern // PRESHARP will flag this as warning 56506/6506:Parameter 'element' to this public method must be validated: A null-dereference can occur here. // False positive, element is checked, see above #pragma warning suppress 6506 object val = element.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty); if ( val != null && val is int && (int)val != 0 ) { if ( HwndProxyElementProvider.IsWindowPatternWindow( NativeMethods.HWND.Cast( new IntPtr( (int)val ) ) ) ) { paramsValidated = true; } } } } if ( !paramsValidated ) { throw new ArgumentException( SR.Get( SRID.ParamsNotApplicableToWindowClosedEvent ) ); } } // Add a client-side Handler for for this event request EventListener l = new EventListener(eventId, scope, null, CacheRequest.CurrentUiaCacheRequest); ClientEventManager.AddListener(element, eventHandler, l); } /// <summary> /// Called by a client to remove a listener for pattern or custom events. /// </summary> /// <param name="eventId">a UIAccess or custom event identifier.</param> /// <param name="element">Element to remove listener for</param> /// <param name="eventHandler">The handler object that was passed to AddEventListener</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void RemoveAutomationEventHandler( AutomationEvent eventId, AutomationElement element, AutomationEventHandler eventHandler ) { Misc.ValidateArgumentNonNull(element, "element" ); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); Misc.ValidateArgument( eventId != AutomationElement.AutomationFocusChangedEvent, SRID.EventIdMustNotBeAutomationFocusChanged ); Misc.ValidateArgument( eventId != AutomationElement.StructureChangedEvent, SRID.EventIdMustNotBeStructureChanged ); Misc.ValidateArgument( eventId != AutomationElement.AutomationPropertyChangedEvent, SRID.EventIdMustNotBeAutomationPropertyChanged ); //CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Read ); // Remove the client-side listener for for this event ClientEventManager.RemoveListener( eventId, element, eventHandler ); } /// <summary> /// Called by a client to add a listener for property changed events. /// </summary> /// <param name="element">Element on which to listen for property changed events.</param> /// <param name="scope">Specifies whether to listen to property changes events on the specified element, and/or its ancestors and children.</param> /// <param name="eventHandler">Callback object to call when a specified property change occurs.</param> /// <param name="properties">Params array of properties to listen for changes in.</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void AddAutomationPropertyChangedEventHandler( AutomationElement element, // reference element for listening to the event TreeScope scope, // scope to listen to AutomationPropertyChangedEventHandler eventHandler, // callback object params AutomationProperty [] properties // listen for changes to these properties ) { Misc.ValidateArgumentNonNull(element, "element" ); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); Misc.ValidateArgumentNonNull(properties, "properties" ); if (properties.Length == 0) { throw new ArgumentException( SR.Get(SRID.AtLeastOnePropertyMustBeSpecified) ); } // Check that no properties are interpreted properties // foreach (AutomationProperty property in properties) { Misc.ValidateArgumentNonNull(property, "properties" ); } // Add a client-side listener for for this event request EventListener l = new EventListener(AutomationElement.AutomationPropertyChangedEvent, scope, properties, CacheRequest.CurrentUiaCacheRequest); ClientEventManager.AddListener(element, eventHandler, l); } /// <summary> /// Called by a client to remove a listener for property changed events. /// </summary> /// <param name="element">Element to remove listener for</param> /// <param name="eventHandler">The handler object that was passed to AutomationPropertyChangedEventHandler</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void RemoveAutomationPropertyChangedEventHandler( AutomationElement element, // reference element being listened to AutomationPropertyChangedEventHandler eventHandler // callback object (used as cookie here) ) { Misc.ValidateArgumentNonNull(element, "element" ); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); //CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Read ); // Remove the client-side listener for for this event ClientEventManager.RemoveListener(AutomationElement.AutomationPropertyChangedEvent, element, eventHandler); } /// <summary> /// Called by a client to add a listener for structure change events. /// </summary> /// <param name="element">Element on which to listen for structure change events.</param> /// <param name="scope">Specifies whether to listen to property changes events on the specified element, and/or its ancestors and children.</param> /// <param name="eventHandler">Delegate to call when a structure change event occurs.</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void AddStructureChangedEventHandler(AutomationElement element, TreeScope scope, StructureChangedEventHandler eventHandler) { Misc.ValidateArgumentNonNull(element, "element"); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler"); // Add a client-side listener for for this event request EventListener l = new EventListener(AutomationElement.StructureChangedEvent, scope, null, CacheRequest.CurrentUiaCacheRequest); ClientEventManager.AddListener(element, eventHandler, l); } /// <summary> /// Called by a client to remove a listener for structure change events. /// </summary> /// <param name="element">Element to remove listener for</param> /// <param name="eventHandler">The handler object that was passed to AddStructureChangedListener</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void RemoveStructureChangedEventHandler(AutomationElement element, StructureChangedEventHandler eventHandler) { Misc.ValidateArgumentNonNull(element, "element"); Misc.ValidateArgumentNonNull(eventHandler, "eventHandler"); //CASRemoval:AutomationPermission.Demand(AutomationPermissionFlag.Read); // Remove the client-side listener for for this event ClientEventManager.RemoveListener(AutomationElement.StructureChangedEvent, element, eventHandler); } /// <summary> /// Called by a client to add a listener for focus changed events. /// </summary> /// <param name="eventHandler">Delegate to call when a focus change event occurs.</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void AddAutomationFocusChangedEventHandler( AutomationFocusChangedEventHandler eventHandler ) { Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); // Add a client-side listener for for this event request EventListener l = new EventListener(AutomationElement.AutomationFocusChangedEvent, TreeScope.Subtree | TreeScope.Ancestors, null, CacheRequest.CurrentUiaCacheRequest); ClientEventManager.AddFocusListener(eventHandler, l); } /// <summary> /// Called by a client to remove a listener for focus changed events. /// </summary> /// <param name="eventHandler">The handler object that was passed to AddAutomationFocusChangedListener</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void RemoveAutomationFocusChangedEventHandler( AutomationFocusChangedEventHandler eventHandler ) { Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" ); //CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Read ); // Remove the client-side listener for for this event ClientEventManager.RemoveFocusListener(eventHandler); } /// <summary> /// Called by a client to remove all listeners that the client has added. /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public static void RemoveAllEventHandlers() { //CASRemoval:AutomationPermission.Demand( AutomationPermissionFlag.Read ); // Remove the client-side listener for for this event ClientEventManager.RemoveAllListeners(); } #endregion Events #endregion Public Methods } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using Mono.Addins; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Connectors.Hypergrid; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Avatar.Lure { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGLureModule")] public class HGLureModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private readonly List<Scene> m_scenes = new List<Scene>(); private IMessageTransferModule m_TransferModule = null; private bool m_Enabled = false; private string m_ThisGridURL; private ExpiringCache<UUID, GridInstantMessage> m_PendingLures = new ExpiringCache<UUID, GridInstantMessage>(); public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { if (config.Configs["Messaging"].GetString("LureModule", string.Empty) == "HGLureModule") { m_Enabled = true; m_ThisGridURL = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "Messaging" }, String.Empty); // Legacy. Remove soon! m_ThisGridURL = config.Configs["Messaging"].GetString("Gatekeeper", m_ThisGridURL); m_log.DebugFormat("[LURE MODULE]: {0} enabled", Name); } } } public void AddRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Add(scene); scene.EventManager.OnIncomingInstantMessage += OnIncomingInstantMessage; scene.EventManager.OnNewClient += OnNewClient; } } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_TransferModule == null) { m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { m_log.Error("[LURE MODULE]: No message transfer module, lures will not work!"); m_Enabled = false; m_scenes.Clear(); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnIncomingInstantMessage; } } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_scenes) { m_scenes.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnIncomingInstantMessage; } } void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; client.OnStartLure += OnStartLure; client.OnTeleportLureRequest += OnTeleportLureRequest; } public void PostInitialise() { } public void Close() { } public string Name { get { return "HGLureModule"; } } public Type ReplaceableInterface { get { return null; } } void OnInstantMessage(IClientAPI client, GridInstantMessage im) { } void OnIncomingInstantMessage(GridInstantMessage im) { if (im.dialog == (byte)InstantMessageDialog.RequestTeleport || im.dialog == (byte)InstantMessageDialog.GodLikeRequestTeleport) { UUID sessionID = new UUID(im.imSessionID); if (!m_PendingLures.Contains(sessionID)) { m_log.DebugFormat("[HG LURE MODULE]: RequestTeleport sessionID={0}, regionID={1}, message={2}", im.imSessionID, im.RegionID, im.message); m_PendingLures.Add(sessionID, im, 7200); // 2 hours } // Forward. We do this, because the IM module explicitly rejects // IMs of this type if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im, delegate(bool success) { }); } } public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client) { if (!(client.Scene is Scene)) return; Scene scene = (Scene)(client.Scene); ScenePresence presence = scene.GetScenePresence(client.AgentId); message += "@" + m_ThisGridURL; m_log.DebugFormat("[HG LURE MODULE]: TP invite with message {0}", message); UUID sessionID = UUID.Random(); GridInstantMessage m = new GridInstantMessage(scene, client.AgentId, client.FirstName+" "+client.LastName, targetid, (byte)InstantMessageDialog.RequestTeleport, false, message, sessionID, false, presence.AbsolutePosition, new Byte[0], true); m.RegionID = client.Scene.RegionInfo.RegionID.Guid; m_log.DebugFormat("[HG LURE MODULE]: RequestTeleport sessionID={0}, regionID={1}, message={2}", m.imSessionID, m.RegionID, m.message); m_PendingLures.Add(sessionID, m, 7200); // 2 hours if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(m, delegate(bool success) { }); } } public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client) { if (!(client.Scene is Scene)) return; // Scene scene = (Scene)(client.Scene); GridInstantMessage im = null; if (m_PendingLures.TryGetValue(lureID, out im)) { m_PendingLures.Remove(lureID); Lure(client, teleportFlags, im); } else m_log.DebugFormat("[HG LURE MODULE]: pending lure {0} not found", lureID); } private void Lure(IClientAPI client, uint teleportflags, GridInstantMessage im) { Scene scene = (Scene)(client.Scene); GridRegion region = scene.GridService.GetRegionByUUID(scene.RegionInfo.ScopeID, new UUID(im.RegionID)); if (region != null) scene.RequestTeleportLocation(client, region.RegionHandle, im.Position + new Vector3(0.5f, 0.5f, 0f), Vector3.UnitX, teleportflags); else // we don't have that region here. Check if it's HG { string[] parts = im.message.Split(new char[] { '@' }); if (parts.Length > 1) { string url = parts[parts.Length - 1]; // the last part if (url.Trim(new char[] {'/'}) != m_ThisGridURL.Trim(new char[] {'/'})) { m_log.DebugFormat("[HG LURE MODULE]: Luring agent to grid {0} region {1} position {2}", url, im.RegionID, im.Position); GatekeeperServiceConnector gConn = new GatekeeperServiceConnector(); GridRegion gatekeeper = new GridRegion(); gatekeeper.ServerURI = url; GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(im.RegionID)); if (finalDestination != null) { ScenePresence sp = scene.GetScenePresence(client.AgentId); IEntityTransferModule transferMod = scene.RequestModuleInterface<IEntityTransferModule>(); if (transferMod != null && sp != null) transferMod.DoTeleport( sp, gatekeeper, finalDestination, im.Position + new Vector3(0.5f, 0.5f, 0f), Vector3.UnitX, teleportflags); } } } } } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; using tk2dEditor.SpriteCollectionEditor; namespace tk2dEditor.SpriteCollectionEditor { public interface IEditorHost { void OnSpriteCollectionChanged(bool retainSelection); void OnSpriteCollectionSortChanged(); Texture2D GetTextureForSprite(int spriteId); SpriteCollectionProxy SpriteCollection { get; } int InspectorWidth { get; } SpriteView SpriteView { get; } void SelectSpritesFromList(int[] indices); void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds); void Commit(); } public class SpriteCollectionEditorEntry { public enum Type { None, Sprite, SpriteSheet, Font, MaxValue } public string name; public int index; public Type type; public bool selected = false; // list management public int listIndex; // index into the currently active list public int selectionKey; // a timestamp of when the entry was selected, to decide the last selected one } } public class tk2dSpriteCollectionEditorPopup : EditorWindow, IEditorHost { tk2dSpriteCollection _spriteCollection; // internal tmp var SpriteView spriteView; SettingsView settingsView; FontView fontView; SpriteSheetView spriteSheetView; // sprite collection we're editing SpriteCollectionProxy spriteCollectionProxy = null; public SpriteCollectionProxy SpriteCollection { get { return spriteCollectionProxy; } } public SpriteView SpriteView { get { return spriteView; } } // This lists all entries List<SpriteCollectionEditorEntry> entries = new List<SpriteCollectionEditorEntry>(); // This lists all selected entries List<SpriteCollectionEditorEntry> selectedEntries = new List<SpriteCollectionEditorEntry>(); // Callback when a sprite collection is changed and the selection needs to be refreshed public void OnSpriteCollectionChanged(bool retainSelection) { var oldSelection = selectedEntries.ToArray(); PopulateEntries(); if (retainSelection) { searchFilter = ""; // name may have changed foreach (var selection in oldSelection) { foreach (var entry in entries) { if (entry.type == selection.type && entry.index == selection.index) { entry.selected = true; break; } } } UpdateSelection(); } } public void SelectSpritesFromList(int[] indices) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); // Clear selection foreach (var entry in entries) entry.selected = false; // Create new selection foreach (var index in indices) { foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == index) { entry.selected = true; selectedEntries.Add(entry); break; } } } } public void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); foreach (var entry in entries) { entry.selected = (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == spriteSheetId); if (entry.selected) { spriteSheetView.Select(spriteCollectionProxy.spriteSheets[spriteSheetId], spriteIds); } } UpdateSelection(); } void UpdateSelection() { // clear settings view if its selected settingsView.show = false; selectedEntries = (from entry in entries where entry.selected == true orderby entry.selectionKey select entry).ToList(); } void ClearSelection() { entries.ForEach((a) => a.selected = false); UpdateSelection(); } // Callback when a sprite collection needs resorting public static bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; } // Callback when a sort criteria is changed public void OnSpriteCollectionSortChanged() { if (searchFilter.Length > 0) { // re-sort list entries = (from entry in entries where Contains(entry.name, searchFilter) select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } else { // re-sort list entries = (from entry in entries select entry) .OrderBy( e => e.type ) .ThenBy( e => e.name, new tk2dEditor.Shared.NaturalComparer() ) .ToList(); } for (int i = 0; i < entries.Count; ++i) entries[i].listIndex = i; } public int InspectorWidth { get { return tk2dPreferences.inst.spriteCollectionInspectorWidth; } } // populate the entries struct for display in the listbox void PopulateEntries() { entries = new List<SpriteCollectionEditorEntry>(); selectedEntries = new List<SpriteCollectionEditorEntry>(); if (spriteCollectionProxy == null) return; for (int spriteIndex = 0; spriteIndex < spriteCollectionProxy.textureParams.Count; ++spriteIndex) { var sprite = spriteCollectionProxy.textureParams[spriteIndex]; var spriteSourceTexture = sprite.texture; if (spriteSourceTexture == null && sprite.name.Length == 0) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = sprite.name; if (sprite.texture == null) { newEntry.name += " (missing)"; } newEntry.index = spriteIndex; newEntry.type = SpriteCollectionEditorEntry.Type.Sprite; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.spriteSheets.Count; ++i) { var spriteSheet = spriteCollectionProxy.spriteSheets[i]; if (!spriteSheet.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = spriteSheet.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.SpriteSheet; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.fonts.Count; ++i) { var font = spriteCollectionProxy.fonts[i]; if (!font.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = font.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.Font; entries.Add(newEntry); } OnSpriteCollectionSortChanged(); selectedEntries = new List<SpriteCollectionEditorEntry>(); } public void SetGenerator(tk2dSpriteCollection spriteCollection) { this._spriteCollection = spriteCollection; this.firstRun = true; spriteCollectionProxy = new SpriteCollectionProxy(spriteCollection); PopulateEntries(); } public void SetGeneratorAndSelectedSprite(tk2dSpriteCollection spriteCollection, int selectedSprite) { searchFilter = ""; SetGenerator(spriteCollection); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == selectedSprite) { entry.selected = true; break; } } UpdateSelection(); } int cachedSpriteId = -1; Texture2D cachedSpriteTexture = null; // Returns a texture for a given sprite, if the sprite is a region sprite, a new texture is returned public Texture2D GetTextureForSprite(int spriteId) { var param = spriteCollectionProxy.textureParams[spriteId]; if (spriteId != cachedSpriteId) { ClearTextureCache(); cachedSpriteId = spriteId; } if (param.extractRegion) { if (cachedSpriteTexture == null) { var tex = param.texture; cachedSpriteTexture = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { cachedSpriteTexture.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } cachedSpriteTexture.Apply(); } return cachedSpriteTexture; } else { return param.texture; } } void ClearTextureCache() { if (cachedSpriteId != -1) cachedSpriteId = -1; if (cachedSpriteTexture != null) { DestroyImmediate(cachedSpriteTexture); cachedSpriteTexture = null; } } void OnEnable() { if (_spriteCollection != null) { SetGenerator(_spriteCollection); } spriteView = new SpriteView(this); settingsView = new SettingsView(this); fontView = new FontView(this); spriteSheetView = new SpriteSheetView(this); } void OnDisable() { ClearTextureCache(); _spriteCollection = null; } void OnDestroy() { tk2dSpriteThumbnailCache.Done(); tk2dEditorSkin.Done(); } string searchFilter = ""; void DrawToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); // LHS GUILayout.BeginHorizontal(GUILayout.Width(leftBarWidth - 6)); // Create Button GUIContent createButton = new GUIContent("Create"); Rect createButtonRect = GUILayoutUtility.GetRect(createButton, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false)); if (GUI.Button(createButtonRect, createButton, EditorStyles.toolbarDropDown)) { GUIUtility.hotControl = 0; GUIContent[] menuItems = new GUIContent[] { new GUIContent("Sprite Sheet"), new GUIContent("Font") }; EditorUtility.DisplayCustomMenu(createButtonRect, menuItems, -1, delegate(object userData, string[] options, int selected) { switch (selected) { case 0: int addedSpriteSheetIndex = spriteCollectionProxy.FindOrCreateEmptySpriteSheetSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == addedSpriteSheetIndex) entry.selected = true; } UpdateSelection(); break; case 1: if (SpriteCollection.allowMultipleAtlases) { EditorUtility.DisplayDialog("Create Font", "Adding fonts to sprite collections isn't allowed when multi atlas spanning is enabled. " + "Please disable it and try again.", "Ok"); } else { int addedFontIndex = spriteCollectionProxy.FindOrCreateEmptyFontSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Font && entry.index == addedFontIndex) entry.selected = true; } UpdateSelection(); } break; } } , null); } // Filter box GUILayout.Space(8); string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.ExpandWidth(true)); if (newSearchFilter != searchFilter) { searchFilter = newSearchFilter; PopulateEntries(); } if (searchFilter.Length > 0) { if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false))) { searchFilter = ""; PopulateEntries(); } } else { GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap); } GUILayout.EndHorizontal(); // Label if (_spriteCollection != null) GUILayout.Label(_spriteCollection.name); // RHS GUILayout.FlexibleSpace(); // Always in settings view when empty if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { GUILayout.Toggle(true, "Settings", EditorStyles.toolbarButton); } else { bool newSettingsView = GUILayout.Toggle(settingsView.show, "Settings", EditorStyles.toolbarButton); if (newSettingsView != settingsView.show) { ClearSelection(); settingsView.show = newSettingsView; } } if (GUILayout.Button("Revert", EditorStyles.toolbarButton) && spriteCollectionProxy != null) { spriteCollectionProxy.CopyFromSource(); OnSpriteCollectionChanged(false); } if (GUILayout.Button("Commit", EditorStyles.toolbarButton) && spriteCollectionProxy != null) Commit(); GUILayout.EndHorizontal(); } public void Commit() { spriteCollectionProxy.DeleteUnusedData(); spriteCollectionProxy.CopyToTarget(); tk2dSpriteCollectionBuilder.ResetCurrentBuild(); if (!tk2dSpriteCollectionBuilder.Rebuild(_spriteCollection)) { EditorUtility.DisplayDialog("Failed to commit sprite collection", "Please check the console for more details.", "Ok"); } spriteCollectionProxy.CopyFromSource(); } void HandleListKeyboardShortcuts(int controlId) { Event ev = Event.current; if (ev.type == EventType.KeyDown && (GUIUtility.keyboardControl == controlId || GUIUtility.keyboardControl == 0) && entries != null && entries.Count > 0) { int selectedIndex = 0; foreach (var e in entries) { if (e.selected) break; selectedIndex++; } int newSelectedIndex = selectedIndex; switch (ev.keyCode) { case KeyCode.Home: newSelectedIndex = 0; break; case KeyCode.End: newSelectedIndex = entries.Count - 1; break; case KeyCode.UpArrow: newSelectedIndex = Mathf.Max(selectedIndex - 1, 0); break; case KeyCode.DownArrow: newSelectedIndex = Mathf.Min(selectedIndex + 1, entries.Count - 1); break; case KeyCode.PageUp: newSelectedIndex = Mathf.Max(selectedIndex - 10, 0); break; case KeyCode.PageDown: newSelectedIndex = Mathf.Min(selectedIndex + 10, entries.Count - 1); break; } if (newSelectedIndex != selectedIndex) { for (int i = 0; i < entries.Count; ++i) entries[i].selected = (i == newSelectedIndex); UpdateSelection(); Repaint(); ev.Use(); } } } Vector2 spriteListScroll = Vector2.zero; int spriteListSelectionKey = 0; void DrawSpriteList() { if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { DrawDropZone(); return; } int spriteListControlId = GUIUtility.GetControlID("tk2d.SpriteList".GetHashCode(), FocusType.Keyboard); HandleListKeyboardShortcuts(spriteListControlId); spriteListScroll = GUILayout.BeginScrollView(spriteListScroll, GUILayout.Width(leftBarWidth)); bool multiSelectKey = (Application.platform == RuntimePlatform.OSXEditor)?Event.current.command:Event.current.control; bool shiftSelectKey = Event.current.shift; bool selectionChanged = false; SpriteCollectionEditorEntry.Type lastType = SpriteCollectionEditorEntry.Type.None; // Run through the list, measure total height // Its significantly faster with loads of sprites in there. int height = 0; int labelHeight = (int)tk2dEditorSkin.SC_ListBoxSectionHeader.CalcHeight(GUIContent.none, 100); int itemHeight = (int)tk2dEditorSkin.SC_ListBoxItem.CalcHeight(GUIContent.none, 100); int spacing = 8; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) height += spacing; height += labelHeight; lastType = entry.type; } height += itemHeight; } Rect rect = GUILayoutUtility.GetRect(1, height, GUILayout.ExpandWidth(true)); int width = Mathf.Max((int)rect.width, 100); int y = 0; // Second pass, just draw what is visible // Don't care about the section labels, theres only a max of 4 of those. lastType = SpriteCollectionEditorEntry.Type.None; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) y += spacing; else GUI.SetNextControlName("firstLabel"); GUI.Label(new Rect(0, y, width, labelHeight), GetEntryTypeString(entry.type), tk2dEditorSkin.SC_ListBoxSectionHeader); y += labelHeight; lastType = entry.type; } bool newSelected = entry.selected; float realY = y - spriteListScroll.y + itemHeight; if (realY > 0 && realY < Screen.height) { // screen.height is wrong, but is conservative newSelected = GUI.Toggle(new Rect(0, y, width, itemHeight), entry.selected, entry.name, tk2dEditorSkin.SC_ListBoxItem); } y += itemHeight; if (newSelected != entry.selected) { GUI.FocusControl("firstLabel"); entry.selectionKey = spriteListSelectionKey++; if (multiSelectKey) { // Only allow multiselection with sprites bool selectionAllowed = entry.type == SpriteCollectionEditorEntry.Type.Sprite; foreach (var e in entries) { if (e != entry && e.selected && e.type != entry.type) { selectionAllowed = false; break; } } if (selectionAllowed) { entry.selected = newSelected; selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } else if (shiftSelectKey) { // find first selected entry in list int firstSelection = int.MaxValue; foreach (var e in entries) { if (e.selected && e.listIndex < firstSelection) { firstSelection = e.listIndex; } } int lastSelection = entry.listIndex; if (lastSelection < firstSelection) { lastSelection = firstSelection; firstSelection = entry.listIndex; } // Filter for multiselection if (entry.type == SpriteCollectionEditorEntry.Type.Sprite) { for (int i = firstSelection; i <= lastSelection; ++i) { if (entries[i].type != entry.type) { firstSelection = entry.listIndex; lastSelection = entry.listIndex; } } } else { firstSelection = lastSelection = entry.listIndex; } foreach (var e in entries) { e.selected = (e.listIndex >= firstSelection && e.listIndex <= lastSelection); } selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } } if (selectionChanged) { GUIUtility.keyboardControl = spriteListControlId; UpdateSelection(); Repaint(); } GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); tk2dPreferences.inst.spriteCollectionListWidth = (int)tk2dGuiUtility.DragableHandle(4819283, viewRect, tk2dPreferences.inst.spriteCollectionListWidth, tk2dGuiUtility.DragDirection.Horizontal); } bool IsValidDragPayload() { int idx = 0; foreach (var v in DragAndDrop.objectReferences) { var type = v.GetType(); if (type == typeof(Texture2D)) return true; else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[idx])) return true; ++idx; } return false; } string GetEntryTypeString(SpriteCollectionEditorEntry.Type kind) { switch (kind) { case SpriteCollectionEditorEntry.Type.Sprite: return "Sprites"; case SpriteCollectionEditorEntry.Type.SpriteSheet: return "Sprite Sheets"; case SpriteCollectionEditorEntry.Type.Font: return "Fonts"; } Debug.LogError("Unhandled type"); return ""; } bool PromptImportDuplicate(string title, string message) { return EditorUtility.DisplayDialog(title, message, "Ignore", "Create Copy"); } void HandleDroppedPayload(Object[] objects) { bool hasDuplicates = false; foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if (tex != null) { if (spriteCollectionProxy.FindSpriteBySource(tex) != -1) { hasDuplicates = true; } } } bool cloneDuplicates = false; if (hasDuplicates && EditorUtility.DisplayDialog("Duplicate textures detected.", "One or more textures is already in the collection. What do you want to do with the duplicates?", "Clone", "Ignore")) { cloneDuplicates = true; } List<int> addedIndices = new List<int>(); foreach (var obj in objects) { Texture2D tex = obj as Texture2D; if ((tex != null) && (cloneDuplicates || spriteCollectionProxy.FindSpriteBySource(tex) == -1)) { string name = spriteCollectionProxy.FindUniqueTextureName(tex.name); int slot = spriteCollectionProxy.FindOrCreateEmptySpriteSlot(); spriteCollectionProxy.textureParams[slot].name = name; spriteCollectionProxy.textureParams[slot].colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; spriteCollectionProxy.textureParams[slot].texture = (Texture2D)obj; addedIndices.Add(slot); } } // And now select them searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && addedIndices.IndexOf(entry.index) != -1) entry.selected = true; } UpdateSelection(); } // recursively find textures in path List<Object> AddTexturesInPath(string path) { List<Object> localObjects = new List<Object>(); foreach (var q in System.IO.Directory.GetFiles(path)) { string f = q.Replace('\\', '/'); System.IO.FileInfo fi = new System.IO.FileInfo(f); if (fi.Extension.ToLower() == ".meta") continue; Object obj = AssetDatabase.LoadAssetAtPath(f, typeof(Texture2D)); if (obj != null) localObjects.Add(obj); } foreach (var q in System.IO.Directory.GetDirectories(path)) { string d = q.Replace('\\', '/'); localObjects.AddRange(AddTexturesInPath(d)); } return localObjects; } int leftBarWidth { get { return tk2dPreferences.inst.spriteCollectionListWidth; } } Object[] deferredDroppedObjects; void DrawDropZone() { GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.Width(leftBarWidth), GUILayout.ExpandHeight(true)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (DragAndDrop.objectReferences.Length == 0 && !SpriteCollection.Empty) GUILayout.Label("Drop sprite here", tk2dEditorSkin.SC_DropBox); else GUILayout.Label("Drop sprites here", tk2dEditorSkin.SC_DropBox); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); Rect rect = new Rect(0, 0, leftBarWidth, Screen.height); if (rect.Contains(Event.current.mousePosition)) { switch (Event.current.type) { case EventType.DragUpdated: if (IsValidDragPayload()) DragAndDrop.visualMode = DragAndDropVisualMode.Copy; else DragAndDrop.visualMode = DragAndDropVisualMode.None; break; case EventType.DragPerform: var droppedObjectsList = new List<Object>(); for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i) { var type = DragAndDrop.objectReferences[i].GetType(); if (type == typeof(Texture2D)) droppedObjectsList.Add(DragAndDrop.objectReferences[i]); else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[i])) droppedObjectsList.AddRange(AddTexturesInPath(DragAndDrop.paths[i])); } deferredDroppedObjects = droppedObjectsList.ToArray(); Repaint(); break; } } } bool dragging = false; bool currentDraggingValue = false; bool firstRun = true; List<UnityEngine.Object> assetsInResources = new List<UnityEngine.Object>(); bool InResources(UnityEngine.Object obj) { return AssetDatabase.GetAssetPath(obj).ToLower().IndexOf("/resources/") != -1; } void CheckForAssetsInResources() { assetsInResources.Clear(); foreach (tk2dSpriteCollectionDefinition tex in SpriteCollection.textureParams) { if (tex.texture == null) continue; if (InResources(tex.texture) && assetsInResources.IndexOf(tex.texture) == -1) assetsInResources.Add(tex.texture); } foreach (tk2dSpriteCollectionFont font in SpriteCollection.fonts) { if (font.texture != null && InResources(font.texture) && assetsInResources.IndexOf(font.texture) == -1) assetsInResources.Add(font.texture); if (font.bmFont != null && InResources(font.bmFont) && assetsInResources.IndexOf(font.bmFont) == -1) assetsInResources.Add(font.bmFont); } } Vector2 assetWarningScroll = Vector2.zero; bool HandleAssetsInResources() { if (firstRun && SpriteCollection != null) { CheckForAssetsInResources(); firstRun = false; } if (assetsInResources.Count > 0) { tk2dGuiUtility.InfoBox("Warning: The following assets are in one or more resources directories.\n" + "These files will be included in the build.", tk2dGuiUtility.WarningLevel.Warning); assetWarningScroll = GUILayout.BeginScrollView(assetWarningScroll, GUILayout.ExpandWidth(true)); foreach (UnityEngine.Object obj in assetsInResources) { EditorGUILayout.ObjectField(obj, typeof(UnityEngine.Object), false); } GUILayout.EndScrollView(); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Ok", GUILayout.MinWidth(100))) { assetsInResources.Clear(); Repaint(); } GUILayout.EndHorizontal(); return true; } return false; } void OnGUI() { if (Event.current.type == EventType.DragUpdated) { if (IsValidDragPayload()) dragging = true; } else if (Event.current.type == EventType.DragExited) { dragging = false; Repaint(); } else { if (currentDraggingValue != dragging) { currentDraggingValue = dragging; } } if (Event.current.type == EventType.Layout && deferredDroppedObjects != null) { HandleDroppedPayload(deferredDroppedObjects); deferredDroppedObjects = null; } if (HandleAssetsInResources()) return; GUILayout.BeginVertical(); DrawToolbar(); GUILayout.BeginHorizontal(); if (currentDraggingValue) DrawDropZone(); else DrawSpriteList(); if (settingsView.show || (spriteCollectionProxy != null && spriteCollectionProxy.Empty)) settingsView.Draw(); else if (fontView.Draw(selectedEntries)) { } else if (spriteSheetView.Draw(selectedEntries)) { } else spriteView.Draw(selectedEntries); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
// 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 BlendInt164() { var test = new ImmBinaryOpTest__BlendInt164(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__BlendInt164 { private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendInt164 testClass) { var result = Avx2.Blend(_fld1, _fld2, 4); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable; static ImmBinaryOpTest__BlendInt164() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmBinaryOpTest__BlendInt164() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Blend( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Blend( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendInt164(); var result = Avx2.Blend(test._fld1, test._fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((4 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((i < 8) ? (((4 & (1 << i)) == 0) ? left[i] : right[i]) : (((4 & (1 << (i - 8))) == 0) ? left[i] : right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int16>(Vector256<Int16>.4, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenSim.Region.Physics.Manager; using ProtoBuf; namespace InWorldz.PhysxPhysics { /// <summary> /// Describes a material that prims can be made out of /// </summary> [ProtoContract] public class Material : IMaterial, IDisposable { public const int NO_PRESET = -1; private const float GRAVITY_MULTIPLIER_DEFAULT = 1.0f; public static Material GROUND; public static Material STONE; public static Material METAL; public static Material GLASS; public static Material WOOD; public static Material FLESH; public static Material PLASTIC; public static Material RUBBER; private static Material[] MaterialsByOMVEnum; private PhysX.Material _baseMaterial = null; private float _serializedStaticFriction; private float _serializedDynamicFriction; private float _serializedRestitution; public bool IsShared { get; set; } [ProtoMember(1)] public int MaterialPreset { get; set; } [ProtoMember(2)] public float Density { get; set; } [ProtoMember(3)] public float StaticFriction { get { if (_baseMaterial != null) return _baseMaterial.StaticFriction; else return _serializedStaticFriction; } set { _serializedStaticFriction = value; } } [ProtoMember(4)] public float DynamicFriction { get { if (_baseMaterial != null) return _baseMaterial.DynamicFriction; else return _serializedDynamicFriction; } set { _serializedDynamicFriction = value; } } [ProtoMember(5)] public float Restitution { get { if (_baseMaterial != null) return _baseMaterial.Restitution; else return _serializedRestitution; } set { _serializedRestitution = value; } } [ProtoMember(6)] public float GravityMultiplier { get; set; } public PhysX.Material PhyMaterial { get { return _baseMaterial; } } private bool _disposed = false; public static void BuiltinMaterialInit(PhysX.Physics physics) { // PhysX collision forces are very strong, so the ground restitution needs to be lowered significantly. GROUND = new Material(physics.CreateMaterial(0.4f, 0.35f, 0.05f), 1200.0f); GROUND.IsShared = true; // For navigable roads, people need a preset that acts mostly like ground. STONE = new Material(physics.CreateMaterial(0.5f, 0.35f, 0.05f), 2400.0f, (int)OpenMetaverse.Material.Stone); STONE.IsShared = true; METAL = new Material(physics.CreateMaterial(0.3f, 0.25f, 0.4f), 2700.0f, (int)OpenMetaverse.Material.Metal); METAL.IsShared = true; GLASS = new Material(physics.CreateMaterial(0.2f, 0.15f, 0.7f), 2500.0f, (int)OpenMetaverse.Material.Glass); GLASS.IsShared = true; WOOD = new Material(physics.CreateMaterial(0.6f, 0.55f, 0.5f), 1000.0f, (int)OpenMetaverse.Material.Wood); WOOD.IsShared = true; FLESH = new Material(physics.CreateMaterial(0.9f, 0.8f, 0.3f), 1400.0f, (int)OpenMetaverse.Material.Flesh); FLESH.IsShared = true; PLASTIC = new Material(physics.CreateMaterial(0.4f, 0.35f, 0.7f), 900.0f, (int)OpenMetaverse.Material.Plastic); PLASTIC.IsShared = true; RUBBER = new Material(physics.CreateMaterial(0.9f, 0.87f, 0.9f), 1100.0f, (int)OpenMetaverse.Material.Rubber); RUBBER.IsShared = true; MaterialsByOMVEnum = new Material[] { STONE, //0... METAL, GLASS, WOOD, FLESH, PLASTIC, RUBBER, WOOD //light.. which makes no sense is remapped to wood }; } internal static IMaterial FindImpl(OpenMetaverse.Material materialEnum) { return MaterialsByOMVEnum[OpenSim.Framework.Util.Clamp<int>((int)materialEnum, 0, MaterialsByOMVEnum.Length - 1)]; } /// <summary> /// Used by serialization /// </summary> public Material() { //any defaults that may not end up getting set during deserialization of old data must //be set here or at their respective property initializer //set the GM default GravityMultiplier = GRAVITY_MULTIPLIER_DEFAULT; } public Material(PhysX.Material baseMaterial, float density) { _baseMaterial = baseMaterial; Density = density; GravityMultiplier = GRAVITY_MULTIPLIER_DEFAULT; MaterialPreset = NO_PRESET; } public Material(PhysX.Material baseMaterial, float density, float gravityMultiplier) { _baseMaterial = baseMaterial; Density = density; GravityMultiplier = gravityMultiplier; MaterialPreset = NO_PRESET; } public Material(PhysX.Material baseMaterial, float density, int materialPreset) : this(baseMaterial, density, GRAVITY_MULTIPLIER_DEFAULT) { MaterialPreset = materialPreset; } public Material(PhysX.Physics physics, float staticFriction, float dynamicFriction, float restitution, float density, float gravityMultiplier) { _baseMaterial = physics.CreateMaterial(staticFriction, dynamicFriction, restitution); Density = density; GravityMultiplier = gravityMultiplier; } public Material(PhysX.Physics physics, float staticFriction, float dynamicFriction, float restitution, float density) { _baseMaterial = physics.CreateMaterial(staticFriction, dynamicFriction, restitution); Density = density; GravityMultiplier = GRAVITY_MULTIPLIER_DEFAULT; } public Material(PhysX.Physics physics, float staticFriction, float dynamicFriction, float restitution, float density, OpenMetaverse.Material presetNumber) : this(physics, staticFriction, dynamicFriction, restitution, density, GRAVITY_MULTIPLIER_DEFAULT) { MaterialPreset = (int)presetNumber; } public void Dispose() { if (!_disposed) { _baseMaterial.Dispose(); _disposed = true; } } public void CheckedDispose() { if (!IsShared) { this.Dispose(); } } public Material ToLocalMaterial(PhysX.Physics physics) { if (this.MaterialPreset != NO_PRESET) { return (Material)FindImpl((OpenMetaverse.Material)this.MaterialPreset); } else { _baseMaterial = physics.CreateMaterial(_serializedStaticFriction, _serializedDynamicFriction, _serializedRestitution); return this; } } public Material Duplicate(PhysX.Physics physics) { if (this.MaterialPreset != NO_PRESET) { return (Material)FindImpl((OpenMetaverse.Material)this.MaterialPreset); } else { PhysX.Material baseMaterial = physics.CreateMaterial(StaticFriction, DynamicFriction, Restitution); return new Material(baseMaterial, Density, GravityMultiplier); } } } }
using System; using Avalonia; using Avalonia.Media; namespace AvaloniaEdit.Text { internal sealed class TextLineRun { private const string NewlineString = "\r\n"; internal const double BaselineFactor = 0.1; internal const double HeightFactor = 1.2; private FormattedText _formattedText; private Size _formattedTextSize; private double[] _glyphWidths; public StringRange StringRange { get; private set; } public int Length { get; set; } public double Width { get; private set; } public TextRun TextRun { get; private set; } public bool IsEnd { get; private set; } public bool IsTab { get; private set; } public bool IsEmbedded { get; private set; } public double Baseline => IsEnd ? 0.0 : FontSize * BaselineFactor; public double Height => IsEnd ? 0.0 : FontSize * HeightFactor; public string Typeface => TextRun.Properties.Typeface; public double FontSize => TextRun.Properties.FontSize; private TextLineRun() { } public static TextLineRun Create(TextSource textSource, int index, int firstIndex, double lengthLeft) { var textRun = textSource.GetTextRun(index); var stringRange = textRun.GetStringRange(); return Create(textSource, stringRange, textRun, index, lengthLeft); } private static TextLineRun Create(TextSource textSource, StringRange stringRange, TextRun textRun, int index, double widthLeft) { if (textRun is TextCharacters) { return CreateRunForEol(textSource, stringRange, textRun, index) ?? CreateRunForText(stringRange, textRun, widthLeft, false, true); } if (textRun is TextEndOfLine) { return new TextLineRun(textRun.Length, textRun) { IsEnd = true }; } if (textRun is TextEmbeddedObject) { return new TextLineRun(textRun.Length, textRun) { IsEmbedded = true, _glyphWidths = new double[textRun.Length] }; } throw new NotSupportedException("Unsupported run type"); } private static TextLineRun CreateRunForEol(TextSource textSource, StringRange stringRange, TextRun textRun, int index) { switch (stringRange[0]) { case '\r': var runLength = 1; if (stringRange.Length > 1 && stringRange[1] == '\n') { runLength = 2; } else if (stringRange.Length == 1) { var nextRun = textSource.GetTextRun(index + 1); var range = nextRun.GetStringRange(); if (range.Length > 0 && range[0] == '\n') { var eolRun = new TextCharacters(NewlineString, textRun.Properties); return new TextLineRun(eolRun.Length, eolRun) { IsEnd = true }; } } return new TextLineRun(runLength, textRun) { IsEnd = true }; case '\n': return new TextLineRun(1, textRun) { IsEnd = true }; case '\t': return CreateRunForTab(textRun); default: return null; } } private static TextLineRun CreateRunForTab(TextRun textRun) { var spaceRun = new TextCharacters(" ", textRun.Properties); var stringRange = spaceRun.StringRange; var run = new TextLineRun(1, spaceRun) { IsTab = true, StringRange = stringRange, // TODO: get from para props Width = 40 }; run.SetGlyphWidths(); return run; } internal static TextLineRun CreateRunForText(StringRange stringRange, TextRun textRun, double widthLeft, bool emergencyWrap, bool breakOnTabs) { var run = new TextLineRun { StringRange = stringRange, TextRun = textRun, Length = textRun.Length }; var formattedText = new FormattedText { Text = stringRange.ToString(), Typeface = new Typeface(run.Typeface, run.FontSize) }; run._formattedText = formattedText; var size = formattedText.Measure(); run._formattedTextSize = size; run.Width = size.Width; run.SetGlyphWidths(); return run; } private TextLineRun(int length, TextRun textRun) { Length = length; TextRun = textRun; } private void SetGlyphWidths() { var result = new double[StringRange.Length]; for (var i = 0; i < StringRange.Length; i++) { // TODO: is there a better way of getting glyph metrics? var size = new FormattedText { Text = StringRange[i].ToString(), Typeface = new Typeface(Typeface, FontSize) }.Measure(); result[i] = size.Width; } _glyphWidths = result; } public void Draw(DrawingContext drawingContext, double x, double y) { if (IsEmbedded) { var embeddedObject = (TextEmbeddedObject)TextRun; embeddedObject.Draw(drawingContext, new Point(x, y)); return; } if (Length <= 0 || IsEnd) { return; } if (_formattedText != null && drawingContext != null) { if (TextRun.Properties.BackgroundBrush != null) { var bounds = new Rect(x, y, _formattedTextSize.Width, _formattedTextSize.Height); drawingContext.FillRectangle(TextRun.Properties.BackgroundBrush, bounds); } drawingContext.DrawText(TextRun.Properties.ForegroundBrush, new Point(x, y), _formattedText); } } public bool UpdateTrailingInfo(TrailingInfo trailing) { if (IsEnd) return true; if (IsTab) return false; var index = Length; if (index > 0 && IsSpace(StringRange[index - 1])) { while (index > 0 && IsSpace(StringRange[index - 1])) { trailing.SpaceWidth += _glyphWidths[index - 1]; index--; trailing.Count++; } return index == 0; } return false; } public double GetDistanceFromCharacter(int index) { if (!IsEnd && !IsTab) { if (index > Length) { index = Length; } double distance = 0; for (var i = 0; i < index; i++) { distance += _glyphWidths[i]; } return distance; } return index > 0 ? Width : 0; } public (int firstIndex, int trailingLength) GetCharacterFromDistance(double distance) { if (IsEnd) return (0, 0); if (Length <= 0) return (0, 0); var index = 0; double width = 0; for (; index < Length; index++) { width = IsTab ? Width / Length : _glyphWidths[index]; if (distance < width) { break; } distance -= width; } return index < Length ? (index, distance > width / 2 ? 1 : 0) : (Length - 1, 1); } private static bool IsSpace(char ch) { return ch == ' ' || ch == '\u00a0'; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Services.Query; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.EntityList { public class PackageDataAdapter { public PackageDataAdapter(EntityReference package, IDataAdapterDependencies dependencies, Func<Guid, Guid, string> getPackageRepositoryUrl, Func<Guid, Guid, string> getPackageVersionUrl, Func<Guid, Guid, string> getPackageImageUrl) { if (package == null) throw new ArgumentNullException("package"); if (dependencies == null) throw new ArgumentNullException("dependencies"); if (getPackageRepositoryUrl == null) throw new ArgumentNullException("getPackageRepositoryUrl"); if (getPackageVersionUrl == null) throw new ArgumentNullException("getPackageVersionUrl"); if (getPackageImageUrl == null) throw new ArgumentNullException("getPackageImageUrl"); Package = package; Dependencies = dependencies; GetPackageRepositoryUrl = getPackageRepositoryUrl; GetPackageVersionUrl = getPackageVersionUrl; GetPackageImageUrl = getPackageImageUrl; } protected IDataAdapterDependencies Dependencies { get; private set; } protected Func<Guid, Guid, string> GetPackageImageUrl { get; private set; } protected Func<Guid, Guid, string> GetPackageRepositoryUrl { get; private set; } protected Func<Guid, Guid, string> GetPackageVersionUrl { get; private set; } protected EntityReference Package { get; private set; } public Package SelectPackage() { var serviceContext = Dependencies.GetServiceContext(); var website = Dependencies.GetWebsite(); var fetch = new Fetch { Version = "1.0", MappingType = MappingType.Logical, Entity = new FetchEntity { Name = Package.LogicalName, Attributes = FetchAttribute.All, Filters = new[] { new Filter { Type = LogicalOperator.And, Conditions = new[] { new Condition("adx_packageid", ConditionOperator.Equal, Package.Id), new Condition("statecode", ConditionOperator.Equal, 0), } } }, Links = new Collection<Link>() } }; AddPackageCategoryJoin(fetch.Entity); AddPackageComponentJoin(fetch.Entity); AddPackageDependencyJoin(fetch.Entity); AddPackageImageJoin(fetch.Entity); AddPackagePublisherJoin(fetch.Entity); AddPackageVersionJoin(fetch.Entity); var entityGrouping = FetchEntities(serviceContext, fetch) .GroupBy(e => e.Id) .FirstOrDefault(); if (entityGrouping == null) { return null; } var entity = entityGrouping.FirstOrDefault(); if (entity == null) { return null; } var versions = GetPackageVersions(entityGrouping, website.Id) .OrderByDescending(e => e.ReleaseDate) .ToArray(); var currentVersion = versions.FirstOrDefault(); if (currentVersion == null) { return null; } PackageImage icon; var images = GetPackageImages(entityGrouping, website.Id, entity.GetAttributeValue<EntityReference>("adx_iconid"), out icon) .OrderBy(e => e.Name) .ToArray(); var packageRepository = entity.GetAttributeValue<EntityReference>("adx_packagerepository"); return new Package { Categories = GetPackageCategories(entityGrouping).ToArray(), Components = GetPackageComponents(entityGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(), ContentUrl = currentVersion.Url, Dependencies = GetPackageDependencies(entityGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(), Description = entity.GetAttributeValue<string>("adx_description"), DisplayName = entity.GetAttributeValue<string>("adx_name"), HideFromPackageListing = entity.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false), Icon = icon, Images = images, OverwriteWarning = entity.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false), PublisherName = entity.GetAttributeAliasedValue<string>("adx_name", "publisher"), ReleaseDate = currentVersion.ReleaseDate, RequiredInstallerVersion = currentVersion.RequiredInstallerVersion, Summary = entity.GetAttributeValue<string>("adx_summary"), Type = GetPackageType(entity.GetAttributeValue<OptionSetValue>("adx_type")), UniqueName = entity.GetAttributeValue<string>("adx_uniquename"), Uri = GetPackageUri(packageRepository, website.Id, entity.GetAttributeValue<string>("adx_uniquename")), Url = null, Version = currentVersion.Version, Versions = versions }; } protected virtual IEnumerable<Entity> FetchEntities(OrganizationServiceContext serviceContext, Fetch fetch) { fetch.PageNumber = 1; while (true) { var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest()); foreach (var entity in response.EntityCollection.Entities) { yield return entity; } if (!response.EntityCollection.MoreRecords) { break; } fetch.PageNumber++; } } private IEnumerable<PackageCategory> GetPackageCategories(IGrouping<Guid, Entity> entityGrouping) { return entityGrouping .GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagecategoryid", "category")) .Where(e => e.Key != null) .Select(e => e.FirstOrDefault()) .Where(e => e != null) .Select(e => e.GetAttributeAliasedValue<string>("adx_name", "category")) .Where(e => !string.IsNullOrWhiteSpace(e)) .Select(e => new PackageCategory(e)) .Distinct(new PackageCategoryComparer()) .OrderBy(e => e.Name); } private IEnumerable<PackageComponent> GetPackageComponents(IGrouping<Guid, Entity> entityGrouping, EntityReference website, EntityReference packageRepository) { var groupings = entityGrouping .GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagecomponentid", "component")) .Where(e => e.Key != null); foreach (var grouping in groupings) { var entity = grouping.FirstOrDefault(); if (entity == null) { continue; } var packageDisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "componentpackage"); if (string.IsNullOrWhiteSpace(packageDisplayName)) { continue; } var packageUniqueName = entity.GetAttributeAliasedValue<string>("adx_uniquename", "componentpackage"); if (string.IsNullOrWhiteSpace(packageUniqueName)) { continue; } var componentPackageRepository = entity.GetAttributeAliasedValue<EntityReference>("adx_packagerepositoryid", "componentpackage"); yield return new PackageComponent { DisplayName = packageDisplayName, Uri = GetPackageUri(componentPackageRepository, website.Id, packageUniqueName), Version = entity.GetAttributeAliasedValue<string>("adx_version", "component"), Order = entity.GetAttributeAliasedValue<int?>("adx_order", "component").GetValueOrDefault(0), CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "component").GetValueOrDefault() }; } } private IEnumerable<PackageDependency> GetPackageDependencies(IGrouping<Guid, Entity> entityGrouping, EntityReference website, EntityReference packageRepository) { var groupings = entityGrouping .GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packagedependencyid", "dependency")) .Where(e => e.Key != null); foreach (var grouping in groupings) { var entity = grouping.FirstOrDefault(); if (entity == null) { continue; } var packageDisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "dependencypackage"); var packageUniqueName = entity.GetAttributeAliasedValue<string>("adx_uniquename", "dependencypackage"); if (!string.IsNullOrWhiteSpace(packageDisplayName) && !string.IsNullOrWhiteSpace(packageUniqueName)) { var dependencyPackageRepository = entity.GetAttributeAliasedValue<EntityReference>("adx_packagerepositoryid", "dependencypackage"); yield return new PackageDependency { DisplayName = packageDisplayName, Uri = GetPackageUri(dependencyPackageRepository, website.Id, packageUniqueName), Version = entity.GetAttributeAliasedValue<string>("adx_version", "dependency"), Order = entity.GetAttributeAliasedValue<int?>("adx_order", "dependency").GetValueOrDefault(0), CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "dependency").GetValueOrDefault() }; continue; } var packageUri = entity.GetAttributeAliasedValue<string>("adx_dependencypackageuri", "dependency"); Uri parsed; if (!string.IsNullOrWhiteSpace(packageUri) && Uri.TryCreate(packageUri, UriKind.RelativeOrAbsolute, out parsed)) { yield return new PackageDependency { DisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "dependency"), Uri = parsed, Version = entity.GetAttributeAliasedValue<string>("adx_version", "dependency"), Order = entity.GetAttributeAliasedValue<int?>("adx_order", "dependency").GetValueOrDefault(0), CreatedOn = entity.GetAttributeAliasedValue<DateTime?>("createdon", "dependency").GetValueOrDefault() }; } } } private Uri GetPackageUri(EntityReference packageRepository, Guid websiteId, string packageUniqueName) { if (packageRepository == null) { return new Uri("#" + packageUniqueName, UriKind.Relative); } var repositoryUrl = GetPackageRepositoryUrl(websiteId, packageRepository.Id); return repositoryUrl == null ? new Uri("#" + packageUniqueName, UriKind.Relative) : new Uri(repositoryUrl + "#" + packageUniqueName, UriKind.RelativeOrAbsolute); } private IEnumerable<PackageImage> GetPackageImages(IGrouping<Guid, Entity> entityGrouping, Guid websiteId, EntityReference iconReference, out PackageImage icon) { icon = null; var images = new List<PackageImage>(); var groupings = entityGrouping .GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packageimageid", "image")) .Where(e => e.Key != null); foreach (var grouping in groupings) { var entity = grouping.FirstOrDefault(); if (entity == null) { continue; } var imageId = entity.GetAttributeAliasedValue<Guid?>("adx_packageimageid", "image"); if (imageId == null) { continue; } var image = new PackageImage { Name = entity.GetAttributeAliasedValue<string>("adx_name", "image"), Description = entity.GetAttributeAliasedValue<string>("adx_description", "image") ?? entity.GetAttributeAliasedValue<string>("adx_name", "image"), Url = GetPackageImageUrl(websiteId, imageId.Value) }; if (iconReference != null && iconReference.Id == imageId) { icon = image; } else { images.Add(image); } } return images; } private PackageType GetPackageType(OptionSetValue type) { if (type == null) { return PackageType.Solution; } if (type.Value == (int)PackageType.Data) { return PackageType.Data; } return PackageType.Solution; } private IEnumerable<PackageVersion> GetPackageVersions(IGrouping<Guid, Entity> entityGrouping, Guid websiteId) { var groupings = entityGrouping .GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version")) .Where(e => e.Key != null); foreach (var grouping in groupings) { var entity = grouping.FirstOrDefault(); if (entity == null) { continue; } var versionId = entity.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version"); if (versionId == null) { continue; } yield return new PackageVersion { Description = entity.GetAttributeAliasedValue<string>("adx_description", "version"), DisplayName = entity.GetAttributeAliasedValue<string>("adx_name", "version"), ReleaseDate = entity.GetAttributeAliasedValue<DateTime?>("adx_releasedate", "version").GetValueOrDefault(), RequiredInstallerVersion = entity.GetAttributeAliasedValue<string>("adx_requiredinstallerversion", "version"), Url = GetPackageVersionUrl(websiteId, versionId.Value), Version = entity.GetAttributeAliasedValue<string>("adx_version", "version"), }; } } protected virtual void AddPackageCategoryJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Name = "adx_package_packagecategory", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.LeftOuter, Links = new[] { new Link { Alias = "category", Name = "adx_packagecategory", FromAttribute = "adx_packagecategoryid", ToAttribute = "adx_packagecategoryid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packagecategoryid"), new FetchAttribute("adx_name"), }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } } } }); } protected virtual void AddPackageComponentJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Alias = "component", Name = "adx_packagecomponent", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packagecomponentid"), new FetchAttribute("adx_name"), new FetchAttribute("adx_packageid"), new FetchAttribute("adx_componentpackageid"), new FetchAttribute("adx_version"), new FetchAttribute("adx_order"), new FetchAttribute("createdon"), }, Links = new[] { new Link { Alias = "componentpackage", Name = "adx_package", FromAttribute = "adx_packageid", ToAttribute = "adx_componentpackageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packageid"), new FetchAttribute("adx_name"), new FetchAttribute("adx_uniquename"), new FetchAttribute("adx_packagerepositoryid") }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } } }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } }); } protected virtual void AddPackageDependencyJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Alias = "dependency", Name = "adx_packagedependency", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packagedependencyid"), new FetchAttribute("adx_name"), new FetchAttribute("adx_packageid"), new FetchAttribute("adx_dependencypackageid"), new FetchAttribute("adx_dependencypackageuri"), new FetchAttribute("adx_version"), new FetchAttribute("adx_order"), new FetchAttribute("createdon"), }, Links = new[] { new Link { Alias = "dependencypackage", Name = "adx_package", FromAttribute = "adx_packageid", ToAttribute = "adx_dependencypackageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packageid"), new FetchAttribute("adx_name"), new FetchAttribute("adx_uniquename"), new FetchAttribute("adx_packagerepositoryid") }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } } }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } }); } protected virtual void AddPackageImageJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Alias = "image", Name = "adx_packageimage", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packageimageid"), new FetchAttribute("adx_name"), new FetchAttribute("adx_description"), }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } }); } protected virtual void AddPackagePublisherJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Alias = "publisher", Name = "adx_packagepublisher", FromAttribute = "adx_packagepublisherid", ToAttribute = "adx_publisherid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_name"), new FetchAttribute("adx_uniquename"), } }); } protected virtual void AddPackageVersionJoin(FetchEntity fetchEntity) { fetchEntity.Links.Add(new Link { Alias = "version", Name = "adx_packageversion", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.LeftOuter, Attributes = new[] { new FetchAttribute("adx_packageversionid"), new FetchAttribute("adx_description"), new FetchAttribute("adx_name"), new FetchAttribute("adx_packageid"), new FetchAttribute("adx_releasedate"), new FetchAttribute("adx_version"), new FetchAttribute("adx_requiredinstallerversion") }, Filters = new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) } } } }); } protected virtual void AddPackageCategoryFilter(FetchEntity fetchEntity, string category) { if (string.IsNullOrWhiteSpace(category)) { return; } fetchEntity.Links.Add(new Link { Name = "adx_package_packagecategory", FromAttribute = "adx_packageid", ToAttribute = "adx_packageid", Type = JoinOperator.Inner, Links = new[] { new Link { Name = "adx_packagecategory", FromAttribute = "adx_packagecategoryid", ToAttribute = "adx_packagecategoryid", Type = JoinOperator.Inner, Filters = new[] { new Filter { Type = LogicalOperator.And, Conditions = new[] { new Condition("adx_name", ConditionOperator.Equal, category), new Condition("statecode", ConditionOperator.Equal, 0) } } } } } }); } protected class PackageCategoryComparer : IEqualityComparer<PackageCategory> { public bool Equals(PackageCategory x, PackageCategory y) { return StringComparer.InvariantCultureIgnoreCase.Equals(x.Name, y.Name); } public int GetHashCode(PackageCategory category) { return category.Name.GetHashCode(); } } } }
// 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ObjectCreationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> C() { } void Foo() { C c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class C { void foo() { var c = [|new C($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParameters() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnLambda() { var markup = @" using System; class C { void foo() { var bar = [|new Action<int, int>($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(b: string.Empty, $$a: 2|]); } }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2,$$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2, $$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAlways() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableNever() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Constructor_BrowsableMixed() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(long y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif void foo() { var x = new D($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif #if BAR void foo() { var x = new D($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // new foo($$"; await TestAsync(markup); } [WorkItem(1078993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078993")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestSigHelpInIncorrectObjectCreationExpression() { var markup = @" class C { void foo(C c) { foo([|new C{$$|] } }"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss1() { var markup = @" class C { public C(object o) { } public C M() { return [|new C(($$) |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss2() { var markup = @" class C { public C(object o) { } public C M() { return [|new C((1,$$) |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss3() { var markup = @" class C { public C(object o) { } public C M() { return [|new C((1, ($$) |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss4() { var markup = @" class C { public C(object o) { } public C M() { return [|new C((1, (2,$$) |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } } }
// // SqlitePclRawStorageEngine.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2014 Couchbase Inc. // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Threading.Tasks; using Couchbase.Lite.Storage; using System.Threading; using SQLitePCL; using Couchbase.Lite.Util; using System.Diagnostics; using System.Text; using System.Collections.Generic; using System.Linq; using SQLitePCL.Ugly; using Couchbase.Lite.Store; #if !NET_3_5 using StringEx = System.String; #endif namespace Couchbase.Lite { internal sealed class SqlitePCLRawStorageEngine : ISQLiteStorageEngine, IDisposable { // NOTE: SqlitePCL.raw only defines a subset of the ones we want, // so we just redefine them here instead. private const int SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN = 0x00200000; private const int SQLITE_OPEN_READONLY = 0x00000001; private const int SQLITE_OPEN_READWRITE = 0x00000002; private const int SQLITE_OPEN_CREATE = 0x00000004; private const int SQLITE_OPEN_FULLMUTEX = 0x00010000; private const int SQLITE_OPEN_NOMUTEX = 0x00008000; private const int SQLITE_OPEN_PRIVATECACHE = 0x00040000; private const int SQLITE_OPEN_SHAREDCACHE = 0x00020000; private const String Tag = "SqlitePCLRawStorageEngine"; private sqlite3 _writeConnection; private sqlite3 _readConnection; private Boolean shouldCommit; private string Path { get; set; } private TaskFactory Factory { get; set; } private CancellationTokenSource _cts = new CancellationTokenSource(); #region implemented abstract members of SQLiteStorageEngine public bool Open(String path) { if (IsOpen) return true; Path = path; Factory = new TaskFactory(new SingleThreadScheduler()); var result = true; try { Log.I(Tag, "Sqlite Version: {0}".Fmt(raw.sqlite3_libversion())); shouldCommit = false; const int writer_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; OpenSqliteConnection(writer_flags, out _writeConnection); const int reader_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; OpenSqliteConnection(reader_flags, out _readConnection); } catch (Exception ex) { Log.E(Tag, "Error opening the Sqlite connection using connection String: {0}".Fmt(path), ex); result = false; } return result; } void OpenSqliteConnection(int flags, out sqlite3 db) { var status = raw.sqlite3_open_v2(Path, out db, flags, null); if (status != raw.SQLITE_OK) { Path = null; var errMessage = "Cannot open Sqlite Database at pth {0}".Fmt(Path); throw new CouchbaseLiteException(errMessage, StatusCode.DbError); } #if !__ANDROID__ && !NET_3_5 && VERBOSE var i = 0; var val = raw.sqlite3_compileoption_get(i); while (val != null) { Log.V(Tag, "Sqlite Config: {0}".Fmt(val)); val = raw.sqlite3_compileoption_get(++i); } #endif raw.sqlite3_create_collation(db, "JSON", null, CouchbaseSqliteJsonUnicodeCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_ASCII", null, CouchbaseSqliteJsonAsciiCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_RAW", null, CouchbaseSqliteJsonRawCollationFunction.Compare); raw.sqlite3_create_collation(db, "REVID", null, CouchbaseSqliteRevIdCollationFunction.Compare); } public Int32 GetVersion() { const string commandText = "PRAGMA user_version;"; sqlite3_stmt statement; //NOTE.JHB Even though this is a read, iOS doesn't return the correct value on the read connection //but someone should try again when the version goes beyond 3.7.13 statement = BuildCommand (_writeConnection, commandText, null); var result = -1; try { var commandResult = raw.sqlite3_step(statement); if (commandResult != raw.SQLITE_ERROR) { Debug.Assert(commandResult == raw.SQLITE_ROW); result = raw.sqlite3_column_int(statement, 0); } } catch (Exception e) { Log.E(Tag, "Error getting user version", e); } finally { statement.Dispose(); } return result; } public void SetVersion(Int32 version) { var errMessage = "Unable to set version to {0}".Fmt(version); var commandText = "PRAGMA user_version = ?"; Factory.StartNew(() => { sqlite3_stmt statement = BuildCommand(_writeConnection, commandText, null); if (raw.sqlite3_bind_int(statement, 1, version) == raw.SQLITE_ERROR) throw new CouchbaseLiteException(errMessage, StatusCode.DbError); int result; try { result = statement.step(); if (result != SQLiteResult.OK) throw new CouchbaseLiteException(errMessage, StatusCode.DbError); } catch (Exception e) { Log.E(Tag, "Error getting user version", e); } finally { statement.Dispose(); } }); } public bool IsOpen { get { return _writeConnection != null; } } int transactionCount = 0; public int BeginTransaction() { if (!IsOpen) { Open(Path); } // NOTE.ZJG: Seems like we should really be using TO SAVEPOINT // but this is how Android SqliteDatabase does it, // so I'm matching that for now. var value = Interlocked.Increment(ref transactionCount); if (value == 1) { var t = Factory.StartNew(() => { try { using (var statement = BuildCommand(_writeConnection, "BEGIN IMMEDIATE TRANSACTION", null)) { statement.step_done(); } } catch (Exception e) { Log.E(Tag, "Error BeginTransaction", e); } }); t.Wait(); } return value; } public int EndTransaction() { if (_writeConnection == null) throw new InvalidOperationException("Database is not open."); var count = Interlocked.Decrement(ref transactionCount); if (count > 0) return count; var t = Factory.StartNew(() => { try { if (shouldCommit) { using (var statement = BuildCommand(_writeConnection, "COMMIT", null)) { statement.step_done(); } shouldCommit = false; } else { using (var statement = BuildCommand(_writeConnection, "ROLLBACK", null)) { statement.step_done(); } } } catch (Exception e) { Log.E(Tag, "Error EndTransaction", e); } }); t.Wait(); return 0; } public void SetTransactionSuccessful() { shouldCommit = true; } /// <summary> /// Execute any SQL that changes the database. /// </summary> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public int ExecSQL(String sql, params Object[] paramArgs) { var t = Factory.StartNew(()=> { sqlite3_stmt command = null; try { command = BuildCommand(_writeConnection, sql, paramArgs); var result = command.step(); if (result == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } catch (ugly.sqlite3_exception e) { Log.E(Tag, "Error {0}, {1} executing sql '{2}'".Fmt(e.errcode, _writeConnection.extended_errcode(), sql), e); throw; } finally { if(command != null) { command.Dispose(); } } }, _cts.Token); try { //FIXME.JHB: This wait should be optional (API change) t.Wait(30000, _cts.Token); } catch (AggregateException ex) { throw ex.InnerException; } catch (OperationCanceledException) { //Closing the storage engine will cause the factory to stop processing, but still //accept new jobs into the scheduler. If execution has gotten here, it means that //ExecSQL was called after Close, and the job will be ignored. Might consider //subclassing the factory to avoid this awkward behavior Log.D(Tag, "StorageEngine closed, canceling operation"); return 0; } if (t.Status != TaskStatus.RanToCompletion) { Log.E(Tag, "ExecSQL timed out waiting for Task #{0}", t.Id); throw new CouchbaseLiteException("ExecSQL timed out", StatusCode.InternalServerError); } return _writeConnection.changes(); } /// <summary> /// Executes only read-only SQL. /// </summary> /// <returns>The query.</returns> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public Cursor IntransactionRawQuery(String sql, params Object[] paramArgs) { if (!IsOpen) { Open(Path); } if (transactionCount == 0) { return RawQuery(sql, paramArgs); } var t = Factory.StartNew(() => { Cursor cursor = null; sqlite3_stmt command = null; try { Log.V(Tag, "RawQuery sql: {0} ({1})", sql, String.Join(", ", paramArgs.ToStringArray())); command = BuildCommand (_writeConnection, sql, paramArgs); cursor = new Cursor(command); } catch (Exception e) { if (command != null) { command.Dispose(); } Log.E(Tag, "Error executing raw query '{0}'".Fmt(sql), e); throw; } return cursor; }); return t.Result; } /// <summary> /// Executes only read-only SQL. /// </summary> /// <returns>The query.</returns> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public Cursor RawQuery(String sql, params Object[] paramArgs) { if (!IsOpen) { Open(Path); } Cursor cursor = null; sqlite3_stmt command = null; var t = Factory.StartNew (() => { try { Log.V (Tag, "RawQuery sql: {0} ({1})", sql, String.Join (", ", paramArgs.ToStringArray ())); command = BuildCommand (_readConnection, sql, paramArgs); cursor = new Cursor (command); } catch (Exception e) { if (command != null) { command.Dispose (); } var args = paramArgs == null ? String.Empty : String.Join (",", paramArgs.ToStringArray ()); Log.E (Tag, "Error executing raw query '{0}' is values '{1}' {2}".Fmt (sql, args, _readConnection.errmsg ()), e); throw; } return cursor; }); return t.Result; } public long Insert(String table, String nullColumnHack, ContentValues values) { return InsertWithOnConflict(table, null, values, ConflictResolutionStrategy.None); } public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy) { if (!StringEx.IsNullOrWhiteSpace(nullColumnHack)) { var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag)); Log.E(Tag, "Unsupported use of nullColumnHack", e); throw e; } var t = Factory.StartNew(() => { var lastInsertedId = -1L; var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy); try { int result; result = command.step(); command.Dispose(); if (result == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); int changes = _writeConnection.changes(); if (changes > 0) { lastInsertedId = _writeConnection.last_insert_rowid(); } if (lastInsertedId == -1L) { if(conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) { Log.E(Tag, "Error inserting " + initialValues + " using " + command); throw new CouchbaseLiteException("Error inserting " + initialValues + " using " + command, StatusCode.DbError); } } else { Log.V(Tag, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues); } } catch (Exception ex) { Log.E(Tag, "Error inserting into table " + table, ex); throw; } return lastInsertedId; }); return t.Result; } public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs) { Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Debug.Assert(values != null); var t = Factory.StartNew(() => { var resultCount = 0; var command = GetUpdateCommand(table, values, whereClause, whereArgs); try { var result = command.step(); if (result == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } catch (ugly.sqlite3_exception ex) { var msg = raw.sqlite3_extended_errcode(_writeConnection).ToString(); Log.E(Tag, "Error {0}: \"{1}\" while updating table {2}\r\n{3}", ex.errcode, msg, table, ex); } resultCount = _writeConnection.changes(); if (resultCount < 0) { Log.E(Tag, "Error updating " + values + " using " + command); throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError); } command.Dispose(); return resultCount; }, CancellationToken.None); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. //doesn't look good var r = t.GetAwaiter().GetResult(); if (t.Exception != null) throw t.Exception; return r; } public int Delete(String table, String whereClause, params String[] whereArgs) { Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); var t = Factory.StartNew(() => { var resultCount = -1; var command = GetDeleteCommand(table, whereClause, whereArgs); try { var result = command.step(); if (result == SQLiteResult.ERROR) throw new CouchbaseLiteException("Error deleting from table " + table, StatusCode.DbError); resultCount = _writeConnection.changes(); if (resultCount < 0) { throw new CouchbaseLiteException("Failed to delete the records.", StatusCode.DbError); } } catch (Exception ex) { Log.E(Tag, "Error {0} when deleting from table {1}".Fmt(_writeConnection.extended_errcode(), table), ex); throw; } finally { command.Dispose(); } return resultCount; }); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. var r = t.GetAwaiter().GetResult(); if (t.Exception != null) { //this is bad: should not arbitrarily crash the app throw t.Exception; } return r; } public void Close() { _cts.Cancel(); ((SingleThreadScheduler)Factory.Scheduler).Dispose(); Close(ref _readConnection); Close(ref _writeConnection); Path = null; } static void Close(ref sqlite3 db) { if (db == null) { return; } try { // Close any open statements, otherwise the // sqlite connection won't actually close. sqlite3_stmt next = null; while ((next = db.next_stmt(next))!= null) { next.Dispose(); } db.close(); Log.W(Tag, "db connection {0} closed", db); } catch (KeyNotFoundException ex) { // Appears to be a bug in sqlite3.find_stmt. Concurrency issue in static dictionary? // Assuming we're done. Log.W(Tag, "Abandoning database close.", ex); } catch (ugly.sqlite3_exception ex) { Log.E(Tag, "Retrying database close.", ex); // Assuming a basic retry fixes this. Thread.Sleep(5000); db.close(); } GC.Collect(); GC.WaitForPendingFinalizers(); try { db.Dispose(); } catch (Exception ex) { Log.E(Tag, "Error while closing database.", ex); } finally { db = null; } } #endregion #region Non-public Members private sqlite3_stmt BuildCommand(sqlite3 db, string sql, object[] paramArgs) { sqlite3_stmt command = null; try { if (!IsOpen) { if(Open(Path) == false) { throw new CouchbaseLiteException("Failed to Open " + Path, StatusCode.DbError); } } int err = raw.SQLITE_OK; lock(Cursor.StmtDisposeLock) { err = raw.sqlite3_prepare_v2(db, sql, out command); } if (err != raw.SQLITE_OK || command == null) { Log.E(Tag, "sqlite3_prepare_v2: " + err); } if (paramArgs != null && paramArgs.Length > 0 && command != null && err != raw.SQLITE_ERROR) { command.bind(paramArgs); } } catch (Exception e) { Log.E(Tag, "Error when build a sql " + sql + " with params " + paramArgs, e); throw; } return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The update command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("UPDATE "); builder.Append(table); builder.Append(" SET "); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var paramList = new List<object>(); var index = 0; foreach (var column in valueSet) { if (index++ > 0) { builder.Append(","); } builder.AppendFormat("{0} = ?", column.Key); paramList.Add(column.Value); } if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } if (whereArgs != null) { paramList.AddRange(whereArgs); } var sql = builder.ToString(); var command = BuildCommand(_writeConnection, sql, paramList.ToArray<object>()); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The insert command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param> sqlite3_stmt GetInsertCommand(String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("INSERT"); if (conflictResolutionStrategy != ConflictResolutionStrategy.None) { builder.Append(" OR "); builder.Append(conflictResolutionStrategy); } builder.Append(" INTO "); builder.Append(table); builder.Append(" ("); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var valueBuilder = new StringBuilder(); var index = 0; var args = new object[valueSet.Count]; foreach (var column in valueSet) { if (index > 0) { builder.Append(","); valueBuilder.Append(","); } builder.AppendFormat("{0}", column.Key); valueBuilder.Append("?"); args[index] = column.Value; index++; } builder.Append(") VALUES ("); builder.Append(valueBuilder); builder.Append(")"); var sql = builder.ToString(); sqlite3_stmt command = null; if (args != null) { Log.D(Tag, "Preparing statement: '{0}' with values: {1}", sql, String.Join(", ", args.Select(o => o == null ? "null" : o.ToString()).ToArray())); } else { Log.D(Tag, "Preparing statement: '{0}'", sql); } command = BuildCommand(_writeConnection, sql, args); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The delete command.</returns> /// <param name="table">Table.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetDeleteCommand(string table, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("DELETE FROM "); builder.Append(table); if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } sqlite3_stmt command; command = BuildCommand(_writeConnection, builder.ToString(), whereArgs); return command; } #endregion #region IDisposable implementation public void Dispose() { Close(); } #endregion } }
// // Options.cs // // Authors: // Jonathan Pryor <[email protected]> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif namespace PWLib.Platform { public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { TypeConverter conv = TypeDescriptor.GetConverter (typeof (T)); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof (T).Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet (Converter<string, string> localizer) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } #endif private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } List<string> lines = GetLines (localizer (GetDescription (p.Description))); o.WriteLine (lines [0]); string prefix = new string (' ', OptionWidth+2); for (int i = 1; i < lines.Count; ++i) { o.Write (prefix); o.WriteLine (lines [i]); } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static List<string> GetLines (string description) { List<string> lines = new List<string> (); if (string.IsNullOrEmpty (description)) { lines.Add (string.Empty); return lines; } int length = 80 - OptionWidth - 2; int start = 0, end; do { end = GetLineEnd (start, length, description); bool cont = false; if (end < description.Length) { char c = description [end]; if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) ++end; else if (c != '\n') { cont = true; --end; } } lines.Add (description.Substring (start, end - start)); if (cont) { lines [lines.Count-1] += "-"; } start = end; if (start < description.Length && description [start] == '\n') ++start; } while (end < description.Length); return lines; } private static int GetLineEnd (int start, int length, string description) { int end = Math.Min (start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { switch (description [i]) { case ' ': case '\t': case '\v': case '-': case ',': case '.': case ';': sep = i; break; case '\n': return i; } } if (sep == -1 || end == description.Length) return end; return sep; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Beatmaps; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Screens.Edit; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Beatmaps { [HeadlessTest] public class TestSceneEditorBeatmap : EditorClockTestScene { /// <summary> /// Tests that the addition event is correctly invoked after a hitobject is added. /// </summary> [Test] public void TestHitObjectAddEvent() { var hitCircle = new HitCircle(); HitObject addedObject = null; EditorBeatmap editorBeatmap = null; AddStep("add beatmap", () => { Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap()); editorBeatmap.HitObjectAdded += h => addedObject = h; }); AddStep("add hitobject", () => editorBeatmap.Add(hitCircle)); AddAssert("received add event", () => addedObject == hitCircle); } /// <summary> /// Tests that the removal event is correctly invoked after a hitobject is removed. /// </summary> [Test] public void HitObjectRemoveEvent() { var hitCircle = new HitCircle(); HitObject removedObject = null; EditorBeatmap editorBeatmap = null; AddStep("add beatmap", () => { Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap { HitObjects = { hitCircle } }); editorBeatmap.HitObjectRemoved += h => removedObject = h; }); AddStep("remove hitobject", () => editorBeatmap.Remove(editorBeatmap.HitObjects.First())); AddAssert("received remove event", () => removedObject == hitCircle); } /// <summary> /// Tests that the changed event is correctly invoked after the start time of a hitobject is changed. /// This tests for hitobjects which were already present before the editor beatmap was constructed. /// </summary> [Test] public void TestInitialHitObjectStartTimeChangeEvent() { var hitCircle = new HitCircle(); HitObject changedObject = null; AddStep("add beatmap", () => { EditorBeatmap editorBeatmap; Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap { HitObjects = { hitCircle } }); editorBeatmap.HitObjectUpdated += h => changedObject = h; }); AddStep("change start time", () => hitCircle.StartTime = 1000); AddAssert("received change event", () => changedObject == hitCircle); } /// <summary> /// Tests that the changed event is correctly invoked after the start time of a hitobject is changed. /// This tests for hitobjects which were added to an existing editor beatmap. /// </summary> [Test] public void TestAddedHitObjectStartTimeChangeEvent() { EditorBeatmap editorBeatmap = null; HitObject changedObject = null; AddStep("add beatmap", () => { Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap()); editorBeatmap.HitObjectUpdated += h => changedObject = h; }); var hitCircle = new HitCircle(); AddStep("add object", () => editorBeatmap.Add(hitCircle)); AddAssert("event not received", () => changedObject == null); AddStep("change start time", () => hitCircle.StartTime = 1000); AddAssert("event received", () => changedObject == hitCircle); } /// <summary> /// Tests that the channged event is not invoked after a hitobject is removed from the beatmap/ /// </summary> [Test] public void TestRemovedHitObjectStartTimeChangeEvent() { var hitCircle = new HitCircle(); var editorBeatmap = new EditorBeatmap(new OsuBeatmap { HitObjects = { hitCircle } }); HitObject changedObject = null; editorBeatmap.HitObjectUpdated += h => changedObject = h; editorBeatmap.Remove(hitCircle); Assert.That(changedObject, Is.Null); hitCircle.StartTime = 1000; Assert.That(changedObject, Is.Null); } /// <summary> /// Tests that an added hitobject is correctly inserted to preserve the sorting order of the beatmap. /// </summary> [Test] public void TestAddHitObjectInMiddle() { var editorBeatmap = new EditorBeatmap(new OsuBeatmap { HitObjects = { new HitCircle(), new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 2000 }, } }); var hitCircle = new HitCircle { StartTime = 1000 }; editorBeatmap.Add(hitCircle); Assert.That(editorBeatmap.HitObjects.Count(h => h == hitCircle), Is.EqualTo(1)); Assert.That(Array.IndexOf(editorBeatmap.HitObjects.ToArray(), hitCircle), Is.EqualTo(3)); } /// <summary> /// Tests that the beatmap remains correctly sorted after the start time of a hitobject is changed. /// </summary> [Test] public void TestResortWhenStartTimeChanged() { var hitCircle = new HitCircle { StartTime = 1000 }; var editorBeatmap = new EditorBeatmap(new OsuBeatmap { HitObjects = { new HitCircle(), new HitCircle { StartTime = 1000 }, new HitCircle { StartTime = 1000 }, hitCircle, new HitCircle { StartTime = 2000 }, } }); hitCircle.StartTime = 0; Assert.That(editorBeatmap.HitObjects.Count(h => h == hitCircle), Is.EqualTo(1)); Assert.That(Array.IndexOf(editorBeatmap.HitObjects.ToArray(), hitCircle), Is.EqualTo(1)); } /// <summary> /// Tests that multiple hitobjects are updated simultaneously. /// </summary> [Test] public void TestMultipleHitObjectUpdate() { var updatedObjects = new List<HitObject>(); var allHitObjects = new List<HitObject>(); EditorBeatmap editorBeatmap = null; AddStep("add beatmap", () => { updatedObjects.Clear(); Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap()); for (int i = 0; i < 10; i++) { var h = new HitCircle(); editorBeatmap.Add(h); allHitObjects.Add(h); } }); AddStep("change all start times", () => { editorBeatmap.HitObjectUpdated += h => updatedObjects.Add(h); for (int i = 0; i < 10; i++) allHitObjects[i].StartTime += 10; }); // Distinct ensures that all hitobjects have been updated once, debounce is tested below. AddAssert("all hitobjects updated", () => updatedObjects.Distinct().Count() == 10); } /// <summary> /// Tests that hitobject updates are debounced when they happen too soon. /// </summary> [Test] public void TestDebouncedUpdate() { var updatedObjects = new List<HitObject>(); EditorBeatmap editorBeatmap = null; AddStep("add beatmap", () => { updatedObjects.Clear(); Child = editorBeatmap = new EditorBeatmap(new OsuBeatmap()); editorBeatmap.Add(new HitCircle()); }); AddStep("change start time twice", () => { editorBeatmap.HitObjectUpdated += h => updatedObjects.Add(h); editorBeatmap.HitObjects[0].StartTime = 10; editorBeatmap.HitObjects[0].StartTime = 20; }); AddAssert("only updated once", () => updatedObjects.Count == 1); } } }
// // SearchEntry.cs // // Author: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2007 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 Gtk; namespace Banshee.Widgets { public class SearchEntry : EventBox { private HBox box; private Entry entry; private HoverImageButton filter_button; private HoverImageButton clear_button; private Menu menu; private int active_filter_id = -1; private uint changed_timeout_id = 0; private string empty_message; private bool ready = false; private event EventHandler filter_changed; private event EventHandler entry_changed; public event EventHandler Changed { add { entry_changed += value; } remove { entry_changed -= value; } } public event EventHandler Activated { add { entry.Activated += value; } remove { entry.Activated -= value; } } public event EventHandler FilterChanged { add { filter_changed += value; } remove { filter_changed -= value; } } public uint ChangeTimeoutMs { get; set; } public Menu Menu { get { return menu; } } protected SearchEntry (IntPtr raw) : base (raw) { } public SearchEntry() { ChangeTimeoutMs = 25; AppPaintable = true; BuildWidget(); BuildMenu(); NoShowAll = true; } private void BuildWidget() { box = new HBox(); entry = new FramelessEntry(this); filter_button = new HoverImageButton(IconSize.Menu, new string [] { "edit-find", Stock.Find }); clear_button = new HoverImageButton(IconSize.Menu, new string [] { "edit-clear", Stock.Clear }); clear_button.TooltipText = Mono.Unix.Catalog.GetString ("Clear search"); box.PackStart(filter_button, false, false, 0); box.PackStart(entry, true, true, 0); box.PackStart(clear_button, false, false, 0); Add(box); box.ShowAll(); entry.StyleSet += OnInnerEntryStyleSet; entry.StateChanged += OnInnerEntryStateChanged; entry.FocusInEvent += OnInnerEntryFocusEvent; entry.FocusOutEvent += OnInnerEntryFocusEvent; entry.Changed += OnInnerEntryChanged; filter_button.Image.Xpad = 2; clear_button.Image.Xpad = 2; filter_button.CanFocus = false; clear_button.CanFocus = false; filter_button.ButtonReleaseEvent += OnButtonReleaseEvent; clear_button.ButtonReleaseEvent += OnButtonReleaseEvent; clear_button.Clicked += OnClearButtonClicked; filter_button.Visible = false; clear_button.Visible = false; } private void BuildMenu() { menu = new Menu(); menu.Deactivated += OnMenuDeactivated; } private void ShowMenu(uint time) { if(menu.Children.Length > 0) { menu.Popup(null, null, OnPositionMenu, 0, time); menu.ShowAll(); } } private void ShowHideButtons() { clear_button.Visible = entry.Text.Length > 0; filter_button.Visible = menu != null && menu.Children.Length > 0; } private void OnPositionMenu(Menu menu, out int x, out int y, out bool push_in) { int origin_x, origin_y, tmp; filter_button.GdkWindow.GetOrigin(out origin_x, out tmp); GdkWindow.GetOrigin(out tmp, out origin_y); x = origin_x + filter_button.Allocation.X; y = origin_y + SizeRequest().Height; push_in = true; } private void OnMenuDeactivated(object o, EventArgs args) { filter_button.QueueDraw(); } private bool toggling = false; private void OnMenuItemToggled(object o, EventArgs args) { if(toggling || !(o is FilterMenuItem)) { return; } toggling = true; FilterMenuItem item = (FilterMenuItem)o; foreach(MenuItem child_item in menu) { if(!(child_item is FilterMenuItem)) { continue; } FilterMenuItem filter_child = (FilterMenuItem)child_item; if(filter_child != item) { filter_child.Active = false; } } item.Active = true; ActiveFilterID = item.ID; toggling = false; } private void OnInnerEntryChanged(object o, EventArgs args) { ShowHideButtons(); if(changed_timeout_id > 0) { GLib.Source.Remove(changed_timeout_id); } if (Ready) changed_timeout_id = GLib.Timeout.Add(ChangeTimeoutMs, OnChangedTimeout); } private bool OnChangedTimeout() { OnChanged(); return false; } private void UpdateStyle () { Gdk.Color color = entry.Style.Base (entry.State); filter_button.ModifyBg (entry.State, color); clear_button.ModifyBg (entry.State, color); box.BorderWidth = (uint)entry.Style.XThickness; } private void OnInnerEntryStyleSet (object o, StyleSetArgs args) { UpdateStyle (); } private void OnInnerEntryStateChanged (object o, EventArgs args) { UpdateStyle (); } private void OnInnerEntryFocusEvent(object o, EventArgs args) { QueueDraw(); } private void OnButtonReleaseEvent(object o, ButtonReleaseEventArgs args) { if(args.Event.Button != 1) { return; } entry.HasFocus = true; if(o == filter_button) { ShowMenu(args.Event.Time); } } private void OnClearButtonClicked(object o, EventArgs args) { active_filter_id = 0; entry.Text = String.Empty; } protected override bool OnKeyPressEvent (Gdk.EventKey evnt) { if (evnt.Key == Gdk.Key.Escape) { active_filter_id = 0; entry.Text = String.Empty; return true; } return base.OnKeyPressEvent (evnt); } protected override bool OnExposeEvent(Gdk.EventExpose evnt) { Style.PaintFlatBox (entry.Style, GdkWindow, State, ShadowType.None, evnt.Area, this, "entry_bg", 0, 0, Allocation.Width, Allocation.Height); PropagateExpose(Child, evnt); Style.PaintShadow(entry.Style, GdkWindow, StateType.Normal, ShadowType.In, evnt.Area, entry, "entry", 0, 0, Allocation.Width, Allocation.Height); return true; } protected override void OnShown() { base.OnShown(); ShowHideButtons(); } protected virtual void OnChanged() { if(!Ready) { return; } EventHandler handler = entry_changed; if(handler != null) { handler(this, EventArgs.Empty); } } protected virtual void OnFilterChanged() { EventHandler handler = filter_changed; if(handler != null) { handler(this, EventArgs.Empty); } if(IsQueryAvailable) { OnInnerEntryChanged(this, EventArgs.Empty); } } public void AddFilterOption(int id, string label) { if(id < 0) { throw new ArgumentException("id", "must be >= 0"); } FilterMenuItem item = new FilterMenuItem(id, label); item.Toggled += OnMenuItemToggled; menu.Append(item); if(ActiveFilterID < 0) { item.Toggle(); } filter_button.Visible = true; } public void AddFilterSeparator() { menu.Append(new SeparatorMenuItem()); } public void RemoveFilterOption(int id) { FilterMenuItem item = FindFilterMenuItem(id); if(item != null) { menu.Remove(item); } } public void ActivateFilter(int id) { FilterMenuItem item = FindFilterMenuItem(id); if(item != null) { item.Toggle(); } } private FilterMenuItem FindFilterMenuItem(int id) { foreach(MenuItem item in menu) { if(item is FilterMenuItem && ((FilterMenuItem)item).ID == id) { return (FilterMenuItem)item; } } return null; } public string GetLabelForFilterID(int id) { FilterMenuItem item = FindFilterMenuItem(id); if(item == null) { return null; } return item.Label; } public void CancelSearch() { entry.Text = String.Empty; ActivateFilter(0); } public int ActiveFilterID { get { return active_filter_id; } private set { if(value == active_filter_id) { return; } active_filter_id = value; OnFilterChanged(); } } public string EmptyMessage { get { return entry.Sensitive ? empty_message : String.Empty; } set { empty_message = value; entry.QueueDraw(); } } public string Query { get { return entry.Text.Trim(); } set { entry.Text = value.Trim(); } } public bool IsQueryAvailable { get { return Query != null && Query != String.Empty; } } public bool Ready { get { return ready; } set { ready = value; } } public new bool HasFocus { get { return entry.HasFocus; } set { entry.HasFocus = true; } } public Entry InnerEntry { get { return entry; } } protected override void OnStateChanged (Gtk.StateType previous_state) { base.OnStateChanged (previous_state); entry.Sensitive = State != StateType.Insensitive; filter_button.Sensitive = State != StateType.Insensitive; clear_button.Sensitive = State != StateType.Insensitive; } private class FilterMenuItem : MenuItem /*CheckMenuItem*/ { private int id; private string label; public FilterMenuItem(int id, string label) : base(label) { this.id = id; this.label = label; //DrawAsRadio = true; } public int ID { get { return id; } } public string Label { get { return label; } } // FIXME: Remove when restored to CheckMenuItem private bool active; public bool Active { get { return active; } set { active = value; } } public new event EventHandler Toggled; protected override void OnActivated () { base.OnActivated (); if (Toggled != null) { Toggled (this, EventArgs.Empty); } } } private class FramelessEntry : Entry { private Gdk.Window text_window; private SearchEntry parent; private Pango.Layout layout; private Gdk.GC text_gc; public FramelessEntry(SearchEntry parent) : base() { this.parent = parent; HasFrame = false; parent.StyleSet += OnParentStyleSet; WidthChars = 1; } private void OnParentStyleSet(object o, EventArgs args) { RefreshGC(); QueueDraw(); } private void RefreshGC() { if(text_window == null) { return; } text_gc = new Gdk.GC(text_window); text_gc.Copy(Style.TextGC(StateType.Normal)); Gdk.Color color_a = parent.Style.Base(StateType.Normal); Gdk.Color color_b = parent.Style.Text(StateType.Normal); text_gc.RgbFgColor = Hyena.Gui.GtkUtilities.ColorBlend(color_a, color_b); } protected override bool OnExposeEvent(Gdk.EventExpose evnt) { // The Entry's GdkWindow is the top level window onto which // the frame is drawn; the actual text entry is drawn into a // separate window, so we can ensure that for themes that don't // respect HasFrame, we never ever allow the base frame drawing // to happen if(evnt.Window == GdkWindow) { return true; } bool ret = base.OnExposeEvent(evnt); if(text_gc == null || evnt.Window != text_window) { text_window = evnt.Window; RefreshGC(); } if(Text.Length > 0 || HasFocus || parent.EmptyMessage == null) { return ret; } if (layout == null) { layout = new Pango.Layout(PangoContext); layout.FontDescription = PangoContext.FontDescription; } int width, height; layout.SetMarkup(parent.EmptyMessage); layout.GetPixelSize(out width, out height); evnt.Window.DrawLayout(text_gc, 2, (SizeRequest().Height - height) / 2, layout); return ret; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; using IL2CPU.API.Attribs; namespace Cosmos.Core_Plugs.System { [Plug(typeof(BitConverter))] public class BitConverterImpl { public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)1 : (byte)0); return r; } public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed (byte* b = bytes) *((short*)b) = value; return bytes; } public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed (byte* b = bytes) *((int*)b) = value; return bytes; } public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed (byte* b = bytes) *((long*)b) = value; return bytes; } public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } public static unsafe short ToInt16(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else if (BitConverter.IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } public static unsafe int ToInt32(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else if (BitConverter.IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } public static unsafe long ToInt64(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else if (BitConverter.IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } public static unsafe double ToDouble(byte[] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); if ((uint)startIndex > value.Length) throw new ArgumentOutOfRangeException("startIndex"); if (startIndex > value.Length - 8) throw new ArgumentException("Array with offset is too short"); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static void ThrowValueArgumentNull() { throw new ArgumentNullException("value"); } private static void ThrowStartIndexArgumentOutOfRange() { throw new ArgumentOutOfRangeException("startIndex", "ArgumentOutOfRange_Index"); } private static void ThrowValueArgumentTooSmall() { throw new ArgumentException("Arg_ArrayPlusOffTooSmall", "value"); } } }
// JTransc {{ JTRANSC_VERSION }} : https://github.com/jtransc/jtransc using System; #pragma warning disable 108, 109, 162, 219, 414, 675 class N { //public static readonly double DoubleNaN = 0.0d / 0.0; public static readonly float FloatNaN = intBitsToFloat(0x7FC00000); public static readonly double DoubleNaN = longBitsToDouble(0x7FF8000000000000); //public static readonly long MAX_INT64 = 9223372036854775807; //public static readonly long MIN_INT64 = -9223372036854775808; //public static readonly int MAX_INT32 = 2147483647; //public static readonly int MIN_INT32 = -2147483648; static readonly public int MIN_INT32 = unchecked((int)0x80000000); static readonly public int MAX_INT32 = unchecked((int)0x7FFFFFFF); static readonly public long MIN_INT64 = unchecked((long)0x8000000000000000L); static readonly public long MAX_INT64 = unchecked((long)0x7FFFFFFFFFFFFFFFL); //static public TOut CHECK_CAST<TOut, TIn>(TIn i) where TIn : class where TOut : class { // if (i == null) return null; // if (!(i is TOut)) { // throw new WrappedThrowable({% CONSTRUCTOR java.lang.ClassCastException:()V %}()); // } // return (TOut)(object)i; //} static public {% CLASS java.lang.Throwable %} getJavaException(Exception ee) { if (ee is WrappedThrowable) return ((WrappedThrowable)ee).t; if (ee is InvalidCastException) return {% CONSTRUCTOR java.lang.ClassCastException:()V %}(); //throw ee; return null; } static public {% CLASS com.jtransc.JTranscWrapped %} wrap(object item) { if (item == null) return null; return {% CLASS com.jtransc.JTranscWrapped %}.wrap(item); } static public object unwrap({% CLASS java.lang.Object %} item) { if (item == null) return null; return {% CLASS com.jtransc.JTranscWrapped %}.unwrap(({% CLASS com.jtransc.JTranscWrapped %})item); } static public int iushr(int l, int r) { return (int)(((uint)l) >> r); } static public void init() { //Console.WriteLine(Console.OutputEncoding.CodePage); } static public JA_L getStackTrace(System.Diagnostics.StackTrace st, int skip) { //var st = new System.Diagnostics.StackTrace(exception); //var st = exception.StackTrace; var o = new JA_L(st.FrameCount - skip, "[Ljava/lang/StackTraceElement;"); for (int n = 0; n < st.FrameCount; n++) { var f = st.GetFrame(n); var clazz = (f != null) ? ("" + f.GetMethod().DeclaringType) : "DummyClass"; var method = (f != null) ? ("" + f.GetMethod().Name) : "dummyMethod"; var file = (f != null) ? ("" + f.GetFileName()) : "Dummy.java"; var lineNumber = (f != null) ? f.GetFileLineNumber() : 0; if (n >= skip) { o[n - skip] = {% CONSTRUCTOR java.lang.StackTraceElement:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V %}( N.str(clazz), N.str(method), N.str(file), lineNumber ); } } return o; } static public bool unboxBool ({% CLASS java.lang.Boolean %} i) { return i{% IMETHOD java.lang.Boolean:booleanValue %}(); } static public sbyte unboxByte ({% CLASS java.lang.Byte %} i) { return i{% IMETHOD java.lang.Byte:byteValue %}(); } static public short unboxShort ({% CLASS java.lang.Short %} i) { return i{% IMETHOD java.lang.Short:shortValue %}(); } static public ushort unboxChar ({% CLASS java.lang.Character %} i) { return i{% IMETHOD java.lang.Character:charValue %}(); } static public int unboxInt ({% CLASS java.lang.Integer %} i) { return i{% IMETHOD java.lang.Integer:intValue %}(); } static public long unboxLong ({% CLASS java.lang.Long %} i) { return i{% IMETHOD java.lang.Long:longValue %}(); } static public float unboxFloat ({% CLASS java.lang.Float %} i) { return i{% IMETHOD java.lang.Float:floatValue %}(); } static public double unboxDouble({% CLASS java.lang.Double %} i) { return i{% IMETHOD java.lang.Double:doubleValue %}(); } static public {% CLASS java.lang.Object %} boxVoid ( ) { return null; } static public {% CLASS java.lang.Boolean %} boxBool (bool v) { return {% SMETHOD java.lang.Boolean:valueOf:(Z)Ljava/lang/Boolean; %}(v); } static public {% CLASS java.lang.Byte %} boxByte (sbyte v) { return {% SMETHOD java.lang.Byte:valueOf:(B)Ljava/lang/Byte; %}(v); } static public {% CLASS java.lang.Short %} boxShort (short v) { return {% SMETHOD java.lang.Short:valueOf:(S)Ljava/lang/Short; %}(v); } static public {% CLASS java.lang.Character %} boxChar (ushort v) { return {% SMETHOD java.lang.Character:valueOf:(C)Ljava/lang/Character; %}(v); } static public {% CLASS java.lang.Integer %} boxInt (int v) { return {% SMETHOD java.lang.Integer:valueOf:(I)Ljava/lang/Integer; %}(v); } static public {% CLASS java.lang.Long %} boxLong (long v) { return {% SMETHOD java.lang.Long:valueOf:(J)Ljava/lang/Long; %}(v); } static public {% CLASS java.lang.Float %} boxFloat (float v) { return {% SMETHOD java.lang.Float:valueOf:(F)Ljava/lang/Float; %}(v); } static public {% CLASS java.lang.Double %} boxDouble(double v) { return {% SMETHOD java.lang.Double:valueOf:(D)Ljava/lang/Double; %}(v); } static public int z2i(bool v) { return v ? 1 : 0; } static public int j2i(long v) { return (int)v; } static public long d2j(double v) { if (Double.IsNaN(v)) { return 0; } else if (!Double.IsInfinity(v)) { return (long)v; } else if (v >= 0) { return MAX_INT64; } else { return MIN_INT64; } } static public long i2j(int v) { return (long)v; } static public long f2j(float v) { if (Single.IsNaN(v)) { return 0; } else if (!Single.IsInfinity(v)) { return (long)v; } else if (v >= 0) { return MAX_INT64; } else { return MIN_INT64; } } static public int f2i(float v) { if (Single.IsNaN(v)) { return 0; } else if (!Single.IsInfinity(v)) { return (int)v; } else if (v >= 0) { return MAX_INT32; } else { return MIN_INT32; } } static public int d2i(double v) { if (Double.IsNaN(v)) { return 0; } else if (!Double.IsInfinity(v)) { return (int)v; } else if (v >= 0) { return MAX_INT32; } else { return MIN_INT32; } } static public long lneg (long l) { return -l; } static public long linv (long l) { return ~l; } static public long ladd (long l, long r) { return l + r; } static public long lsub (long l, long r) { return l - r; } static public long lmul (long l, long r) { return l * r; } static public long lxor (long l, long r) { return l ^ r; } static public long lor (long l, long r) { return l | r; } static public long land (long l, long r) { return l & r; } static public long lshl (long l, long r) { return l << (int)r; } static public long lshr (long l, long r) { return l >> (int)r; } static public long lushr(long l, long r) { return (long)((ulong)l >> (int)r); } static public int lcmp (long l, long r) { return (l < r) ? -1 : ((l > r) ? 1 : 0); } static public int idiv(int a, int b) { if (a == 0) return 0; if (b == 0) return 0; if (a == N.MIN_INT32 && b == -1) return N.MIN_INT32; return a / b; } static public int irem(int a, int b) { if (a == 0) return 0; if (b == 0) return 0; if (a == N.MIN_INT32 && b == -1) return 0; return a % b; } static public long ldiv(long a, long b) { if (a == 0) return 0; if (b == 0) return 0; if (a == N.MIN_INT64 && b == -1) return N.MIN_INT64; return a / b; } static public long lrem(long a, long b) { if (a == 0) return 0; if (b == 0) return 0; if (a == N.MIN_INT64 && b == -1) return 0; return a % b; } static public int cmp (double a, double b) { return (a < b) ? (-1) : ((a > b) ? (+1) : 0); } static public int cmpl(double a, double b) { return (Double.IsNaN(a) || Double.IsNaN(b)) ? (-1) : N.cmp(a, b); } static public int cmpg(double a, double b) { return (Double.IsNaN(a) || Double.IsNaN(b)) ? (+1) : N.cmp(a, b); } static public void monitorEnter({% CLASS java.lang.Object %} obj) { System.Threading.Monitor.Enter(obj); } static public void monitorExit({% CLASS java.lang.Object %} obj) { System.Threading.Monitor.Exit(obj); } static public void arraycopy({% CLASS java.lang.Object %} src, int srcPos, {% CLASS java.lang.Object %} dest, int destPos, int length) { _arraycopy(src, srcPos, dest, destPos, length); } static private int _arraycopy({% CLASS java.lang.Object %} src, int srcPos, {% CLASS java.lang.Object %} dest, int destPos, int length) { if (src is JA_0) return ((JA_0)src).copyTo(((JA_0)dest), srcPos, destPos, length); throw new Exception("Not implemented arraycopy for " + src); } static public JA_L strArray(string[] strs) { int len = strs.Length; JA_L o = new JA_L(len, "[Ljava/lang/String;"); for (int n = 0; n < len; n++) o[n] = N.str(strs[n]); return o; } static public {% CLASS java.lang.Class %} resolveClass(string name) { return {% SMETHOD java.lang.Class:forName:(Ljava/lang/String;)Ljava/lang/Class; %}(N.str(name)); } static public string istr({% CLASS java.lang.String %} s) { if (s == null) return null; JA_C chars = s{% IFIELD java.lang.String:value %}; int len = chars.length; char[] cchars = new char[len]; for (int n = 0; n < len; n++) cchars[n] = (char)chars[n]; return new string(cchars); } static public {% CLASS java.lang.String %} str(string s) { if (s == null) return null; char[] c = s.ToCharArray(); int len = c.Length; ushort[] shorts = new ushort[len]; for (int n = 0; n < len; n++) shorts[n] = (ushort)c[n]; return {% CONSTRUCTOR java.lang.String:([C)V %}(new JA_C(shorts)); } static public {% CLASS java.lang.String %} strLitEscape(string s) { return str(s); } #if UNSAFE static public unsafe double longBitsToDouble(long v) { return unchecked(*((double*)&v)); } static public unsafe long doubleToLongBits(double v) { return unchecked(*((long*)&v)); } static public unsafe float intBitsToFloat(int v) { return unchecked(*((float*)&v)); } static public unsafe int floatToIntBits(float v) { return unchecked(*((int*)&v)); } #else //static public double longBitsToDouble(long v) { return BitConverter.Int64BitsToDouble(v); } // Requires FW >= 4.0 //static public long doubleToLongBits(double v) { return BitConverter.DoubleToInt64Bits(v); } // Requires FW >= 4.0 static public double longBitsToDouble(long v) { return BitConverter.ToDouble(BitConverter.GetBytes(v), 0); } // Compatible with FW 2.0 static public long doubleToLongBits(double v) { return BitConverter.ToInt64(BitConverter.GetBytes(v), 0); } // Compatible with FW 2.0 static public float intBitsToFloat(int v) { return BitConverter.ToSingle(BitConverter.GetBytes(v), 0); } static public int floatToIntBits(float v) { return BitConverter.ToInt32(BitConverter.GetBytes(v), 0); } #endif static public double getTime() { return (double)CurrentTimeMillis(); } private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static long CurrentTimeMillis() { return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds; } } class JA_0 : {% CLASS java.lang.Object %} { public readonly int length; public readonly string desc; public JA_0(int length, string desc) { this.length = length; this.desc = desc; } virtual public int copyTo(JA_0 target, int src, int dst, int len) { return 0; } } class JA_Template<T> : JA_0 { public T[] data; public JA_Template(T[] data, string desc) : base(data.Length, desc) { this.data = data; } public JA_Template(int size, string desc) : base(size, desc) { this.data = new T[size]; } override public int copyTo(JA_0 target, int src, int dst, int len) { Array.Copy(this.data, src, ((JA_Template<T>)target).data, dst, len); return len; } public void setArraySlice(int index, T[] data) { Array.Copy(data, 0, this.data, index, data.Length); } public T this[int i] { get { return data[i]; } set { data[i] = value; } } } class JA_B : JA_Template<sbyte> { public JA_B(sbyte[] data, string desc = "[B") : base(data, desc) { } public JA_B(int size, string desc = "[B") : base(size, desc) { } public byte[] u() { return (byte[])(Array)this.data; } } class JA_C : JA_Template<ushort> { public JA_C(ushort[] data, string desc = "[C") : base(data, desc) { } public JA_C(int size, string desc = "[C") : base(size, desc) { } } class JA_S : JA_Template<short> { public JA_S(short[] data, string desc = "[S") : base(data, desc) { } public JA_S(int size, string desc = "[S") : base(size, desc) { } } class JA_I : JA_Template<int> { public JA_I(int[] data, string desc = "[I") : base(data, desc) { } public JA_I(int size, string desc = "[I") : base(size, desc) { } static public JA_I T(int[] data) { return new JA_I(data); } } class JA_J : JA_Template<long> { public JA_J(long[] data, string desc = "[J") : base(data, desc) { } public JA_J(int size, string desc = "[J") : base(size, desc) { } } class JA_F : JA_Template<float> { public JA_F(float[] data, string desc = "[F") : base(data, desc) { } public JA_F(int size, string desc = "[F") : base(size, desc) { } } class JA_D : JA_Template<double> { public JA_D(double[] data, string desc = "[D") : base(data, desc) { } public JA_D(int size, string desc = "[D") : base(size, desc) { } } class JA_L : JA_Template<{% CLASS java.lang.Object %}> { public JA_L({% CLASS java.lang.Object %}[] data, string desc) : base(data, desc) { } public JA_L(int size, string desc) : base(size, desc) { } static public JA_L fromArray(string desc, {% CLASS java.lang.Object %}[] data) { return new JA_L(data, desc); } static public JA_L T0(string desc) { return new JA_L(new {% CLASS java.lang.Object %}[]{}, desc); } static public JA_L T1(string desc, {% CLASS java.lang.Object %} a) { return new JA_L(new[]{ a }, desc); } static public JA_L T2(string desc, {% CLASS java.lang.Object %} a, {% CLASS java.lang.Object %} b) { return new JA_L(new[]{ a, b }, desc); } static public JA_L T3(string desc, {% CLASS java.lang.Object %} a, {% CLASS java.lang.Object %} b, {% CLASS java.lang.Object %} c) { return new JA_L(new[]{ a, b, c }, desc); } static public JA_L T4(string desc, {% CLASS java.lang.Object %} a, {% CLASS java.lang.Object %} b, {% CLASS java.lang.Object %} c, {% CLASS java.lang.Object %} d) { return new JA_L(new[]{ a, b, c, d }, desc); } static public JA_0 createMultiSure(string desc, params int[] sizes) { return _createMultiSure(desc, 0, sizes); } static public JA_0 _createMultiSure(string desc, int index, int[] sizes) { if (!desc.StartsWith("[")) return null; if (index >= sizes.Length - 1) return JA_L.create(sizes[index], desc); int len = sizes[index]; JA_L o = new JA_L(len, desc); string desc2 = desc.Substring(1); for (int n = 0; n < len; n++) { o[n] = JA_L._createMultiSure(desc2, index + 1, sizes); } return o; } static JA_0 create(int size, string desc) { switch (desc) { case "[Z": return new JA_Z(size); case "[B": return new JA_B(size); case "[C": return new JA_C(size); case "[S": return new JA_S(size); case "[I": return new JA_I(size); case "[J": return new JA_J(size); case "[F": return new JA_F(size); case "[D": return new JA_D(size); default: return new JA_L(size, desc); } } } class JA_Z : JA_B { public JA_Z(sbyte[] data, string desc = "[Z") : base(data, desc) { } public JA_Z(int size, string desc = "[Z") : base(size, desc) { } } class WrappedThrowable : Exception { public {% CLASS java.lang.Throwable %} t; public WrappedThrowable({% CLASS java.lang.Throwable %} t) : base() { this.t = ({% CLASS java.lang.Throwable %})t; //this.t.csException = this; } public WrappedThrowable({% CLASS java.lang.Object %} t) : base() { this.t = ({% CLASS java.lang.Throwable %})t; //this.t.csException = this; } } /* ## BODY ## */
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; #if NET_45 using System.Collections.Generic; #endif namespace Octokit { /// <summary> /// A client for GitHub's Repositories API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details. /// </remarks> public interface IRepositoriesClient { /// <summary> /// Client for managing pull requests. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details /// </remarks> IPullRequestsClient PullRequest { get; } /// <summary> /// Client for managing branches in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/branches/">Branches API documentation</a> for more details /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] IRepositoryBranchesClient Branch { get; } /// <summary> /// Client for managing commit comments in a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> IRepositoryCommentsClient Comment { get; } /// <summary> /// Client for managing deploy keys in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information. /// </remarks> IRepositoryDeployKeysClient DeployKeys { get; } /// <summary> /// Client for managing the contents of a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information. /// </remarks> IRepositoryContentsClient Content { get; } /// <summary> /// Creates a new repository for the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository.</returns> Task<Repository> Create(NewRepository newRepository); /// <summary> /// Creates a new repository in the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="organizationLogin">Login of the organization in which to create the repository</param> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository</returns> Task<Repository> Create(string organizationLogin, NewRepository newRepository); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(string owner, string name); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(int repositoryId); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(string owner, string name); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(int repositoryId); /// <summary> /// Gets all public repositories. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllPublic(); /// <summary> /// Gets all public repositories since the integer Id of the last Repository that you've seen. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters of the last repository seen</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllForCurrent(); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(ApiOptions options); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="login">The account name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// </remarks> /// <param name="login">The account name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization, ApiOptions options); /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> ICommitStatusClient Status { get; } /// <summary> /// A client for GitHub's Repository Hooks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks> IRepositoryHooksClient Hooks { get; } /// <summary> /// A client for GitHub's Repository Forks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks> IRepositoryForksClient Forks { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> IRepoCollaboratorsClient Collaborator { get; } /// <summary> /// Client for GitHub's Repository Deployments API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details /// </remarks> IDeploymentsClient Deployment { get; } /// <summary> /// Client for GitHub's Repository Statistics API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details ///</remarks> IStatisticsClient Statistics { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> IRepositoryCommitsClient Commit { get; } /// <summary> /// Access GitHub's Releases API. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/releases/ /// </remarks> IReleasesClient Release { get; } /// <summary> /// Client for GitHub's Repository Merging API /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details ///</remarks> IMergingClient Merging { get; } /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(int repositoryId); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name, ApiOptions options); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(int repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(int repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(int repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name, ApiOptions options); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(int repositoryId, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(int repositoryId); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(int repositoryId, ApiOptions options); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> [Obsolete("Please use RepositoriesClient.Branch.Get() instead. This method will be removed in a future version")] Task<Branch> GetBranch(string owner, string name, string branchName); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> [Obsolete("Please use RepositoriesClient.Branch.Get() instead. This method will be removed in a future version")] Task<Branch> GetBranch(int repositoryId, string branchName); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(string owner, string name, RepositoryUpdate update); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The Id of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(int repositoryId, RepositoryUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> [Obsolete("This existing implementation will cease to work when the Branch Protection API preview period ends. Please use the RepositoryBranchesClient methods instead.")] Task<Branch> EditBranch(string owner, string name, string branch, BranchUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The Id of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> [Obsolete("This existing implementation will cease to work when the Branch Protection API preview period ends. Please use the RepositoryBranchesClient methods instead.")] Task<Branch> EditBranch(int repositoryId, string branch, BranchUpdate update); /// <summary> /// A client for GitHub's Repository Pages API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information. /// </remarks> IRepositoryPagesClient Page { get; } /// <summary> /// A client for GitHub's Repository Invitations API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/invitations/">Repository Invitations API documentation</a> for more information. /// </remarks> IRepositoryInvitationsClient Invitation { get; } } }
/* * Copyright (c) Contributors, http://aurora-sim.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; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using RegionFlags = Aurora.Framework.RegionFlags; namespace Aurora.Modules.Estate { public class EstateSettingsModule : ISharedRegionStartupModule { #region Declares private readonly Dictionary<UUID, int> LastTelehub = new Dictionary<UUID, int>(); private readonly Dictionary<UUID, int> TimeSinceLastTeleport = new Dictionary<UUID, int>(); private readonly List<IScene> m_scenes = new List<IScene>(); private string[] BanCriteria = new string[0]; private bool ForceLandingPointsOnCrossing; private bool LoginsDisabled = true; private IRegionConnector RegionConnector; private float SecondsBeforeNextTeleport = 3; private bool StartDisabled; private bool m_enabled; private bool m_enabledBlockTeleportSeconds; private bool m_checkMaturityLevel = true; #endregion #region ISharedRegionModule public string Name { get { return "EstateSettingsModule"; } } #endregion #region Console Commands protected void ProcessLoginCommands(string[] cmd) { if (cmd.Length < 2) { MainConsole.Instance.Info("Syntax: login enable|disable|status"); return; } switch (cmd[1]) { case "enable": if (LoginsDisabled) MainConsole.Instance.Warn("Enabling Logins"); LoginsDisabled = false; break; case "disable": if (!LoginsDisabled) MainConsole.Instance.Warn("Disabling Logins"); LoginsDisabled = true; break; case "status": MainConsole.Instance.Warn("Logins are " + (LoginsDisabled ? "dis" : "en") + "abled."); break; default: MainConsole.Instance.Info("Syntax: login enable|disable|status"); break; } } protected void BanUser(string[] cmdparams) { if (cmdparams.Length < 4) { MainConsole.Instance.Warn("Not enough parameters!"); return; } IScenePresence SP = MainConsole.Instance.ConsoleScene.SceneGraph.GetScenePresence(cmdparams[2], cmdparams[3]); if (SP == null) { MainConsole.Instance.Warn("Could not find user"); return; } EstateSettings ES = MainConsole.Instance.ConsoleScene.RegionInfo.EstateSettings; AgentCircuitData circuitData = MainConsole.Instance.ConsoleScene.AuthenticateHandler.GetAgentCircuitData(SP.UUID); ES.AddBan(new EstateBan { BannedHostAddress = circuitData.IPAddress, BannedHostIPMask = circuitData.IPAddress, BannedHostNameMask = circuitData.IPAddress, BannedUserID = SP.UUID, EstateID = ES.EstateID }); ES.Save(); string alert = null; if (cmdparams.Length > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); if (alert != null) SP.ControllingClient.Kick(alert); else SP.ControllingClient.Kick("\nThe Aurora manager banned and kicked you out.\n"); // kick client... IEntityTransferModule transferModule = SP.Scene.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) transferModule.IncomingCloseAgent(SP.Scene, SP.UUID); } protected void UnBanUser(string[] cmdparams) { if (cmdparams.Length < 4) { MainConsole.Instance.Warn("Not enough parameters!"); return; } UserAccount account = MainConsole.Instance.ConsoleScene.UserAccountService.GetUserAccount(UUID.Zero, Util.CombineParams (cmdparams, 2)); if (account == null) { MainConsole.Instance.Warn("Could not find user"); return; } EstateSettings ES = MainConsole.Instance.ConsoleScene.RegionInfo.EstateSettings; ES.RemoveBan(account.PrincipalID); ES.Save(); } protected void SetRegionInfoOption(string[] cmdparams) { IScene scene = MainConsole.Instance.ConsoleScene; if (scene == null) scene = m_scenes[0]; #region 3 Params needed if (cmdparams.Length < 4) { MainConsole.Instance.Warn("Not enough parameters!"); return; } if (cmdparams[2] == "Maturity") { if (cmdparams[3] == "PG") { scene.RegionInfo.AccessLevel = Util.ConvertMaturityToAccessLevel(0); } else if (cmdparams[3] == "Mature") { scene.RegionInfo.AccessLevel = Util.ConvertMaturityToAccessLevel(1); } else if (cmdparams[3] == "Adult") { scene.RegionInfo.AccessLevel = Util.ConvertMaturityToAccessLevel(2); } else { MainConsole.Instance.Warn("Your parameter did not match any existing parameters. Try PG, Mature, or Adult"); return; } scene.RegionInfo.RegionSettings.Save(); //Tell the grid about the changes IGridRegisterModule gridRegModule = scene.RequestModuleInterface<IGridRegisterModule>(); if (gridRegModule != null) gridRegModule.UpdateGridRegion(scene); } #endregion #region 4 Params needed if (cmdparams.Length < 4) { MainConsole.Instance.Warn("Not enough parameters!"); return; } if (cmdparams[2] == "AddEstateBan".ToLower()) { EstateBan EB = new EstateBan { BannedUserID = m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID }; scene.RegionInfo.EstateSettings.AddBan(EB); } if (cmdparams[2] == "AddEstateManager".ToLower()) { scene.RegionInfo.EstateSettings.AddEstateManager( m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID); } if (cmdparams[2] == "AddEstateAccess".ToLower()) { scene.RegionInfo.EstateSettings.AddEstateUser( m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID); } if (cmdparams[2] == "RemoveEstateBan".ToLower()) { scene.RegionInfo.EstateSettings.RemoveBan( m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID); } if (cmdparams[2] == "RemoveEstateManager".ToLower()) { scene.RegionInfo.EstateSettings.RemoveEstateManager( m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID); } if (cmdparams[2] == "RemoveEstateAccess".ToLower()) { scene.RegionInfo.EstateSettings.RemoveEstateUser( m_scenes[0].UserAccountService.GetUserAccount(UUID.Zero, cmdparams[3], cmdparams[4]).PrincipalID); } #endregion scene.RegionInfo.RegionSettings.Save(); scene.RegionInfo.EstateSettings.Save(); } #endregion #region Client private void OnNewClient(IClientAPI client) { client.OnGodlikeMessage += GodlikeMessage; client.OnEstateTelehubRequest += GodlikeMessage; //This is ok, we do estate checks and check to make sure that only telehubs are dealt with here } private void OnClosingClient(IClientAPI client) { client.OnGodlikeMessage -= GodlikeMessage; client.OnEstateTelehubRequest -= GodlikeMessage; } #endregion #region Telehub Settings public void GodlikeMessage(IClientAPI client, UUID requester, string Method, List<string> Parameters) { if (RegionConnector == null) return; IScenePresence Sp = client.Scene.GetScenePresence(client.AgentId); if (!client.Scene.Permissions.CanIssueEstateCommand(client.AgentId, false)) return; string parameter1 = Parameters[0]; if (Method == "telehub") { if (parameter1 == "spawnpoint remove") { Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle); if (telehub == null) return; //Remove the one we sent at X telehub.SpawnPos.RemoveAt(int.Parse(Parameters[1])); RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle); SendTelehubInfo(client); } if (parameter1 == "spawnpoint add") { ISceneChildEntity part = Sp.Scene.GetSceneObjectPart(uint.Parse(Parameters[1])); if (part == null) return; Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle); if (telehub == null) return; telehub.RegionLocX = client.Scene.RegionInfo.RegionLocX; telehub.RegionLocY = client.Scene.RegionInfo.RegionLocY; telehub.RegionID = client.Scene.RegionInfo.RegionID; Vector3 pos = new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ); if (telehub.TelehubLocX == 0 && telehub.TelehubLocY == 0) return; //No spawns without a telehub telehub.SpawnPos.Add(part.AbsolutePosition - pos); //Spawns are offsets RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle); SendTelehubInfo(client); } if (parameter1 == "delete") { RegionConnector.RemoveTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle); SendTelehubInfo(client); } if (parameter1 == "connect") { ISceneChildEntity part = Sp.Scene.GetSceneObjectPart(uint.Parse(Parameters[1])); if (part == null) return; Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle); if (telehub == null) telehub = new Telehub(); telehub.RegionLocX = client.Scene.RegionInfo.RegionLocX; telehub.RegionLocY = client.Scene.RegionInfo.RegionLocY; telehub.RegionID = client.Scene.RegionInfo.RegionID; telehub.TelehubLocX = part.AbsolutePosition.X; telehub.TelehubLocY = part.AbsolutePosition.Y; telehub.TelehubLocZ = part.AbsolutePosition.Z; telehub.TelehubRotX = part.ParentEntity.Rotation.X; telehub.TelehubRotY = part.ParentEntity.Rotation.Y; telehub.TelehubRotZ = part.ParentEntity.Rotation.Z; telehub.ObjectUUID = part.UUID; telehub.Name = part.Name; RegionConnector.AddTelehub(telehub, client.Scene.RegionInfo.RegionHandle); SendTelehubInfo(client); } if (parameter1 == "info ui") SendTelehubInfo(client); } } private void SendTelehubInfo(IClientAPI client) { if (RegionConnector != null) { Telehub telehub = RegionConnector.FindTelehub(client.Scene.RegionInfo.RegionID, client.Scene.RegionInfo.RegionHandle); if (telehub == null) { client.SendTelehubInfo(Vector3.Zero, Quaternion.Identity, new List<Vector3>(), UUID.Zero, ""); } else { Vector3 pos = new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ); Quaternion rot = new Quaternion(telehub.TelehubRotX, telehub.TelehubRotY, telehub.TelehubRotZ); client.SendTelehubInfo(pos, rot, telehub.SpawnPos, telehub.ObjectUUID, telehub.Name); } } } #endregion #region Teleport Permissions private bool OnAllowedIncomingTeleport(UUID userID, IScene scene, Vector3 Position, uint TeleportFlags, out Vector3 newPosition, out string reason) { newPosition = Position; UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID); IScenePresence Sp = scene.GetScenePresence(userID); if (account == null) { IUserAgentService uas = scene.RequestModuleInterface<IUserAgentService>(); AgentCircuitData circuit; if (uas == null || (circuit = scene.AuthenticateHandler.GetAgentCircuitData(userID)) != null || !uas.VerifyAgent(circuit)) { reason = "Failed authentication."; return false; //NO! } } //Make sure that this user is inside the region as well if (Position.X < -2f || Position.Y < -2f || Position.X > scene.RegionInfo.RegionSizeX + 2 || Position.Y > scene.RegionInfo.RegionSizeY + 2) { MainConsole.Instance.DebugFormat( "[EstateService]: AllowedIncomingTeleport was given an illegal position of {0} for avatar {1}, {2}. Clamping", Position, Name, userID); bool changedX = false; bool changedY = false; while (Position.X < 0) { Position.X += scene.RegionInfo.RegionSizeX; changedX = true; } while (Position.X > scene.RegionInfo.RegionSizeX) { Position.X -= scene.RegionInfo.RegionSizeX; changedX = true; } while (Position.Y < 0) { Position.Y += scene.RegionInfo.RegionSizeY; changedY = true; } while (Position.Y > scene.RegionInfo.RegionSizeY) { Position.Y -= scene.RegionInfo.RegionSizeY; changedY = true; } if (changedX) Position.X = scene.RegionInfo.RegionSizeX - Position.X; if (changedY) Position.Y = scene.RegionInfo.RegionSizeY - Position.Y; } IAgentConnector AgentConnector = DataManager.DataManager.RequestPlugin<IAgentConnector>(); IAgentInfo agentInfo = null; if (AgentConnector != null) agentInfo = AgentConnector.GetAgent(userID); ILandObject ILO = null; IParcelManagementModule parcelManagement = scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) ILO = parcelManagement.GetLandObject(Position.X, Position.Y); if (ILO == null) { if (Sp != null) Sp.ClearSavedVelocity(); //If we are moving the agent, clear their velocity //Can't find land, give them the first parcel in the region and find a good position for them ILO = parcelManagement.AllParcels()[0]; Position = parcelManagement.GetParcelCenterAtGround(ILO); } //parcel permissions if (ILO.IsBannedFromLand(userID)) //Note: restricted is dealt with in the next block { if (Sp != null) Sp.ClearSavedVelocity(); //If we are moving the agent, clear their velocity if (Sp == null) { reason = "Banned from this parcel."; return false; } if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason)) { //We found a place for them, but we don't need to check any further on positions here //return true; } } //Move them out of banned parcels ParcelFlags parcelflags = (ParcelFlags) ILO.LandData.Flags; if ((parcelflags & ParcelFlags.UseAccessGroup) == ParcelFlags.UseAccessGroup && (parcelflags & ParcelFlags.UseAccessList) == ParcelFlags.UseAccessList && (parcelflags & ParcelFlags.UsePassList) == ParcelFlags.UsePassList) { if (Sp != null) Sp.ClearSavedVelocity(); //If we are moving the agent, clear their velocity //One of these is in play then if ((parcelflags & ParcelFlags.UseAccessGroup) == ParcelFlags.UseAccessGroup) { if (Sp == null) { reason = "Banned from this parcel."; return false; } if (Sp.ControllingClient.ActiveGroupId != ILO.LandData.GroupID) { if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason)) { //We found a place for them, but we don't need to check any further on positions here //return true; } } } else if ((parcelflags & ParcelFlags.UseAccessList) == ParcelFlags.UseAccessList) { if (Sp == null) { reason = "Banned from this parcel."; return false; } //All but the people on the access list are banned if (ILO.IsRestrictedFromLand(userID)) if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason)) { //We found a place for them, but we don't need to check any further on positions here //return true; } } else if ((parcelflags & ParcelFlags.UsePassList) == ParcelFlags.UsePassList) { if (Sp == null) { reason = "Banned from this parcel."; return false; } //All but the people on the pass/access list are banned if (ILO.IsRestrictedFromLand(Sp.UUID)) if (!FindUnBannedParcel(Position, Sp, userID, out ILO, out newPosition, out reason)) { //We found a place for them, but we don't need to check any further on positions here //return true; } } } EstateSettings ES = scene.RegionInfo.EstateSettings; TeleportFlags tpflags = (TeleportFlags) TeleportFlags; const TeleportFlags allowableFlags = OpenMetaverse.TeleportFlags.ViaLandmark | OpenMetaverse.TeleportFlags.ViaHome | OpenMetaverse.TeleportFlags.ViaLure | OpenMetaverse.TeleportFlags.ForceRedirect | OpenMetaverse.TeleportFlags.Godlike | OpenMetaverse.TeleportFlags.NineOneOne; //If the user wants to force landing points on crossing, we act like they are not crossing, otherwise, check the child property and that the ViaRegionID is set bool isCrossing = !ForceLandingPointsOnCrossing && (Sp != null && Sp.IsChildAgent && ((tpflags & OpenMetaverse.TeleportFlags.ViaRegionID) == OpenMetaverse.TeleportFlags.ViaRegionID)); //Move them to the nearest landing point if (!((tpflags & allowableFlags) != 0) && !isCrossing && !ES.AllowDirectTeleport) { if (Sp != null) Sp.ClearSavedVelocity(); //If we are moving the agent, clear their velocity if (!scene.Permissions.IsGod(userID)) { Telehub telehub = RegionConnector.FindTelehub(scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle); if (telehub != null) { if (telehub.SpawnPos.Count == 0) { Position = new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ); } else { int LastTelehubNum = 0; if (!LastTelehub.TryGetValue(scene.RegionInfo.RegionID, out LastTelehubNum)) LastTelehubNum = 0; Position = telehub.SpawnPos[LastTelehubNum] + new Vector3(telehub.TelehubLocX, telehub.TelehubLocY, telehub.TelehubLocZ); LastTelehubNum++; if (LastTelehubNum == telehub.SpawnPos.Count) LastTelehubNum = 0; LastTelehub[scene.RegionInfo.RegionID] = LastTelehubNum; } } } } else if (!((tpflags & allowableFlags) != 0) && !isCrossing && !scene.Permissions.GenericParcelPermission(userID, ILO, (ulong) GroupPowers.None)) //Telehubs override parcels { if (Sp != null) Sp.ClearSavedVelocity(); //If we are moving the agent, clear their velocity if (ILO.LandData.LandingType == (int) LandingType.None) //Blocked, force this person off this land { //Find a new parcel for them List<ILandObject> Parcels = parcelManagement.ParcelsNearPoint(Position); if (Parcels.Count > 1) { newPosition = parcelManagement.GetNearestRegionEdgePosition(Sp); } else { bool found = false; //We need to check here as well for bans, can't toss someone into a parcel they are banned from #if (!ISWIN) foreach (ILandObject Parcel in Parcels) { if (!Parcel.IsBannedFromLand(userID)) { //Now we have to check their userloc if (ILO.LandData.LandingType == (int) LandingType.None) continue; //Blocked, check next one else if (ILO.LandData.LandingType == (int) LandingType.LandingPoint) //Use their landing spot newPosition = Parcel.LandData.UserLocation; else //They allow for anywhere, so dump them in the center at the ground newPosition = parcelManagement.GetParcelCenterAtGround(Parcel); found = true; } } #else foreach (ILandObject Parcel in Parcels.Where(Parcel => !Parcel.IsBannedFromLand(userID))) { //Now we have to check their userloc if (ILO.LandData.LandingType == (int) LandingType.None) continue; //Blocked, check next one else if (ILO.LandData.LandingType == (int) LandingType.LandingPoint) //Use their landing spot newPosition = Parcel.LandData.UserLocation; else //They allow for anywhere, so dump them in the center at the ground newPosition = parcelManagement.GetParcelCenterAtGround(Parcel); found = true; } #endif if (!found) //Dump them at the edge { if (Sp != null) newPosition = parcelManagement.GetNearestRegionEdgePosition(Sp); else { reason = "Banned from this parcel."; return false; } } } } else if (ILO.LandData.LandingType == (int) LandingType.LandingPoint) //Move to tp spot newPosition = ILO.LandData.UserLocation != Vector3.Zero ? ILO.LandData.UserLocation : parcelManagement.GetNearestRegionEdgePosition(Sp); } //We assume that our own region isn't null.... if (agentInfo != null) { //Can only enter prelude regions once! if (scene.RegionInfo.RegionFlags != -1 && ((scene.RegionInfo.RegionFlags & (int)RegionFlags.Prelude) == (int)RegionFlags.Prelude) && agentInfo != null) { if (agentInfo.OtherAgentInformation.ContainsKey("Prelude" + scene.RegionInfo.RegionID)) { reason = "You may not enter this region as you have already been to this prelude region."; return false; } else { agentInfo.OtherAgentInformation.Add("Prelude" + scene.RegionInfo.RegionID, OSD.FromInteger((int) IAgentFlags.PastPrelude)); AgentConnector.UpdateAgent(agentInfo); } } if (agentInfo.OtherAgentInformation.ContainsKey("LimitedToEstate")) { int LimitedToEstate = agentInfo.OtherAgentInformation["LimitedToEstate"]; if (scene.RegionInfo.EstateSettings.EstateID != LimitedToEstate) { reason = "You may not enter this reason, as it is outside of the estate you are limited to."; return false; } } } if ((ILO.LandData.Flags & (int) ParcelFlags.DenyAnonymous) != 0) { if (account != null && (account.UserFlags & (int) IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile) == (int) IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile) { reason = "You may not enter this region."; return false; } } if ((ILO.LandData.Flags & (uint) ParcelFlags.DenyAgeUnverified) != 0 && agentInfo != null) { if ((agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor) { reason = "You may not enter this region."; return false; } } //Check that we are not underground as well ITerrainChannel chan = scene.RequestModuleInterface<ITerrainChannel>(); if (chan != null) { float posZLimit = chan[(int) newPosition.X, (int) newPosition.Y] + (float) 1.25; if (posZLimit >= (newPosition.Z) && !(Single.IsInfinity(posZLimit) || Single.IsNaN(posZLimit))) { newPosition.Z = posZLimit; } } //newPosition = Position; reason = ""; return true; } private bool OnAllowedIncomingAgent(IScene scene, AgentCircuitData agent, bool isRootAgent, out string reason) { #region Incoming Agent Checks UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agent.AgentID); bool foreign = false; IScenePresence Sp = scene.GetScenePresence(agent.AgentID); if (account == null) { IUserAgentService uas = scene.RequestModuleInterface<IUserAgentService>(); if (uas != null) //SOO hate doing this... foreign = true; } if (LoginsDisabled) { reason = "Logins Disabled"; return false; } //Check how long its been since the last TP if (m_enabledBlockTeleportSeconds && Sp != null && !Sp.IsChildAgent) { if (TimeSinceLastTeleport.ContainsKey(Sp.Scene.RegionInfo.RegionID)) { if (TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] > Util.UnixTimeSinceEpoch()) { reason = "Too many teleports. Please try again soon."; return false; // Too soon since the last TP } } TimeSinceLastTeleport[Sp.Scene.RegionInfo.RegionID] = Util.UnixTimeSinceEpoch() + ((int) (SecondsBeforeNextTeleport)); } //Gods tp freely if ((Sp != null && Sp.GodLevel != 0) || (account != null && account.UserLevel != 0)) { reason = ""; return true; } //Check whether they fit any ban criteria if (Sp != null) { foreach (string banstr in BanCriteria) { if (Sp.Name.Contains(banstr)) { reason = "You have been banned from this region."; return false; } else if (((IPEndPoint) Sp.ControllingClient.GetClientEP()).Address.ToString().Contains(banstr)) { reason = "You have been banned from this region."; return false; } } //Make sure they exist in the grid right now IAgentInfoService presence = scene.RequestModuleInterface<IAgentInfoService>(); if (presence == null) { reason = String.Format( "Failed to verify user presence in the grid for {0} in region {1}. Presence service does not exist.", account.Name, scene.RegionInfo.RegionName); return false; } UserInfo pinfo = presence.GetUserInfo(agent.AgentID.ToString()); if (!foreign && (pinfo == null || (!pinfo.IsOnline && ((agent.teleportFlags & (uint) TeleportFlags.ViaLogin) == 0)))) { reason = String.Format( "Failed to verify user presence in the grid for {0}, access denied to region {1}.", account.Name, scene.RegionInfo.RegionName); return false; } } EstateSettings ES = scene.RegionInfo.EstateSettings; IEntityCountModule entityCountModule = scene.RequestModuleInterface<IEntityCountModule>(); if (entityCountModule != null && scene.RegionInfo.RegionSettings.AgentLimit < entityCountModule.RootAgents + 1) { reason = "Too many agents at this time. Please come back later."; return false; } List<EstateBan> EstateBans = new List<EstateBan>(ES.EstateBans); int i = 0; //Check bans foreach (EstateBan ban in EstateBans) { if (ban.BannedUserID == agent.AgentID) { if (Sp != null) { string banIP = ((IPEndPoint) Sp.ControllingClient.GetClientEP()).Address.ToString(); if (ban.BannedHostIPMask != banIP) //If it changed, ban them again { //Add the ban with the new hostname ES.AddBan(new EstateBan { BannedHostIPMask = banIP, BannedUserID = ban.BannedUserID, EstateID = ban.EstateID, BannedHostAddress = ban.BannedHostAddress, BannedHostNameMask = ban.BannedHostNameMask }); //Update the database ES.Save(); } } reason = "Banned from this region."; return false; } if (Sp != null) { IPAddress end = Sp.ControllingClient.EndPoint; IPHostEntry rDNS = null; try { rDNS = Dns.GetHostEntry(end); } catch (SocketException) { MainConsole.Instance.WarnFormat("[IPBAN] IP address \"{0}\" cannot be resolved via DNS", end); rDNS = null; } if (ban.BannedHostIPMask == agent.IPAddress || (rDNS != null && rDNS.HostName.Contains(ban.BannedHostIPMask)) || end.ToString().StartsWith(ban.BannedHostIPMask)) { //Ban the new user ES.AddBan(new EstateBan { EstateID = ES.EstateID, BannedHostIPMask = agent.IPAddress, BannedUserID = agent.AgentID, BannedHostAddress = agent.IPAddress, BannedHostNameMask = agent.IPAddress }); ES.Save(); reason = "Banned from this region."; return false; } } i++; } //Estate owners/managers/access list people/access groups tp freely as well if (ES.EstateOwner == agent.AgentID || new List<UUID>(ES.EstateManagers).Contains(agent.AgentID) || new List<UUID>(ES.EstateAccess).Contains(agent.AgentID) || CheckEstateGroups(ES, agent)) { reason = ""; return true; } if (account != null && ES.DenyAnonymous && ((account.UserFlags & (int) IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile) == (int) IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile)) { reason = "You may not enter this region."; return false; } if (account != null && ES.DenyIdentified && ((account.UserFlags & (int) IUserProfileInfo.ProfileFlags.PaymentInfoOnFile) == (int) IUserProfileInfo.ProfileFlags.PaymentInfoOnFile)) { reason = "You may not enter this region."; return false; } if (account != null && ES.DenyTransacted && ((account.UserFlags & (int) IUserProfileInfo.ProfileFlags.PaymentInfoInUse) == (int) IUserProfileInfo.ProfileFlags.PaymentInfoInUse)) { reason = "You may not enter this region."; return false; } const long m_Day = 25*60*60; //Find out day length in seconds if (account != null && scene.RegionInfo.RegionSettings.MinimumAge != 0 && (account.Created - Util.UnixTimeSinceEpoch()) < (scene.RegionInfo.RegionSettings.MinimumAge*m_Day)) { reason = "You may not enter this region."; return false; } if (!ES.PublicAccess) { reason = "You may not enter this region, Public access has been turned off."; return false; } IAgentConnector AgentConnector = DataManager.DataManager.RequestPlugin<IAgentConnector>(); IAgentInfo agentInfo = null; if (AgentConnector != null) { agentInfo = AgentConnector.GetAgent(agent.AgentID); if (agentInfo == null) { AgentConnector.CreateNewAgent(agent.AgentID); agentInfo = AgentConnector.GetAgent(agent.AgentID); } } if (m_checkMaturityLevel) { if (agentInfo != null && scene.RegionInfo.AccessLevel > Util.ConvertMaturityToAccessLevel((uint) agentInfo.MaturityRating)) { reason = "The region has too high of a maturity level. Blocking teleport."; return false; } if (agentInfo != null && ES.DenyMinors && (agentInfo.Flags & IAgentFlags.Minor) == IAgentFlags.Minor) { reason = "The region has too high of a maturity level. Blocking teleport."; return false; } } #endregion reason = ""; return true; } private bool CheckEstateGroups(EstateSettings ES, AgentCircuitData agent) { IGroupsModule gm = m_scenes.Count == 0 ? null : m_scenes[0].RequestModuleInterface<IGroupsModule>(); if (gm != null && ES.EstateGroups.Length > 0) { List<UUID> esGroups = new List<UUID>(ES.EstateGroups); GroupMembershipData[] gmds = gm.GetMembershipData(agent.AgentID); #if (!ISWIN) foreach (GroupMembershipData gmd in gmds) { if (esGroups.Contains(gmd.GroupID)) return true; } return false; #else return gmds.Any(gmd => esGroups.Contains(gmd.GroupID)); #endif } return false; } private bool FindUnBannedParcel(Vector3 Position, IScenePresence Sp, UUID AgentID, out ILandObject ILO, out Vector3 newPosition, out string reason) { ILO = null; IParcelManagementModule parcelManagement = Sp.Scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { List<ILandObject> Parcels = parcelManagement.ParcelsNearPoint(Position); if (Parcels.Count == 0) { newPosition = Sp == null ? new Vector3(0, 0, 0) : parcelManagement.GetNearestRegionEdgePosition(Sp); ILO = null; //Dumped in the region corner, we will leave them there reason = ""; return false; } else { bool FoundParcel = false; #if (!ISWIN) foreach (ILandObject lo in Parcels) { if (!lo.IsEitherBannedOrRestricted(AgentID)) { newPosition = lo.LandData.UserLocation; ILO = lo; //Update the parcel settings FoundParcel = true; break; } } #else foreach (ILandObject lo in Parcels.Where(lo => !lo.IsEitherBannedOrRestricted(AgentID))) { newPosition = lo.LandData.UserLocation; ILO = lo; //Update the parcel settings FoundParcel = true; break; } #endif if (!FoundParcel) { //Dump them in the region corner as they are banned from all nearby parcels newPosition = Sp == null ? new Vector3(0, 0, 0) : parcelManagement.GetNearestRegionEdgePosition(Sp); reason = ""; ILO = null; return false; } } } newPosition = Position; reason = ""; return true; } #endregion #region ISharedRegionStartupModule Members public void Initialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { IConfig config = source.Configs["EstateSettingsModule"]; if (config != null) { m_enabled = config.GetBoolean("Enabled", true); m_enabledBlockTeleportSeconds = config.GetBoolean("AllowBlockTeleportsMinTime", true); SecondsBeforeNextTeleport = config.GetFloat("BlockTeleportsTime", 3); StartDisabled = config.GetBoolean("StartDisabled", StartDisabled); ForceLandingPointsOnCrossing = config.GetBoolean("ForceLandingPointsOnCrossing", ForceLandingPointsOnCrossing); m_checkMaturityLevel = config.GetBoolean("CheckMaturityLevel", true); string banCriteriaString = config.GetString("BanCriteria", ""); if (banCriteriaString != "") BanCriteria = banCriteriaString.Split(','); } if (!m_enabled) return; m_scenes.Add(scene); RegionConnector = DataManager.DataManager.RequestPlugin<IRegionConnector>(); scene.EventManager.OnNewClient += OnNewClient; scene.Permissions.OnAllowIncomingAgent += OnAllowedIncomingAgent; scene.Permissions.OnAllowedIncomingTeleport += OnAllowedIncomingTeleport; scene.EventManager.OnClosingClient += OnClosingClient; if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand( "set regionsetting maturity", "set regionsetting maturity [value]", "Sets a region's maturity - 0(PG),1(Mature),2(Adult)", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting addestateban", "set regionsetting addestateban [first] [last]", "Add a user to the estate ban list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting removeestateban", "set regionsetting removeestateban [first] [last]", "Remove a user from the estate ban list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting addestatemanager", "set regionsetting addestatemanager [first] [last]", "Add a user to the estate manager list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting removeestatemanager", "set regionsetting removeestatemanager [first] [last]", "Remove a user from the estate manager list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting addestateaccess", "set regionsetting addestateaccess [first] [last]", "Add a user to the estate access list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "set regionsetting removeestateaccess", "set regionsetting removeestateaccess [first] [last]", "Remove a user from the estate access list", SetRegionInfoOption); MainConsole.Instance.Commands.AddCommand( "estate ban user", "estate ban user", "Bans a user from the current estate", BanUser); MainConsole.Instance.Commands.AddCommand( "estate unban user", "estate unban user", "Bans a user from the current estate", UnBanUser); MainConsole.Instance.Commands.AddCommand( "login enable", "login enable", "Enable simulator logins", ProcessLoginCommands); MainConsole.Instance.Commands.AddCommand( "login disable", "login disable", "Disable simulator logins", ProcessLoginCommands); MainConsole.Instance.Commands.AddCommand( "login status", "login status", "Show login status", ProcessLoginCommands); } } public void PostInitialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void FinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void PostFinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void Close(IScene scene) { if (!m_enabled) return; m_scenes.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.Permissions.OnAllowIncomingAgent -= OnAllowedIncomingAgent; scene.Permissions.OnAllowedIncomingTeleport -= OnAllowedIncomingTeleport; scene.EventManager.OnClosingClient -= OnClosingClient; } public void DeleteRegion(IScene scene) { } public void StartupComplete() { if (!StartDisabled) { MainConsole.Instance.DebugFormat("[Region]: Enabling logins"); LoginsDisabled = false; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { /// <devdoc> /// <para> /// Provides access to local and remote /// processes. Enables you to start and stop system processes. /// </para> /// </devdoc> public partial class Process : Component { private bool _haveProcessId; private int _processId; private bool _haveProcessHandle; private SafeProcessHandle _processHandle; private bool _isRemoteMachine; private string _machineName; private ProcessInfo _processInfo; private ProcessThreadCollection _threads; private ProcessModuleCollection _modules; private bool _haveWorkingSetLimits; private IntPtr _minWorkingSet; private IntPtr _maxWorkingSet; private bool _haveProcessorAffinity; private IntPtr _processorAffinity; private bool _havePriorityClass; private ProcessPriorityClass _priorityClass; private ProcessStartInfo _startInfo; private bool _watchForExit; private bool _watchingForExit; private EventHandler _onExited; private bool _exited; private int _exitCode; private DateTime? _startTime; private DateTime _exitTime; private bool _haveExitTime; private bool _priorityBoostEnabled; private bool _havePriorityBoostEnabled; private bool _raisedOnExited; private RegisteredWaitHandle _registeredWaitHandle; private WaitHandle _waitHandle; private StreamReader _standardOutput; private StreamWriter _standardInput; private StreamReader _standardError; private bool _disposed; private bool _haveMainWindow; private IntPtr _mainWindowHandle; private string _mainWindowTitle; private bool _haveResponding; private bool _responding; private static object s_createProcessLock = new object(); private StreamReadMode _outputStreamReadMode; private StreamReadMode _errorStreamReadMode; // Support for asynchronously reading streams public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; // Abstract the stream details internal AsyncStreamReader _output; internal AsyncStreamReader _error; internal bool _pendingOutputRead; internal bool _pendingErrorRead; #if FEATURE_TRACESWITCH internal static TraceSwitch _processTracing = #if DEBUG new TraceSwitch("processTracing", "Controls debug output from Process component"); #else null; #endif #endif /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class. /// </para> /// </devdoc> public Process() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Process)) { GC.SuppressFinalize(this); } _machineName = "."; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) { GC.SuppressFinalize(this); _processInfo = processInfo; _machineName = machineName; _isRemoteMachine = isRemoteMachine; _processId = processId; _haveProcessId = true; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } public SafeProcessHandle SafeHandle { get { EnsureState(State.Associated); return OpenProcessHandle(); } } public IntPtr Handle => SafeHandle.DangerousGetHandle(); /// <devdoc> /// Returns whether this process component is associated with a real process. /// </devdoc> /// <internalonly/> bool Associated { get { return _haveProcessId || _haveProcessHandle; } } /// <devdoc> /// <para> /// Gets the base priority of /// the associated process. /// </para> /// </devdoc> public int BasePriority { get { EnsureState(State.HaveProcessInfo); return _processInfo.BasePriority; } } /// <devdoc> /// <para> /// Gets /// the /// value that was specified by the associated process when it was terminated. /// </para> /// </devdoc> public int ExitCode { get { EnsureState(State.Exited); return _exitCode; } } /// <devdoc> /// <para> /// Gets a /// value indicating whether the associated process has been terminated. /// </para> /// </devdoc> public bool HasExited { get { if (!_exited) { EnsureState(State.Associated); UpdateHasExited(); if (_exited) { RaiseOnExited(); } } return _exited; } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { if (!_startTime.HasValue) { _startTime = StartTimeCore; } return _startTime.Value; } } /// <devdoc> /// <para> /// Gets the time that the associated process exited. /// </para> /// </devdoc> public DateTime ExitTime { get { if (!_haveExitTime) { EnsureState(State.Exited); _exitTime = ExitTimeCore; _haveExitTime = true; } return _exitTime; } } /// <devdoc> /// <para> /// Gets /// the unique identifier for the associated process. /// </para> /// </devdoc> public int Id { get { EnsureState(State.HaveId); return _processId; } } /// <devdoc> /// <para> /// Gets /// the name of the computer on which the associated process is running. /// </para> /// </devdoc> public string MachineName { get { EnsureState(State.Associated); return _machineName; } } /// <devdoc> /// <para> /// Gets or sets the maximum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MaxWorkingSet { get { EnsureWorkingSetLimits(); return _maxWorkingSet; } set { SetWorkingSetLimits(null, value); } } /// <devdoc> /// <para> /// Gets or sets the minimum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MinWorkingSet { get { EnsureWorkingSetLimits(); return _minWorkingSet; } set { SetWorkingSetLimits(value, null); } } public ProcessModuleCollection Modules { get { if (_modules == null) { EnsureState(State.HaveId | State.IsLocal); _modules = ProcessManager.GetModules(_processId); } return _modules; } } public long NonpagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolNonPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int NonpagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolNonPagedBytes); } } public long PagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytes); } } public long PagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolPagedBytes); } } public long PeakPagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakPagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytesPeak); } } public long PeakWorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSetPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakWorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSetPeak); } } public long PeakVirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakVirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytesPeak); } } /// <devdoc> /// <para> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </para> /// </devdoc> public bool PriorityBoostEnabled { get { if (!_havePriorityBoostEnabled) { _priorityBoostEnabled = PriorityBoostEnabledCore; _havePriorityBoostEnabled = true; } return _priorityBoostEnabled; } set { PriorityBoostEnabledCore = value; _priorityBoostEnabled = value; _havePriorityBoostEnabled = true; } } /// <devdoc> /// <para> /// Gets or sets the overall priority category for the /// associated process. /// </para> /// </devdoc> public ProcessPriorityClass PriorityClass { get { if (!_havePriorityClass) { _priorityClass = PriorityClassCore; _havePriorityClass = true; } return _priorityClass; } set { if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass)); } PriorityClassCore = value; _priorityClass = value; _havePriorityClass = true; } } public long PrivateMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PrivateBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PrivateMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PrivateBytes); } } /// <devdoc> /// <para> /// Gets /// the friendly name of the process. /// </para> /// </devdoc> public string ProcessName { get { EnsureState(State.HaveProcessInfo); return _processInfo.ProcessName; } } /// <devdoc> /// <para> /// Gets /// or sets which processors the threads in this process can be scheduled to run on. /// </para> /// </devdoc> public IntPtr ProcessorAffinity { get { if (!_haveProcessorAffinity) { _processorAffinity = ProcessorAffinityCore; _haveProcessorAffinity = true; } return _processorAffinity; } set { ProcessorAffinityCore = value; _processorAffinity = value; _haveProcessorAffinity = true; } } public int SessionId { get { EnsureState(State.HaveProcessInfo); return _processInfo.SessionId; } } /// <devdoc> /// <para> /// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/> /// . /// </para> /// </devdoc> public ProcessStartInfo StartInfo { get { if (_startInfo == null) { if (Associated) { throw new InvalidOperationException(SR.CantGetProcessStartInfo); } _startInfo = new ProcessStartInfo(); } return _startInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Associated) { throw new InvalidOperationException(SR.CantSetProcessStartInfo); } _startInfo = value; } } /// <devdoc> /// <para> /// Gets the set of threads that are running in the associated /// process. /// </para> /// </devdoc> public ProcessThreadCollection Threads { get { if (_threads == null) { EnsureState(State.HaveProcessInfo); int count = _processInfo._threadInfoList.Count; ProcessThread[] newThreadsArray = new ProcessThread[count]; for (int i = 0; i < count; i++) { newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]); } ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray); _threads = newThreads; } return _threads; } } public int HandleCount { get { EnsureState(State.HaveProcessInfo); EnsureHandleCountPopulated(); return _processInfo.HandleCount; } } partial void EnsureHandleCountPopulated(); [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public long VirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytes; } } public int VirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytes); } } /// <devdoc> /// <para> /// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/> /// event is fired /// when the process terminates. /// </para> /// </devdoc> public bool EnableRaisingEvents { get { return _watchForExit; } set { if (value != _watchForExit) { if (Associated) { if (value) { OpenProcessHandle(); EnsureWatchingForExit(); } else { StopWatchingForExit(); } } _watchForExit = value; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamWriter StandardInput { get { if (_standardInput == null) { throw new InvalidOperationException(SR.CantGetStandardIn); } return _standardInput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardOutput { get { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.SyncMode; } else if (_outputStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardOutput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardError { get { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.SyncMode; } else if (_errorStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardError; } } public long WorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSet; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int WorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSet); } } public event EventHandler Exited { add { _onExited += value; } remove { _onExited -= value; } } /// <devdoc> /// This is called from the threadpool when a process exits. /// </devdoc> /// <internalonly/> private void CompletionCallback(object context, bool wasSignaled) { StopWatchingForExit(); RaiseOnExited(); } /// <internalonly/> /// <devdoc> /// <para> /// Free any resources associated with this component. /// </para> /// </devdoc> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Dispose managed and unmanaged resources Close(); } _disposed = true; } } public bool Responding { get { if (!_haveResponding) { _responding = IsRespondingCore(); _haveResponding = true; } return _responding; } } public string MainWindowTitle { get { if (_mainWindowTitle == null) { _mainWindowTitle = GetMainWindowTitle(); } return _mainWindowTitle; } } public bool CloseMainWindow() { return CloseMainWindowCore(); } public bool WaitForInputIdle() { return WaitForInputIdle(int.MaxValue); } public bool WaitForInputIdle(int milliseconds) { return WaitForInputIdleCore(milliseconds); } public IntPtr MainWindowHandle { get { if (!_haveMainWindow) { EnsureState(State.IsLocal | State.HaveId); _mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId); _haveMainWindow = true; } return _mainWindowHandle; } } public ISynchronizeInvoke SynchronizingObject { get; set; } /// <devdoc> /// <para> /// Frees any resources associated with this component. /// </para> /// </devdoc> public void Close() { if (Associated) { if (_haveProcessHandle) { StopWatchingForExit(); #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()"); #endif _processHandle.Dispose(); _processHandle = null; _haveProcessHandle = false; } _haveProcessId = false; _isRemoteMachine = false; _machineName = "."; _raisedOnExited = false; //Don't call close on the Readers and writers //since they might be referenced by somebody else while the //process is still alive but this method called. _standardOutput = null; _standardInput = null; _standardError = null; _output = null; _error = null; CloseCore(); Refresh(); } } /// <devdoc> /// Helper method for checking preconditions when accessing properties. /// </devdoc> /// <internalonly/> private void EnsureState(State state) { if ((state & State.Associated) != (State)0) if (!Associated) throw new InvalidOperationException(SR.NoAssociatedProcess); if ((state & State.HaveId) != (State)0) { if (!_haveProcessId) { if (_haveProcessHandle) { SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle)); } else { EnsureState(State.Associated); throw new InvalidOperationException(SR.ProcessIdRequired); } } } if ((state & State.IsLocal) != (State)0 && _isRemoteMachine) { throw new NotSupportedException(SR.NotSupportedRemote); } if ((state & State.HaveProcessInfo) != (State)0) { if (_processInfo == null) { if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId); _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); if (_processInfo == null) { throw new InvalidOperationException(SR.NoProcessInfo); } } } if ((state & State.Exited) != (State)0) { if (!HasExited) { throw new InvalidOperationException(SR.WaitTillExit); } if (!_haveProcessHandle) { throw new InvalidOperationException(SR.NoProcessHandle); } } } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), null, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <devdoc> /// Make sure we have obtained the min and max working set limits. /// </devdoc> /// <internalonly/> private void EnsureWorkingSetLimits() { if (!_haveWorkingSetLimits) { GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } } /// <devdoc> /// Helper to set minimum or maximum working set limits. /// </devdoc> /// <internalonly/> private void SetWorkingSetLimits(IntPtr? min, IntPtr? max) { SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and /// the name of a computer in the network. /// </para> /// </devdoc> public static Process GetProcessById(int processId, string machineName) { if (!ProcessManager.IsProcessRunning(processId, machineName)) { throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture))); } return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null); } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given the /// identifier of a process on the local computer. /// </para> /// </devdoc> public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } /// <devdoc> /// <para> /// Creates an array of <see cref='System.Diagnostics.Process'/> components that are /// associated /// with process resources on the /// local computer. These process resources share the specified process name. /// </para> /// </devdoc> public static Process[] GetProcessesByName(string processName) { return GetProcessesByName(processName, "."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each process resource on the local computer. /// </para> /// </devdoc> public static Process[] GetProcesses() { return GetProcesses("."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each /// process resource on the specified computer. /// </para> /// </devdoc> public static Process[] GetProcesses(string machineName) { bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName); ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); Process[] processes = new Process[processInfos.Length]; for (int i = 0; i < processInfos.Length; i++) { ProcessInfo processInfo = processInfos[i]; processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo); } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")"); #if DEBUG if (_processTracing.TraceVerbose) { Debug.Indent(); for (int i = 0; i < processInfos.Length; i++) { Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName); } Debug.Unindent(); } #endif #endif return processes; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> /// component and associates it with the current active process. /// </para> /// </devdoc> public static Process GetCurrentProcess() { return new Process(".", false, GetCurrentProcessId(), null); } /// <devdoc> /// <para> /// Raises the <see cref='System.Diagnostics.Process.Exited'/> event. /// </para> /// </devdoc> protected void OnExited() { EventHandler exited = _onExited; if (exited != null) { exited(this, EventArgs.Empty); } } /// <devdoc> /// Raise the Exited event, but make sure we don't do it more than once. /// </devdoc> /// <internalonly/> private void RaiseOnExited() { if (!_raisedOnExited) { lock (this) { if (!_raisedOnExited) { _raisedOnExited = true; OnExited(); } } } } /// <devdoc> /// <para> /// Discards any information about the associated process /// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the /// first request for information for each property causes the process component /// to obtain a new value from the associated process. /// </para> /// </devdoc> public void Refresh() { _processInfo = null; _threads = null; _modules = null; _exited = false; _haveWorkingSetLimits = false; _haveProcessorAffinity = false; _havePriorityClass = false; _haveExitTime = false; _havePriorityBoostEnabled = false; RefreshCore(); } /// <summary> /// Opens a long-term handle to the process, with all access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle OpenProcessHandle() { if (!_haveProcessHandle) { //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } SetProcessHandle(GetProcessHandle()); } return _processHandle; } /// <devdoc> /// Helper to associate a process handle with this component. /// </devdoc> /// <internalonly/> private void SetProcessHandle(SafeProcessHandle processHandle) { _processHandle = processHandle; _haveProcessHandle = true; if (_watchForExit) { EnsureWatchingForExit(); } } /// <devdoc> /// Helper to associate a process id with this component. /// </devdoc> /// <internalonly/> private void SetProcessId(int processId) { _processId = processId; _haveProcessId = true; ConfigureAfterProcessIdSet(); } /// <summary>Additional optional configuration hook after a process ID is set.</summary> partial void ConfigureAfterProcessIdSet(); /// <devdoc> /// <para> /// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/> /// component and associates it with the /// <see cref='System.Diagnostics.Process'/> . If a process resource is reused /// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) { throw new InvalidOperationException(SR.FileNameMissing); } if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } return StartCore(startInfo); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of a /// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName) { return Start(new ProcessStartInfo(fileName)); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of an /// application and a set of command line arguments. Associates the process resource /// with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName, string arguments) { return Start(new ProcessStartInfo(fileName, arguments)); } /// <devdoc> /// <para> /// Starts a process resource specified by the process start /// information passed in, for example the file name of the process to start. /// Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; return process.Start() ? process : null; } /// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } } public override string ToString() { if (Associated) { string processName = ProcessName; if (processName.Length != 0) { return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName); } } return base.ToString(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to wait /// indefinitely for the associated process to exit. /// </para> /// </devdoc> public void WaitForExit() { WaitForExit(Timeout.Infinite); } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for /// the associated process to exit. /// </summary> public bool WaitForExit(int milliseconds) { bool exited = WaitForExitCore(milliseconds); if (exited && _watchForExit) { RaiseOnExited(); } return exited; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardOutput stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to OutputDataReceived. /// </para> /// </devdoc> public void BeginOutputReadLine() { if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.AsyncMode; } else if (_outputStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingOutputRead) throw new InvalidOperationException(SR.PendingAsyncOperation); _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_output == null) { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } Stream s = _standardOutput.BaseStream; _output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding); } _output.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardError stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived. /// </para> /// </devdoc> public void BeginErrorReadLine() { if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.AsyncMode; } else if (_errorStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingErrorRead) { throw new InvalidOperationException(SR.PendingAsyncOperation); } _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_error == null) { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } Stream s = _standardError.BaseStream; _error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding); } _error.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginOutputReadLine(). /// </para> /// </devdoc> public void CancelOutputRead() { if (_output != null) { _output.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingOutputRead = false; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginErrorReadLine(). /// </para> /// </devdoc> public void CancelErrorRead() { if (_error != null) { _error.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingErrorRead = false; } internal void OutputReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler outputDataReceived = OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); outputDataReceived(this, e); // Call back to user informing data is available } } internal void ErrorReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler errorDataReceived = ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); errorDataReceived(this, e); // Call back to user informing data is available. } } /// <summary> /// This enum defines the operation mode for redirected process stream. /// We don't support switching between synchronous mode and asynchronous mode. /// </summary> private enum StreamReadMode { Undefined, SyncMode, AsyncMode } /// <summary>A desired internal state.</summary> private enum State { HaveId = 0x1, IsLocal = 0x2, HaveProcessInfo = 0x8, Exited = 0x10, Associated = 0x20, } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace System.Data.SqlClient { public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder { private enum Keywords { // specific ordering for ConnectionString output construction // NamedConnection, DataSource, FailoverPartner, AttachDBFilename, InitialCatalog, IntegratedSecurity, PersistSecurityInfo, UserID, Password, Enlist, Pooling, MinPoolSize, MaxPoolSize, MultipleActiveResultSets, Replication, ConnectTimeout, Encrypt, TrustServerCertificate, LoadBalanceTimeout, PacketSize, TypeSystemVersion, ApplicationName, CurrentLanguage, WorkstationID, UserInstance, TransactionBinding, ApplicationIntent, MultiSubnetFailover, ConnectRetryCount, ConnectRetryInterval, // keep the count value last KeywordsCount } internal const int KeywordsCount = (int)Keywords.KeywordsCount; internal const int DeprecatedKeywordsCount = 4; private static readonly string[] s_validKeywords = CreateValidKeywords(); private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary(); private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent; private string _applicationName = DbConnectionStringDefaults.ApplicationName; private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename; private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage; private string _dataSource = DbConnectionStringDefaults.DataSource; private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner; private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog; // private string _namedConnection = DbConnectionStringDefaults.NamedConnection; private string _password = DbConnectionStringDefaults.Password; private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding; private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion; private string _userID = DbConnectionStringDefaults.UserID; private string _workstationID = DbConnectionStringDefaults.WorkstationID; private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize; private int _packetSize = DbConnectionStringDefaults.PacketSize; private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount; private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval; private bool _encrypt = DbConnectionStringDefaults.Encrypt; private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate; private bool _enlist = DbConnectionStringDefaults.Enlist; private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity; private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets; private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo; private bool _pooling = DbConnectionStringDefaults.Pooling; private bool _replication = DbConnectionStringDefaults.Replication; private bool _userInstance = DbConnectionStringDefaults.UserInstance; private static string[] CreateValidKeywords() { string[] validKeywords = new string[KeywordsCount]; validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent; validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName; validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename; validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout; validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage; validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource; validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt; validKeywords[(int)Keywords.Enlist] = DbConnectionStringKeywords.Enlist; validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner; validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog; validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity; validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout; validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize; validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize; validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets; validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover; // validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection; validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize; validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password; validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo; validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling; validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication; validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding; validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate; validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion; validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID; validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance; validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID; validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount; validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval; return validKeywords; } private static Dictionary<string, Keywords> CreateKeywordsDictionary() { Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase); hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent); hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName); hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename); hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout); hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage); hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource); hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt); hash.Add(DbConnectionStringKeywords.Enlist, Keywords.Enlist); hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner); hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog); hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity); hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout); hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets); hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize); hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize); hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover); // hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection); hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize); hash.Add(DbConnectionStringKeywords.Password, Keywords.Password); hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo); hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling); hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication); hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding); hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate); hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion); hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID); hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance); hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID); hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount); hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval); hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName); hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename); hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename); hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout); hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout); hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage); hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog); hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity); hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout); hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password); hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo); hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID); hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID); hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID); Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect"); return hash; } public SqlConnectionStringBuilder() : this((string)null) { } public SqlConnectionStringBuilder(string connectionString) : base() { if (!string.IsNullOrEmpty(connectionString)) { ConnectionString = connectionString; } } public override object this[string keyword] { get { Keywords index = GetIndex(keyword); return GetAt(index); } set { if (null != value) { Keywords index = GetIndex(keyword); switch (index) { case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break; case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break; case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break; case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break; case Keywords.DataSource: DataSource = ConvertToString(value); break; case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break; case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break; // case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break; case Keywords.Password: Password = ConvertToString(value); break; case Keywords.UserID: UserID = ConvertToString(value); break; case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break; case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break; case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break; case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break; case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break; case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break; case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break; case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break; case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break; case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break; case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break; case Keywords.Enlist: Enlist = ConvertToBoolean(value); break; case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break; case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break; case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break; case Keywords.Pooling: Pooling = ConvertToBoolean(value); break; case Keywords.Replication: Replication = ConvertToBoolean(value); break; case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break; case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break; case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break; default: Debug.Assert(false, "unexpected keyword"); throw UnsupportedKeyword(keyword); } } else { Remove(keyword); } } } public ApplicationIntent ApplicationIntent { get { return _applicationIntent; } set { if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value)) { throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value); } SetApplicationIntentValue(value); _applicationIntent = value; } } public string ApplicationName { get { return _applicationName; } set { SetValue(DbConnectionStringKeywords.ApplicationName, value); _applicationName = value; } } public string AttachDBFilename { get { return _attachDBFilename; } set { SetValue(DbConnectionStringKeywords.AttachDBFilename, value); _attachDBFilename = value; } } public int ConnectTimeout { get { return _connectTimeout; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout); } SetValue(DbConnectionStringKeywords.ConnectTimeout, value); _connectTimeout = value; } } public string CurrentLanguage { get { return _currentLanguage; } set { SetValue(DbConnectionStringKeywords.CurrentLanguage, value); _currentLanguage = value; } } public string DataSource { get { return _dataSource; } set { SetValue(DbConnectionStringKeywords.DataSource, value); _dataSource = value; } } public bool Encrypt { get { return _encrypt; } set { SetValue(DbConnectionStringKeywords.Encrypt, value); _encrypt = value; } } public bool TrustServerCertificate { get { return _trustServerCertificate; } set { SetValue(DbConnectionStringKeywords.TrustServerCertificate, value); _trustServerCertificate = value; } } public bool Enlist { get { return _enlist; } set { SetValue(DbConnectionStringKeywords.Enlist, value); _enlist = value; } } public string FailoverPartner { get { return _failoverPartner; } set { SetValue(DbConnectionStringKeywords.FailoverPartner, value); _failoverPartner = value; } } [TypeConverter(typeof(SqlInitialCatalogConverter))] public string InitialCatalog { get { return _initialCatalog; } set { SetValue(DbConnectionStringKeywords.InitialCatalog, value); _initialCatalog = value; } } public bool IntegratedSecurity { get { return _integratedSecurity; } set { SetValue(DbConnectionStringKeywords.IntegratedSecurity, value); _integratedSecurity = value; } } public int LoadBalanceTimeout { get { return _loadBalanceTimeout; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout); } SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value); _loadBalanceTimeout = value; } } public int MaxPoolSize { get { return _maxPoolSize; } set { if (value < 1) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize); } SetValue(DbConnectionStringKeywords.MaxPoolSize, value); _maxPoolSize = value; } } public int ConnectRetryCount { get { return _connectRetryCount; } set { if ((value < 0) || (value > 255)) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount); } SetValue(DbConnectionStringKeywords.ConnectRetryCount, value); _connectRetryCount = value; } } public int ConnectRetryInterval { get { return _connectRetryInterval; } set { if ((value < 1) || (value > 60)) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval); } SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value); _connectRetryInterval = value; } } public int MinPoolSize { get { return _minPoolSize; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize); } SetValue(DbConnectionStringKeywords.MinPoolSize, value); _minPoolSize = value; } } public bool MultipleActiveResultSets { get { return _multipleActiveResultSets; } set { SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value); _multipleActiveResultSets = value; } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")] public bool MultiSubnetFailover { get { return _multiSubnetFailover; } set { SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value); _multiSubnetFailover = value; } } /* [DisplayName(DbConnectionStringKeywords.NamedConnection)] [ResCategoryAttribute(Res.DataCategory_NamedConnectionString)] [ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)] [RefreshPropertiesAttribute(RefreshProperties.All)] [TypeConverter(typeof(NamedConnectionStringConverter))] public string NamedConnection { get { return _namedConnection; } set { SetValue(DbConnectionStringKeywords.NamedConnection, value); _namedConnection = value; } } */ public int PacketSize { get { return _packetSize; } set { if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value)) { throw SQL.InvalidPacketSizeValue(); } SetValue(DbConnectionStringKeywords.PacketSize, value); _packetSize = value; } } public string Password { get { return _password; } set { SetValue(DbConnectionStringKeywords.Password, value); _password = value; } } public bool PersistSecurityInfo { get { return _persistSecurityInfo; } set { SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value); _persistSecurityInfo = value; } } public bool Pooling { get { return _pooling; } set { SetValue(DbConnectionStringKeywords.Pooling, value); _pooling = value; } } public bool Replication { get { return _replication; } set { SetValue(DbConnectionStringKeywords.Replication, value); _replication = value; } } public string TransactionBinding { get { return _transactionBinding; } set { SetValue(DbConnectionStringKeywords.TransactionBinding, value); _transactionBinding = value; } } public string TypeSystemVersion { get { return _typeSystemVersion; } set { SetValue(DbConnectionStringKeywords.TypeSystemVersion, value); _typeSystemVersion = value; } } public string UserID { get { return _userID; } set { SetValue(DbConnectionStringKeywords.UserID, value); _userID = value; } } public bool UserInstance { get { return _userInstance; } set { SetValue(DbConnectionStringKeywords.UserInstance, value); _userInstance = value; } } public string WorkstationID { get { return _workstationID; } set { SetValue(DbConnectionStringKeywords.WorkstationID, value); _workstationID = value; } } public override ICollection Keys { get { return new System.Collections.ObjectModel.ReadOnlyCollection<string>(s_validKeywords); } } public override ICollection Values { get { // written this way so if the ordering of Keywords & _validKeywords changes // this is one less place to maintain object[] values = new object[s_validKeywords.Length]; for (int i = 0; i < values.Length; ++i) { values[i] = GetAt((Keywords)i); } return new System.Collections.ObjectModel.ReadOnlyCollection<object>(values); } } public override void Clear() { base.Clear(); for (int i = 0; i < s_validKeywords.Length; ++i) { Reset((Keywords)i); } } public override bool ContainsKey(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); return s_keywords.ContainsKey(keyword); } private static bool ConvertToBoolean(object value) { return DbConnectionStringBuilderUtil.ConvertToBoolean(value); } private static int ConvertToInt32(object value) { return DbConnectionStringBuilderUtil.ConvertToInt32(value); } private static bool ConvertToIntegratedSecurity(object value) { return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value); } private static string ConvertToString(object value) { return DbConnectionStringBuilderUtil.ConvertToString(value); } private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value); } private object GetAt(Keywords index) { switch (index) { case Keywords.ApplicationIntent: return this.ApplicationIntent; case Keywords.ApplicationName: return ApplicationName; case Keywords.AttachDBFilename: return AttachDBFilename; case Keywords.ConnectTimeout: return ConnectTimeout; case Keywords.CurrentLanguage: return CurrentLanguage; case Keywords.DataSource: return DataSource; case Keywords.Encrypt: return Encrypt; case Keywords.Enlist: return Enlist; case Keywords.FailoverPartner: return FailoverPartner; case Keywords.InitialCatalog: return InitialCatalog; case Keywords.IntegratedSecurity: return IntegratedSecurity; case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout; case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets; case Keywords.MaxPoolSize: return MaxPoolSize; case Keywords.MinPoolSize: return MinPoolSize; case Keywords.MultiSubnetFailover: return MultiSubnetFailover; // case Keywords.NamedConnection: return NamedConnection; case Keywords.PacketSize: return PacketSize; case Keywords.Password: return Password; case Keywords.PersistSecurityInfo: return PersistSecurityInfo; case Keywords.Pooling: return Pooling; case Keywords.Replication: return Replication; case Keywords.TransactionBinding: return TransactionBinding; case Keywords.TrustServerCertificate: return TrustServerCertificate; case Keywords.TypeSystemVersion: return TypeSystemVersion; case Keywords.UserID: return UserID; case Keywords.UserInstance: return UserInstance; case Keywords.WorkstationID: return WorkstationID; case Keywords.ConnectRetryCount: return ConnectRetryCount; case Keywords.ConnectRetryInterval: return ConnectRetryInterval; default: Debug.Assert(false, "unexpected keyword"); throw UnsupportedKeyword(s_validKeywords[(int)index]); } } private Keywords GetIndex(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { return index; } throw UnsupportedKeyword(keyword); } public override bool Remove(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { if (base.Remove(s_validKeywords[(int)index])) { Reset(index); return true; } } return false; } private void Reset(Keywords index) { switch (index) { case Keywords.ApplicationIntent: _applicationIntent = DbConnectionStringDefaults.ApplicationIntent; break; case Keywords.ApplicationName: _applicationName = DbConnectionStringDefaults.ApplicationName; break; case Keywords.AttachDBFilename: _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename; break; case Keywords.ConnectTimeout: _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; break; case Keywords.CurrentLanguage: _currentLanguage = DbConnectionStringDefaults.CurrentLanguage; break; case Keywords.DataSource: _dataSource = DbConnectionStringDefaults.DataSource; break; case Keywords.Encrypt: _encrypt = DbConnectionStringDefaults.Encrypt; break; case Keywords.Enlist: _enlist = DbConnectionStringDefaults.Enlist; break; case Keywords.FailoverPartner: _failoverPartner = DbConnectionStringDefaults.FailoverPartner; break; case Keywords.InitialCatalog: _initialCatalog = DbConnectionStringDefaults.InitialCatalog; break; case Keywords.IntegratedSecurity: _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity; break; case Keywords.LoadBalanceTimeout: _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; break; case Keywords.MultipleActiveResultSets: _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets; break; case Keywords.MaxPoolSize: _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; break; case Keywords.MinPoolSize: _minPoolSize = DbConnectionStringDefaults.MinPoolSize; break; case Keywords.MultiSubnetFailover: _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; break; // case Keywords.NamedConnection: // _namedConnection = DbConnectionStringDefaults.NamedConnection; // break; case Keywords.PacketSize: _packetSize = DbConnectionStringDefaults.PacketSize; break; case Keywords.Password: _password = DbConnectionStringDefaults.Password; break; case Keywords.PersistSecurityInfo: _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo; break; case Keywords.Pooling: _pooling = DbConnectionStringDefaults.Pooling; break; case Keywords.ConnectRetryCount: _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount; break; case Keywords.ConnectRetryInterval: _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval; break; case Keywords.Replication: _replication = DbConnectionStringDefaults.Replication; break; case Keywords.TransactionBinding: _transactionBinding = DbConnectionStringDefaults.TransactionBinding; break; case Keywords.TrustServerCertificate: _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate; break; case Keywords.TypeSystemVersion: _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion; break; case Keywords.UserID: _userID = DbConnectionStringDefaults.UserID; break; case Keywords.UserInstance: _userInstance = DbConnectionStringDefaults.UserInstance; break; case Keywords.WorkstationID: _workstationID = DbConnectionStringDefaults.WorkstationID; break; default: Debug.Assert(false, "unexpected keyword"); throw UnsupportedKeyword(s_validKeywords[(int)index]); } } private void SetValue(string keyword, bool value) { base[keyword] = value.ToString(); } private void SetValue(string keyword, int value) { base[keyword] = value.ToString((System.IFormatProvider)null); } private void SetValue(string keyword, string value) { ADP.CheckArgumentNull(value, keyword); base[keyword] = value; } private void SetApplicationIntentValue(ApplicationIntent value) { Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value"); base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value); } public override bool ShouldSerialize(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; return s_keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(s_validKeywords[(int)index]); } public override bool TryGetValue(string keyword, out object value) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { value = GetAt(index); return true; } value = null; return false; } private static readonly string[] s_notSupportedKeywords = new string[] { DbConnectionStringKeywords.AsynchronousProcessing, DbConnectionStringKeywords.ConnectionReset, DbConnectionStringKeywords.ContextConnection, DbConnectionStringKeywords.TransactionBinding, DbConnectionStringSynonyms.Async }; private static readonly string[] s_notSupportedNetworkLibraryKeywords = new string[] { DbConnectionStringKeywords.NetworkLibrary, DbConnectionStringSynonyms.NET, DbConnectionStringSynonyms.NETWORK }; private Exception UnsupportedKeyword(string keyword) { if (s_notSupportedKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase)) { return SQL.UnsupportedKeyword(keyword); } else if (s_notSupportedNetworkLibraryKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase)) { return SQL.NetworkLibraryKeywordNotSupported(); } else { return ADP.KeywordNotSupported(keyword); } } private sealed class SqlInitialCatalogConverter : StringConverter { // converter classes should have public ctor public SqlInitialCatalogConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return GetStandardValuesSupportedInternal(context); } private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context) { // Only say standard values are supported if the connection string has enough // information set to instantiate a connection and retrieve a list of databases bool flag = false; if (null != context) { SqlConnectionStringBuilder constr = (context.Instance as SqlConnectionStringBuilder); if (null != constr) { if ((0 < constr.DataSource.Length) && (constr.IntegratedSecurity || (0 < constr.UserID.Length))) { flag = true; } } } return flag; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { // Although theoretically this could be true, some people may want to just type in a name return false; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { // There can only be standard values if the connection string is in a state that might // be able to instantiate a connection if (GetStandardValuesSupportedInternal(context)) { // Create an array list to store the database names List<string> values = new List<string>(); try { SqlConnectionStringBuilder constr = (SqlConnectionStringBuilder)context.Instance; // Create a connection using (SqlConnection connection = new SqlConnection()) { // Create a basic connection string from current property values connection.ConnectionString = constr.ConnectionString; // Try to open the connection connection.Open(); DataTable databaseTable = connection.GetSchema("DATABASES"); foreach (DataRow row in databaseTable.Rows) { string dbName = (string)row["database_name"]; values.Add(dbName); } } } catch (SqlException e) { ADP.TraceExceptionWithoutRethrow(e); // silently fail } // Return values as a StandardValuesCollection return new StandardValuesCollection(values); } return null; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Option; using QuantConnect.Securities.Positions; using QuantConnect.Util; namespace QuantConnect.Brokerages.Backtesting { /// <summary> /// Represents a brokerage to be used during backtesting. This is intended to be only be used with the BacktestingTransactionHandler /// </summary> public class BacktestingBrokerage : Brokerage { // flag used to indicate whether or not we need to scan for // fills, this is purely a performance concern is ConcurrentDictionary.IsEmpty // is not exactly the fastest operation and Scan gets called at least twice per // time loop private bool _needsScan; private readonly ConcurrentDictionary<int, Order> _pending; private readonly object _needsScanLock = new object(); private readonly HashSet<Symbol> _pendingOptionAssignments = new HashSet<Symbol>(); /// <summary> /// This is the algorithm under test /// </summary> protected readonly IAlgorithm Algorithm; /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm /// </summary> /// <param name="algorithm">The algorithm instance</param> public BacktestingBrokerage(IAlgorithm algorithm) : base("Backtesting Brokerage") { Algorithm = algorithm; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="name">The name of the brokerage</param> protected BacktestingBrokerage(IAlgorithm algorithm, string name) : base(name) { Algorithm = algorithm; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm. Adds market simulation to BacktestingBrokerage; /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="marketSimulation">The backtesting market simulation instance</param> public BacktestingBrokerage(IAlgorithm algorithm, IBacktestingMarketSimulation marketSimulation) : base("Backtesting Brokerage") { Algorithm = algorithm; MarketSimulation = marketSimulation; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Gets the connection status /// </summary> /// <remarks> /// The BacktestingBrokerage is always connected /// </remarks> public override bool IsConnected => true; /// <summary> /// Gets all open orders on the account /// </summary> /// <returns>The open orders returned from IB</returns> public override List<Order> GetOpenOrders() { return Algorithm.Transactions.GetOpenOrders().ToList(); } /// <summary> /// Gets all holdings for the account /// </summary> /// <returns>The current holdings from the account</returns> public override List<Holding> GetAccountHoldings() { // grab everything from the portfolio with a non-zero absolute quantity return (from kvp in Algorithm.Portfolio.Securities.OrderBy(x => x.Value.Symbol) where kvp.Value.Holdings.AbsoluteQuantity > 0 select new Holding(kvp.Value)).ToList(); } /// <summary> /// Gets the current cash balance for each currency held in the brokerage account /// </summary> /// <returns>The current cash balance for each currency available for trading</returns> public override List<CashAmount> GetCashBalance() { return Algorithm.Portfolio.CashBook.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList(); } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.PlaceOrder(): Type: " + order.Type + " Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity); } if (order.Status == OrderStatus.New) { lock (_needsScanLock) { _needsScan = true; SetPendingOrder(order); } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId); // fire off the event that says this order has been submitted var submitted = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Submitted }; OnOrderEvent(submitted); return true; } return false; } /// <summary> /// Updates the order with the same ID /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public override bool UpdateOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.UpdateOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity + " Status: " + order.Status); } lock (_needsScanLock) { Order pending; if (!_pending.TryGetValue(order.Id, out pending)) { // can't update something that isn't there return false; } _needsScan = true; SetPendingOrder(order); } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId); // fire off the event that says this order has been updated var updated = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.UpdateSubmitted }; OnOrderEvent(updated); return true; } /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was made for the order to be canceled, false otherwise</returns> public override bool CancelOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.CancelOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity); } lock (_needsScanLock) { Order pending; if (!_pending.TryRemove(order.Id, out pending)) { // can't cancel something that isn't there return false; } } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(order.Id.ToStringInvariant()); // fire off the event that says this order has been canceled var canceled = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Canceled }; OnOrderEvent(canceled); return true; } /// <summary> /// Market Simulation - simulates various market conditions in backtest /// </summary> public IBacktestingMarketSimulation MarketSimulation { get; set; } /// <summary> /// Scans all the outstanding orders and applies the algorithm model fills to generate the order events /// </summary> public virtual void Scan() { lock (_needsScanLock) { // there's usually nothing in here if (!_needsScan) { return; } var stillNeedsScan = false; // process each pending order to produce fills/fire events foreach (var kvp in _pending.OrderBySafe(x => x.Key)) { var order = kvp.Value; if (order == null) { Log.Error("BacktestingBrokerage.Scan(): Null pending order found: " + kvp.Key); _pending.TryRemove(kvp.Key, out order); continue; } if (order.Status.IsClosed()) { // this should never actually happen as we always remove closed orders as they happen _pending.TryRemove(order.Id, out order); continue; } // all order fills are processed on the next bar (except for market orders) if (order.Time == Algorithm.UtcTime && order.Type != OrderType.Market && order.Type != OrderType.OptionExercise) { stillNeedsScan = true; continue; } var fills = Array.Empty<OrderEvent>(); Security security; if (!Algorithm.Securities.TryGetValue(order.Symbol, out security)) { Log.Error($"BacktestingBrokerage.Scan(): Unable to process order: {order.Id}. The security no longer exists. UtcTime: {Algorithm.UtcTime}"); // invalidate the order in the algorithm before removing OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) {Status = OrderStatus.Invalid}); _pending.TryRemove(order.Id, out order); continue; } if (order.Type == OrderType.MarketOnOpen) { // This is a performance improvement: // Since MOO should never fill on the same bar or on stale data (see FillModel) // the order can remain unfilled for multiple 'scans', so we want to avoid // margin and portfolio calculations since they are expensive var currentBar = security.GetLastData(); var localOrderTime = order.Time.ConvertFromUtc(security.Exchange.TimeZone); if (currentBar == null || localOrderTime >= currentBar.EndTime) { stillNeedsScan = true; continue; } } // check if the time in force handler allows fills if (order.TimeInForce.IsOrderExpired(security, order)) { OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Canceled, Message = "The order has expired." }); _pending.TryRemove(order.Id, out order); continue; } // check if we would actually be able to fill this if (!Algorithm.BrokerageModel.CanExecuteOrder(security, order)) { continue; } // verify sure we have enough cash to perform the fill HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult; try { var group = Algorithm.Portfolio.Positions.CreatePositionGroup(order); hasSufficientBuyingPowerResult = group.BuyingPowerModel.HasSufficientBuyingPowerForOrder( new HasSufficientPositionGroupBuyingPowerForOrderParameters(Algorithm.Portfolio, group, order) ); } catch (Exception err) { // if we threw an error just mark it as invalid and remove the order from our pending list OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero, err.Message) { Status = OrderStatus.Invalid }); Order pending; _pending.TryRemove(order.Id, out pending); Log.Error(err); Algorithm.Error($"Order Error: id: {order.Id}, Error executing margin models: {err.Message}"); continue; } //Before we check this queued order make sure we have buying power: if (hasSufficientBuyingPowerResult.IsSufficient) { //Model: var model = security.FillModel; //Based on the order type: refresh its model to get fill price and quantity try { if (order.Type == OrderType.OptionExercise) { var option = (Option)security; fills = option.OptionExerciseModel.OptionExercise(option, order as OptionExerciseOrder).ToArray(); } else { var context = new FillModelParameters( security, order, Algorithm.SubscriptionManager.SubscriptionDataConfigService, Algorithm.Settings.StalePriceTimeSpan); fills = new[] { model.Fill(context).OrderEvent }; } // invoke fee models for completely filled order events foreach (var fill in fills) { if (fill.Status == OrderStatus.Filled) { // this check is provided for backwards compatibility of older user-defined fill models // that may be performing fee computation inside the fill model w/out invoking the fee model // TODO : This check can be removed in April, 2019 -- a 6-month window to upgrade (also, suspect small % of users, if any are impacted) if (fill.OrderFee.Value.Amount == 0m) { fill.OrderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); } } } } catch (Exception err) { Log.Error(err); Algorithm.Error($"Order Error: id: {order.Id}, Transaction model failed to fill for order type: {order.Type} with error: {err.Message}"); } } else if (order.Status == OrderStatus.CancelPending) { // the pending CancelOrderRequest will be handled during the next transaction handler run continue; } else { // invalidate the order in the algorithm before removing var message = $"Insufficient buying power to complete order (Value:{order.GetValue(security).SmartRounding()}), Reason: {hasSufficientBuyingPowerResult.Reason}."; OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero, message) { Status = OrderStatus.Invalid }); Order pending; _pending.TryRemove(order.Id, out pending); Algorithm.Error($"Order Error: id: {order.Id}, {message}"); continue; } foreach (var fill in fills) { // check if the fill should be emitted if (!order.TimeInForce.IsFillValid(security, order, fill)) { break; } // change in status or a new fill if (order.Status != fill.Status || fill.FillQuantity != 0) { // we update the order status so we do not re process it if we re enter // because of the call to OnOrderEvent. // Note: this is done by the transaction handler but we have a clone of the order order.Status = fill.Status; //If the fill models come back suggesting filled, process the affects on portfolio OnOrderEvent(fill); } if (fill.IsAssignment) { fill.Message = order.Tag; OnOptionPositionAssigned(fill); } } if (fills.All(x => x.Status.IsClosed())) { _pending.TryRemove(order.Id, out order); } else { stillNeedsScan = true; } } // if we didn't fill then we need to continue to scan or // if there are still pending orders _needsScan = stillNeedsScan || !_pending.IsEmpty; } } /// <summary> /// Runs market simulation /// </summary> public void SimulateMarket() { // if simulator is installed, we run it MarketSimulation?.SimulateMarketConditions(this, Algorithm); } /// <summary> /// This method is called by market simulator in order to launch an assignment event /// </summary> /// <param name="option">Option security to assign</param> /// <param name="quantity">Quantity to assign</param> public virtual void ActivateOptionAssignment(Option option, int quantity) { // do not process the same assignment more than once if (_pendingOptionAssignments.Contains(option.Symbol)) return; _pendingOptionAssignments.Add(option.Symbol); // assignments always cause a positive change to option contract holdings var request = new SubmitOrderRequest(OrderType.OptionExercise, option.Type, option.Symbol, Math.Abs(quantity), 0m, 0m, 0m, Algorithm.UtcTime, "Simulated option assignment before expiration"); var ticket = Algorithm.Transactions.ProcessRequest(request); Log.Trace($"BacktestingBrokerage.ActivateOptionAssignment(): OrderId: {ticket.OrderId}"); } /// <summary> /// Event invocator for the OrderFilled event /// </summary> /// <param name="e">The OrderEvent</param> protected override void OnOrderEvent(OrderEvent e) { if (e.Status.IsClosed() && _pendingOptionAssignments.Contains(e.Symbol)) { _pendingOptionAssignments.Remove(e.Symbol); } base.OnOrderEvent(e); } /// <summary> /// The BacktestingBrokerage is always connected. This is a no-op. /// </summary> public override void Connect() { //NOP } /// <summary> /// The BacktestingBrokerage is always connected. This is a no-op. /// </summary> public override void Disconnect() { //NOP } /// <summary> /// Sets the pending order as a clone to prevent object reference nastiness /// </summary> /// <param name="order">The order to be added to the pending orders dictionary</param> /// <returns></returns> private void SetPendingOrder(Order order) { _pending[order.Id] = order; } /// <summary> /// Process delistings /// </summary> /// <param name="delistings">Delistings to process</param> public void ProcessDelistings(Delistings delistings) { // Process our delistings, important to do options first because of possibility of having future options contracts // and underlying future delisting at the same time. foreach (var delisting in delistings?.Values.OrderBy(x => !x.Symbol.SecurityType.IsOption())) { Log.Trace($"BacktestingBrokerage.ProcessDelistings(): Delisting {delisting.Type}: {delisting.Symbol.Value}, UtcTime: {Algorithm.UtcTime}, DelistingTime: {delisting.Time}"); if (delisting.Type == DelistingType.Warning) { // We do nothing with warnings continue; } var security = Algorithm.Securities[delisting.Symbol]; if (security.Symbol.SecurityType.IsOption()) { // Process the option delisting OnOptionNotification(new OptionNotificationEventArgs(delisting.Symbol, 0)); } else { // Any other type of delisting OnDelistingNotification(new DelistingNotificationEventArgs(delisting.Symbol)); } // don't allow users to open a new position once we sent the liquidation order security.IsTradable = false; security.IsDelisted = true; // the subscription are getting removed from the data feed because they end // remove security from all universes foreach (var ukvp in Algorithm.UniverseManager) { var universe = ukvp.Value; if (universe.ContainsMember(security.Symbol)) { var userUniverse = universe as UserDefinedUniverse; if (userUniverse != null) { userUniverse.Remove(security.Symbol); } else { universe.RemoveMember(Algorithm.UtcTime, security); } } } // Cancel any other orders var cancelledOrders = Algorithm.Transactions.CancelOpenOrders(delisting.Symbol); foreach (var cancelledOrder in cancelledOrders) { Log.Trace("AlgorithmManager.Run(): " + cancelledOrder); } } } } }
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 TodoListService.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.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, 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; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// Usda /// </summary> public sealed partial class Usda : DirtyExtensibleObject, IIdentifiable { private DirtyValue<decimal?>? _additionalMemberBaseIncome; private DirtyValue<string?>? _adjustedIncomeCalculationDescription1; private DirtyValue<string?>? _adjustedIncomeCalculationDescription2; private DirtyValue<string?>? _adjustedIncomeCalculationDescription3; private DirtyValue<decimal?>? _advanceAmountToDate; private DirtyValue<decimal?>? _amountLoanlineCredit; private DirtyValue<decimal?>? _annualChildCareExpenses; private DirtyValue<string?>? _annualIncomeCalculationDescription1; private DirtyValue<string?>? _annualIncomeCalculationDescription2; private DirtyValue<string?>? _annualIncomeCalculationDescription3; private DirtyValue<string?>? _annualIncomeCalculationDescription4; private DirtyValue<string?>? _annualIncomeCalculationDescription5; private DirtyValue<DateTime?>? _annualReviewDate; private DirtyValue<string?>? _applicationNumber; private DirtyValue<string?>? _approvedLenderTaxId; private DirtyValue<decimal?>? _balanceOwedOnLoan; private DirtyValue<decimal?>? _borrowerTotalStableIncome; private DirtyValue<StringEnumValue<BorrowerTypeCode>>? _borrowerTypeCode; private DirtyValue<decimal?>? _buydownInterestAssistanceRate; private DirtyValue<string?>? _caseNumberBorrowerId; private DirtyValue<string?>? _caseNumberCo; private DirtyValue<string?>? _caseNumberSt; private DirtyValue<DateTime?>? _certificationEffectiveDate; private DirtyValue<DateTime?>? _certificationExpirationDate; private DirtyValue<bool?>? _certifiedLoanIndicator; private DirtyValue<string?>? _childCareProviderAddress; private DirtyValue<string?>? _childCareProviderCity; private DirtyValue<string?>? _childCareProviderPhone; private DirtyValue<string?>? _childCareProviderProviderName; private DirtyValue<StringEnumValue<State>>? _childCareProviderState; private DirtyValue<string?>? _childCareProviderZip; private DirtyValue<decimal?>? _childCostPerMonth; private DirtyValue<decimal?>? _childCostPerWeek; private DirtyValue<decimal?>? _coborrowerStableBaseIncome; private DirtyValue<string?>? _coborrowerStableBaseIncomeDesc; private DirtyValue<decimal?>? _coborrowerStableOtherIncome; private DirtyValue<string?>? _coborrowerStableOtherIncomeDesc; private DirtyValue<decimal?>? _coBorrowerTotalStableIncome; private DirtyValue<DateTime?>? _dateConfirmedObligationProcessed; private DirtyValue<DateTime?>? _dateLoanNoteGuaranteeIssued; private DirtyValue<DateTime?>? _dateLoanNoteGuaranteeRequestReceived; private DirtyValue<DateTime?>? _dateObligationInGls; private DirtyValue<DateTime?>? _dateVerifiedInUnifi; private DirtyValue<decimal?>? _dependentDeduction; private DirtyValue<decimal?>? _disabilityDeduction; private DirtyValue<decimal?>? _elderlyHouseholdDeduction; private DirtyValue<decimal?>? _feeRate; private DirtyValue<string?>? _financedLoanClosingCostDescription; private DirtyValue<decimal?>? _financedLoanClosingCosts; private DirtyValue<decimal?>? _guaranteeFeeCollected; private DirtyValue<decimal?>? _guaranteeFeeOnCommitment; private DirtyValue<StringEnumValue<GuaranteeFeePurposeCodeType>>? _guaranteeFeePurposeCodeType; private DirtyValue<DateTime?>? _guaranteePeriodBeginsDate; private DirtyValue<DateTime?>? _guaranteePeriodEndsDate; private DirtyValue<StringEnumValue<GuaranteeType>>? _guaranteeType; private DirtyValue<int?>? _householdSize; private DirtyValue<string?>? _id; private DirtyValue<StringEnumValue<InterestAssistanceCodeType>>? _interestAssistanceCodeType; private DirtyValue<bool?>? _interestRateBasedonFannieIndicator; private DirtyValue<StringEnumValue<InterestRateCodeType>>? _interestRateCodeType; private DirtyValue<bool?>? _interestRateFloatToLoanClosingIndicator; private DirtyValue<bool?>? _lackAdequateHeatIndicator; private DirtyValue<string?>? _lenderAuthorizedRepCompany; private DirtyValue<string?>? _lenderAuthorizedRepName; private DirtyValue<string?>? _lenderAuthorizedRepTitle; private DirtyValue<string?>? _lenderIdNo; private DirtyValue<decimal?>? _lenderNoteRateOnGuaranteedPortion; private DirtyValue<decimal?>? _lenderNoteRateOnNonGuaranteedPortion; private DirtyValue<StringEnumValue<LenderStatusCodeType>>? _lenderStatusCodeType; private DirtyValue<StringEnumValue<LenderTypeCode>>? _lenderTypeCode; private DirtyValue<StringEnumValue<UsdaLoanType>>? _loanType; private DirtyValue<bool?>? _lockCompletePlumbingIndicator; private DirtyValue<decimal?>? _medicalExpenses; private DirtyValue<decimal?>? _moderateIncomeLimit; private DirtyValue<decimal?>? _monthlyRepaymentIncome; private DirtyValue<int?>? _numberofDependents; private DirtyValue<int?>? _numberofPeopleInHousehold; private DirtyValue<bool?>? _obligationMatchesCommitmentLenderRequestIndicator; private DirtyValue<string?>? _officialWhoConfirmedGlsUpdated; private DirtyValue<bool?>? _oneTimeClose; private DirtyValue<decimal?>? _otherIncome; private DirtyValue<decimal?>? _otherStableDependableMonthlyIncome; private DirtyValue<bool?>? _overcrowdedIndicator; private DirtyValue<decimal?>? _percentofLoanGuaranteed; private DirtyValue<StringEnumValue<PeriodOperatingLineCreditYearsType>>? _periodOperatingLineCreditYearsType; private DirtyValue<bool?>? _physicallyDeterioratedIndicator; private DirtyValue<string?>? _preparedByName; private DirtyValue<string?>? _preparedByTitle; private DirtyValue<string?>? _presentLandloardAddress; private DirtyValue<string?>? _presentLandloardCity; private DirtyValue<string?>? _presentLandloardName; private DirtyValue<string?>? _presentLandloardPhone; private DirtyValue<StringEnumValue<State>>? _presentLandloardState; private DirtyValue<string?>? _presentLandloardZip; private DirtyValue<string?>? _previousLandloardAddress; private DirtyValue<string?>? _previousLandloardCity; private DirtyValue<string?>? _previousLandloardName; private DirtyValue<string?>? _previousLandloardPhone; private DirtyValue<StringEnumValue<State>>? _previousLandloardState; private DirtyValue<string?>? _previousLandloardZip; private DirtyValue<decimal?>? _purchaseOrRefinancedAmount; private DirtyValue<string?>? _purchaseOrRefinanceDescription; private DirtyValue<StringEnumValue<RdsfhRefinancedLoanIndicatorType>>? _rdsfhRefinancedLoanIndicatorType; private DirtyValue<bool?>? _refinanceLoanIndicator; private DirtyValue<StringEnumValue<UsdaRefinanceType>>? _refinanceType; private DirtyValue<decimal?>? _repairOtherAmount; private DirtyValue<string?>? _repairOtherDescription; private DirtyValue<decimal?>? _reservationAmountRequested; private DirtyValue<string?>? _reserved; private DirtyValue<string?>? _servicingOfficeName; private DirtyValue<bool?>? _sfhglpIndicator; private DirtyValue<StringEnumValue<SourceOfFundsType>>? _sourceOfFundsType; private DirtyValue<decimal?>? _stableDependableMonthlyIncome; private DirtyValue<string?>? _stableOtherIncomeDesc; private DirtyValue<string?>? _submittingLenderAddress; private DirtyValue<string?>? _submittingLenderCity; private DirtyValue<string?>? _submittingLenderContactFax; private DirtyValue<string?>? _submittingLenderContactName; private DirtyValue<string?>? _submittingLenderContactPhone; private DirtyValue<string?>? _submittingLenderName; private DirtyValue<StringEnumValue<State>>? _submittingLenderState; private DirtyValue<string?>? _submittingLenderTaxId; private DirtyValue<string?>? _submittingLenderZip; private DirtyValue<int?>? _termOfBuydown; private DirtyValue<string?>? _thirdPartyOriginator; private DirtyValue<string?>? _title; private DirtyValue<decimal?>? _totalBorrowerStableBaseIncome; private DirtyValue<decimal?>? _totalBorrowerStableOtherIncome; private DirtyValue<decimal?>? _totalHouseholdDeduction; private DirtyValue<decimal?>? _totalRequestAmount; private DirtyValue<string?>? _tpoTaxId; private DirtyValue<string?>? _underwritingDecisionBy; private DirtyValue<DateTime?>? _underwritingDecisionDate; private DirtyValue<StringEnumValue<UnderwritingDecisionType>>? _underwritingDecisionType; private DirtyList<UsdaHouseholdIncome>? _usdaHouseholdIncomes; private DirtyValue<string?>? _verificationCode; /// <summary> /// USDA - Additional Adult Household Member(s) (Base Income: Primary Employment from Wages, Salary, self-Employed, Additional income to Primary Employment, Other Income) [USDA.X167] /// </summary> public decimal? AdditionalMemberBaseIncome { get => _additionalMemberBaseIncome; set => SetField(ref _additionalMemberBaseIncome, value); } /// <summary> /// USDA - Adjusted Income Calculation - Calculate and Record how the calculation of deduction in the space below line 8 [USDA.X214] /// </summary> public string? AdjustedIncomeCalculationDescription1 { get => _adjustedIncomeCalculationDescription1; set => SetField(ref _adjustedIncomeCalculationDescription1, value); } /// <summary> /// USDA - Adjusted Income Calculation - Calculate and Record how the calculation of deduction in the space below line 10 [USDA.X215] /// </summary> public string? AdjustedIncomeCalculationDescription2 { get => _adjustedIncomeCalculationDescription2; set => SetField(ref _adjustedIncomeCalculationDescription2, value); } /// <summary> /// USDA - Adjusted Income Calculation - Calculate and Record how the calculation of deduction in the space below line 11 [USDA.X216] /// </summary> public string? AdjustedIncomeCalculationDescription3 { get => _adjustedIncomeCalculationDescription3; set => SetField(ref _adjustedIncomeCalculationDescription3, value); } /// <summary> /// USDA - Loan Closing - Advance Amount to Date [USDA.X134] /// </summary> public decimal? AdvanceAmountToDate { get => _advanceAmountToDate; set => SetField(ref _advanceAmountToDate, value); } /// <summary> /// USDA - Loan Closing - Amount of Loanline of Credit [USDA.X133] /// </summary> public decimal? AmountLoanlineCredit { get => _amountLoanlineCredit; set => SetField(ref _amountLoanlineCredit, value); } /// <summary> /// USDA - Annual Adjusted Income - Annual Child Care Expenses [USDA.X173] /// </summary> public decimal? AnnualChildCareExpenses { get => _annualChildCareExpenses; set => SetField(ref _annualChildCareExpenses, value); } /// <summary> /// USDA - Annual Income Calculation - Calculate and Record how the calculation of each income source/type was determined in the space below line 1 [USDA.X209] /// </summary> public string? AnnualIncomeCalculationDescription1 { get => _annualIncomeCalculationDescription1; set => SetField(ref _annualIncomeCalculationDescription1, value); } /// <summary> /// USDA - Annual Income Calculation - Calculate and Record how the calculation of each income source/type was determined in the space below line 2 [USDA.X210] /// </summary> public string? AnnualIncomeCalculationDescription2 { get => _annualIncomeCalculationDescription2; set => SetField(ref _annualIncomeCalculationDescription2, value); } /// <summary> /// USDA - Annual Income Calculation - Calculate and Record how the calculation of each income source/type was determined in the space below line 3 [USDA.X211] /// </summary> public string? AnnualIncomeCalculationDescription3 { get => _annualIncomeCalculationDescription3; set => SetField(ref _annualIncomeCalculationDescription3, value); } /// <summary> /// USDA - Annual Income Calculation - Calculate and Record how the calculation of each income source/type was determined in the space below line 4 [USDA.X212] /// </summary> public string? AnnualIncomeCalculationDescription4 { get => _annualIncomeCalculationDescription4; set => SetField(ref _annualIncomeCalculationDescription4, value); } /// <summary> /// USDA - Annual Income Calculation - Calculate and Record how the calculation of each income source/type was determined in the space below line 5 [USDA.X213] /// </summary> public string? AnnualIncomeCalculationDescription5 { get => _annualIncomeCalculationDescription5; set => SetField(ref _annualIncomeCalculationDescription5, value); } /// <summary> /// USDA - Loan Closing - Annual Review Date [USDA.X147] /// </summary> public DateTime? AnnualReviewDate { get => _annualReviewDate; set => SetField(ref _annualReviewDate, value); } /// <summary> /// USDA - Application Number [USDA.X29] /// </summary> public string? ApplicationNumber { get => _applicationNumber; set => SetField(ref _applicationNumber, value); } /// <summary> /// USDA - Approved Lender Tax ID No [USDA.X25] /// </summary> public string? ApprovedLenderTaxId { get => _approvedLenderTaxId; set => SetField(ref _approvedLenderTaxId, value); } /// <summary> /// USDA - Loan Closing - Balance Owed On Loan [USDA.X144] /// </summary> public decimal? BalanceOwedOnLoan { get => _balanceOwedOnLoan; set => SetField(ref _balanceOwedOnLoan, value); } /// <summary> /// USDA - Annual Adjusted Income - Borrower Total Stable Income [USDA.X201] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? BorrowerTotalStableIncome { get => _borrowerTotalStableIncome; set => SetField(ref _borrowerTotalStableIncome, value); } /// <summary> /// USDA - Loan Closing - Borrower Type Code [USDA.X123] /// </summary> public StringEnumValue<BorrowerTypeCode> BorrowerTypeCode { get => _borrowerTypeCode; set => SetField(ref _borrowerTypeCode, value); } /// <summary> /// USDA - Loan Closing - Buydown / Interest Assistance Rate [USDA.X139] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? BuydownInterestAssistanceRate { get => _buydownInterestAssistanceRate; set => SetField(ref _buydownInterestAssistanceRate, value); } /// <summary> /// USDA - Case Number - Borrower ID [USDA.X122] /// </summary> public string? CaseNumberBorrowerId { get => _caseNumberBorrowerId; set => SetField(ref _caseNumberBorrowerId, value); } /// <summary> /// USDA - Case Number - CO [USDA.X121] /// </summary> public string? CaseNumberCo { get => _caseNumberCo; set => SetField(ref _caseNumberCo, value); } /// <summary> /// USDA - Case Number - ST [USDA.X120] /// </summary> public string? CaseNumberSt { get => _caseNumberSt; set => SetField(ref _caseNumberSt, value); } /// <summary> /// USDA - Loan Closing - Certification Effective Date [USDA.X126] /// </summary> public DateTime? CertificationEffectiveDate { get => _certificationEffectiveDate; set => SetField(ref _certificationEffectiveDate, value); } /// <summary> /// USDA - Loan Closing - Certification Expiration Date [USDA.X127] /// </summary> public DateTime? CertificationExpirationDate { get => _certificationExpirationDate; set => SetField(ref _certificationExpirationDate, value); } /// <summary> /// USDA - Loan Closing - Certified Loan [USDA.X148] /// </summary> public bool? CertifiedLoanIndicator { get => _certifiedLoanIndicator; set => SetField(ref _certifiedLoanIndicator, value); } /// <summary> /// USDA - Child Care Provider - Address [USDA.X99] /// </summary> public string? ChildCareProviderAddress { get => _childCareProviderAddress; set => SetField(ref _childCareProviderAddress, value); } /// <summary> /// USDA - Child Care Provider - City [USDA.X100] /// </summary> public string? ChildCareProviderCity { get => _childCareProviderCity; set => SetField(ref _childCareProviderCity, value); } /// <summary> /// USDA - Child Care Provider - Phone Number [USDA.X103] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? ChildCareProviderPhone { get => _childCareProviderPhone; set => SetField(ref _childCareProviderPhone, value); } /// <summary> /// USDA - Child Care Provider - Name [USDA.X98] /// </summary> public string? ChildCareProviderProviderName { get => _childCareProviderProviderName; set => SetField(ref _childCareProviderProviderName, value); } /// <summary> /// USDA - Child Care Provider - State [USDA.X101] /// </summary> public StringEnumValue<State> ChildCareProviderState { get => _childCareProviderState; set => SetField(ref _childCareProviderState, value); } /// <summary> /// USDA - Child Care Provider - Zip [USDA.X102] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? ChildCareProviderZip { get => _childCareProviderZip; set => SetField(ref _childCareProviderZip, value); } /// <summary> /// USDA - Child Care Cost Per Month [USDA.X97] /// </summary> public decimal? ChildCostPerMonth { get => _childCostPerMonth; set => SetField(ref _childCostPerMonth, value); } /// <summary> /// USDA - Child Care Cost Per Week [USDA.X96] /// </summary> public decimal? ChildCostPerWeek { get => _childCostPerWeek; set => SetField(ref _childCostPerWeek, value); } /// <summary> /// USDA - Annual Adjusted Income - Co-Borrower Stable Dependable Monthly Income (parties to note only) [USDA.X202] /// </summary> public decimal? CoborrowerStableBaseIncome { get => _coborrowerStableBaseIncome; set => SetField(ref _coborrowerStableBaseIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Coborrower Calculation of Base Income Description [USDA.X203] /// </summary> public string? CoborrowerStableBaseIncomeDesc { get => _coborrowerStableBaseIncomeDesc; set => SetField(ref _coborrowerStableBaseIncomeDesc, value); } /// <summary> /// USDA - Annual Adjusted Income - Co-Borrower Other Stable Dependable Monthly Income (parties to note only) [USDA.X204] /// </summary> public decimal? CoborrowerStableOtherIncome { get => _coborrowerStableOtherIncome; set => SetField(ref _coborrowerStableOtherIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Coborrower Calculation of Other Income Description [USDA.X205] /// </summary> public string? CoborrowerStableOtherIncomeDesc { get => _coborrowerStableOtherIncomeDesc; set => SetField(ref _coborrowerStableOtherIncomeDesc, value); } /// <summary> /// USDA - Annual Adjusted Income - CoBorrower Total Stable Income [USDA.X206] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? CoBorrowerTotalStableIncome { get => _coBorrowerTotalStableIncome; set => SetField(ref _coBorrowerTotalStableIncome, value); } /// <summary> /// USDA - Tracking - Date Confirmed Obligation Processed [USDA.X154] /// </summary> public DateTime? DateConfirmedObligationProcessed { get => _dateConfirmedObligationProcessed; set => SetField(ref _dateConfirmedObligationProcessed, value); } /// <summary> /// USDA - Tracking - Date Loan Note Guarantee Issued [USDA.X159] /// </summary> public DateTime? DateLoanNoteGuaranteeIssued { get => _dateLoanNoteGuaranteeIssued; set => SetField(ref _dateLoanNoteGuaranteeIssued, value); } /// <summary> /// USDA - Tracking - DateLoan Note Guarantee Request Received [USDA.X157] /// </summary> public DateTime? DateLoanNoteGuaranteeRequestReceived { get => _dateLoanNoteGuaranteeRequestReceived; set => SetField(ref _dateLoanNoteGuaranteeRequestReceived, value); } /// <summary> /// USDA - Tracking - Date of Obligation in GLS [USDA.X153] /// </summary> public DateTime? DateObligationInGls { get => _dateObligationInGls; set => SetField(ref _dateObligationInGls, value); } /// <summary> /// USDA - Tracking - Date Verified in Unifi [USDA.X162] /// </summary> public DateTime? DateVerifiedInUnifi { get => _dateVerifiedInUnifi; set => SetField(ref _dateVerifiedInUnifi, value); } /// <summary> /// USDA - Annual Adjusted Income - Dependent Deduction [USDA.X172] /// </summary> public decimal? DependentDeduction { get => _dependentDeduction; set => SetField(ref _dependentDeduction, value); } /// <summary> /// USDA - Annual Adjusted Income - Disability Deduction [USDA.X175] /// </summary> public decimal? DisabilityDeduction { get => _disabilityDeduction; set => SetField(ref _disabilityDeduction, value); } /// <summary> /// USDA - Annual Adjusted Income - Elderly Household Deduction [USDA.X174] /// </summary> public decimal? ElderlyHouseholdDeduction { get => _elderlyHouseholdDeduction; set => SetField(ref _elderlyHouseholdDeduction, value); } /// <summary> /// USDA - Loan Closing - Fee Rate [USDA.X131] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? FeeRate { get => _feeRate; set => SetField(ref _feeRate, value); } /// <summary> /// USDA - Financed Loan Closing Cost Description [USDA.X21] /// </summary> public string? FinancedLoanClosingCostDescription { get => _financedLoanClosingCostDescription; set => SetField(ref _financedLoanClosingCostDescription, value); } /// <summary> /// USDA - Financed Loan Closing Costs [USDA.X217] /// </summary> public decimal? FinancedLoanClosingCosts { get => _financedLoanClosingCosts; set => SetField(ref _financedLoanClosingCosts, value); } /// <summary> /// USDA - Tracking - Guarantee Fee Collected [USDA.X160] /// </summary> public decimal? GuaranteeFeeCollected { get => _guaranteeFeeCollected; set => SetField(ref _guaranteeFeeCollected, value); } /// <summary> /// USDA - Tracking - Guarantee Fee On Commitment [USDA.X161] /// </summary> public decimal? GuaranteeFeeOnCommitment { get => _guaranteeFeeOnCommitment; set => SetField(ref _guaranteeFeeOnCommitment, value); } /// <summary> /// USDA - Loan Closing - Guarantee Fee Purpose Code [USDA.X130] /// </summary> public StringEnumValue<GuaranteeFeePurposeCodeType> GuaranteeFeePurposeCodeType { get => _guaranteeFeePurposeCodeType; set => SetField(ref _guaranteeFeePurposeCodeType, value); } /// <summary> /// USDA - Loan Closing - Date Guarantee Period Begins [USDA.X145] /// </summary> public DateTime? GuaranteePeriodBeginsDate { get => _guaranteePeriodBeginsDate; set => SetField(ref _guaranteePeriodBeginsDate, value); } /// <summary> /// USDA - Loan Closing - Date Guarantee Period Ends [USDA.X146] /// </summary> public DateTime? GuaranteePeriodEndsDate { get => _guaranteePeriodEndsDate; set => SetField(ref _guaranteePeriodEndsDate, value); } /// <summary> /// USDA - Loan Closing - Type of Guarantee [USDA.X142] /// </summary> public StringEnumValue<GuaranteeType> GuaranteeType { get => _guaranteeType; set => SetField(ref _guaranteeType, value); } /// <summary> /// USDA - Annual Adjusted Income - Household Size [USDA.X179] /// </summary> public int? HouseholdSize { get => _householdSize; set => SetField(ref _householdSize, value); } /// <summary> /// Usda Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// USDA - Loan Closing - Interest Assistance Code [USDA.X129] /// </summary> public StringEnumValue<InterestAssistanceCodeType> InterestAssistanceCodeType { get => _interestAssistanceCodeType; set => SetField(ref _interestAssistanceCodeType, value); } /// <summary> /// USDA - Is Interest Rate Based on Fannie Mae [USDA.X18] /// </summary> public bool? InterestRateBasedonFannieIndicator { get => _interestRateBasedonFannieIndicator; set => SetField(ref _interestRateBasedonFannieIndicator, value); } /// <summary> /// USDA - Loan Closing - Interest Rate Code [USDA.X143] /// </summary> public StringEnumValue<InterestRateCodeType> InterestRateCodeType { get => _interestRateCodeType; set => SetField(ref _interestRateCodeType, value); } /// <summary> /// USDA - Is Interest Rate Based on Fannie Mae - Interest Rate will Float Until Loan Closing [USDA.X19] /// </summary> public bool? InterestRateFloatToLoanClosingIndicator { get => _interestRateFloatToLoanClosingIndicator; set => SetField(ref _interestRateFloatToLoanClosingIndicator, value); } /// <summary> /// USDA - Characteristics Present Housing - Lack Adequate Heat Indicator [USDA.X105] /// </summary> public bool? LackAdequateHeatIndicator { get => _lackAdequateHeatIndicator; set => SetField(ref _lackAdequateHeatIndicator, value); } /// <summary> /// USDA - Lender's Authorized Representative Company Name [USDA.X32] /// </summary> public string? LenderAuthorizedRepCompany { get => _lenderAuthorizedRepCompany; set => SetField(ref _lenderAuthorizedRepCompany, value); } /// <summary> /// USDA - Lender's Authorized Representative Name [USDA.X31] /// </summary> public string? LenderAuthorizedRepName { get => _lenderAuthorizedRepName; set => SetField(ref _lenderAuthorizedRepName, value); } /// <summary> /// USDA - Lender's Authorized Representative Title [USDA.X30] /// </summary> public string? LenderAuthorizedRepTitle { get => _lenderAuthorizedRepTitle; set => SetField(ref _lenderAuthorizedRepTitle, value); } /// <summary> /// USDA - Loan Closing - Lender ID No [USDA.X186] /// </summary> public string? LenderIdNo { get => _lenderIdNo; set => SetField(ref _lenderIdNo, value); } /// <summary> /// USDA - Loan Closing - Lender's Note Interest Rate On Guaranteed Portion [USDA.X137] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? LenderNoteRateOnGuaranteedPortion { get => _lenderNoteRateOnGuaranteedPortion; set => SetField(ref _lenderNoteRateOnGuaranteedPortion, value); } /// <summary> /// USDA - Loan Closing - Lender's Note Interest Rate On Non-Guaranteed Portion [USDA.X138] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? LenderNoteRateOnNonGuaranteedPortion { get => _lenderNoteRateOnNonGuaranteedPortion; set => SetField(ref _lenderNoteRateOnNonGuaranteedPortion, value); } /// <summary> /// USDA - Loan Closing - Lender Status Code [USDA.X124] /// </summary> public StringEnumValue<LenderStatusCodeType> LenderStatusCodeType { get => _lenderStatusCodeType; set => SetField(ref _lenderStatusCodeType, value); } /// <summary> /// USDA - Loan Closing - Lender Type Code [USDA.X125] /// </summary> public StringEnumValue<LenderTypeCode> LenderTypeCode { get => _lenderTypeCode; set => SetField(ref _lenderTypeCode, value); } /// <summary> /// USDA - Loan Type [USDA.X43] /// </summary> public StringEnumValue<UsdaLoanType> LoanType { get => _loanType; set => SetField(ref _loanType, value); } /// <summary> /// USDA - Characteristics Present Housing - Lock Complete Plumbing Indicator [USDA.X104] /// </summary> public bool? LockCompletePlumbingIndicator { get => _lockCompletePlumbingIndicator; set => SetField(ref _lockCompletePlumbingIndicator, value); } /// <summary> /// USDA - Annual Adjusted Income - Medical Expenses [USDA.X176] /// </summary> public decimal? MedicalExpenses { get => _medicalExpenses; set => SetField(ref _medicalExpenses, value); } /// <summary> /// USDA - Annual Adjusted Income - Moderate Income Limit [USDA.X180] /// </summary> public decimal? ModerateIncomeLimit { get => _moderateIncomeLimit; set => SetField(ref _moderateIncomeLimit, value); } /// <summary> /// USDA - Annual Adjusted Income - Monthly Repayment Income [USDA.X184] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? MonthlyRepaymentIncome { get => _monthlyRepaymentIncome; set => SetField(ref _monthlyRepaymentIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Number of Dependent for Deduction (child under age 18, or full-time student) [USDA.X185] /// </summary> public int? NumberofDependents { get => _numberofDependents; set => SetField(ref _numberofDependents, value); } /// <summary> /// USDA - Number of people in household [USDA.X9] /// </summary> public int? NumberofPeopleInHousehold { get => _numberofPeopleInHousehold; set => SetField(ref _numberofPeopleInHousehold, value); } /// <summary> /// USDA - Tracking - Obligation Matches Commitment and Lender Request [USDA.X156] /// </summary> public bool? ObligationMatchesCommitmentLenderRequestIndicator { get => _obligationMatchesCommitmentLenderRequestIndicator; set => SetField(ref _obligationMatchesCommitmentLenderRequestIndicator, value); } /// <summary> /// USDA - Tracking - Official Who Confirmed GLS Updated [USDA.X155] /// </summary> public string? OfficialWhoConfirmedGlsUpdated { get => _officialWhoConfirmedGlsUpdated; set => SetField(ref _officialWhoConfirmedGlsUpdated, value); } /// <summary> /// USDA One Time Close [USDA.X219] /// </summary> public bool? OneTimeClose { get => _oneTimeClose; set => SetField(ref _oneTimeClose, value); } /// <summary> /// USDA - Other Income (Alimony, Child Support, y, Pension/Retirement, Social Security, Disability, Trust Income, Notes Receivable, etc.) [USDA.X169] /// </summary> public decimal? OtherIncome { get => _otherIncome; set => SetField(ref _otherIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Other Stable Dependable Monthly Income (parties to note only) [USDA.X183] /// </summary> public decimal? OtherStableDependableMonthlyIncome { get => _otherStableDependableMonthlyIncome; set => SetField(ref _otherStableDependableMonthlyIncome, value); } /// <summary> /// USDA - Characteristics Present Housing - Overcrowded Indicator [USDA.X107] /// </summary> public bool? OvercrowdedIndicator { get => _overcrowdedIndicator; set => SetField(ref _overcrowdedIndicator, value); } /// <summary> /// USDA - Loan Closing - Percent of Loan Guaranteed [USDA.X199] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? PercentofLoanGuaranteed { get => _percentofLoanGuaranteed; set => SetField(ref _percentofLoanGuaranteed, value); } /// <summary> /// USDA - Loan Closing - Period of Operating Line of Credit Years [USDA.X140] /// </summary> public StringEnumValue<PeriodOperatingLineCreditYearsType> PeriodOperatingLineCreditYearsType { get => _periodOperatingLineCreditYearsType; set => SetField(ref _periodOperatingLineCreditYearsType, value); } /// <summary> /// USDA - Characteristics Present Housing - Physically Deteriorated or Structurally Unsound Indicator [USDA.X106] /// </summary> public bool? PhysicallyDeterioratedIndicator { get => _physicallyDeterioratedIndicator; set => SetField(ref _physicallyDeterioratedIndicator, value); } /// <summary> /// USDA - Annual and Repayment Income Worksheet Prepared By Name [USDA.X196] /// </summary> public string? PreparedByName { get => _preparedByName; set => SetField(ref _preparedByName, value); } /// <summary> /// USDA - Annual and Repayment Income Worksheet Prepared By Title [USDA.X197] /// </summary> public string? PreparedByTitle { get => _preparedByTitle; set => SetField(ref _preparedByTitle, value); } /// <summary> /// USDA - Present Landloard - Address [USDA.X109] /// </summary> public string? PresentLandloardAddress { get => _presentLandloardAddress; set => SetField(ref _presentLandloardAddress, value); } /// <summary> /// USDA - Present Landloard - City [USDA.X110] /// </summary> public string? PresentLandloardCity { get => _presentLandloardCity; set => SetField(ref _presentLandloardCity, value); } /// <summary> /// USDA - Present Landloard - Name [USDA.X108] /// </summary> public string? PresentLandloardName { get => _presentLandloardName; set => SetField(ref _presentLandloardName, value); } /// <summary> /// USDA - Present Landloard - Phone Number [USDA.X113] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? PresentLandloardPhone { get => _presentLandloardPhone; set => SetField(ref _presentLandloardPhone, value); } /// <summary> /// USDA - Present Landloard - State [USDA.X111] /// </summary> public StringEnumValue<State> PresentLandloardState { get => _presentLandloardState; set => SetField(ref _presentLandloardState, value); } /// <summary> /// USDA - Present Landloard - Zip [USDA.X112] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? PresentLandloardZip { get => _presentLandloardZip; set => SetField(ref _presentLandloardZip, value); } /// <summary> /// USDA - Previous Landloard - Address [USDA.X115] /// </summary> public string? PreviousLandloardAddress { get => _previousLandloardAddress; set => SetField(ref _previousLandloardAddress, value); } /// <summary> /// USDA - Previous Landloard - City [USDA.X116] /// </summary> public string? PreviousLandloardCity { get => _previousLandloardCity; set => SetField(ref _previousLandloardCity, value); } /// <summary> /// USDA - Previous Landloard - Name [USDA.X114] /// </summary> public string? PreviousLandloardName { get => _previousLandloardName; set => SetField(ref _previousLandloardName, value); } /// <summary> /// USDA - Previous Landloard - Phone Number [USDA.X119] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? PreviousLandloardPhone { get => _previousLandloardPhone; set => SetField(ref _previousLandloardPhone, value); } /// <summary> /// USDA - Previous Landloard - State [USDA.X117] /// </summary> public StringEnumValue<State> PreviousLandloardState { get => _previousLandloardState; set => SetField(ref _previousLandloardState, value); } /// <summary> /// USDA - Previous Landloard - Zip [USDA.X118] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? PreviousLandloardZip { get => _previousLandloardZip; set => SetField(ref _previousLandloardZip, value); } /// <summary> /// USDA - Purchase or Refinanced Amount [USDA.X198] /// </summary> public decimal? PurchaseOrRefinancedAmount { get => _purchaseOrRefinancedAmount; set => SetField(ref _purchaseOrRefinancedAmount, value); } /// <summary> /// USDA - Purchase / Refinance Description [USDA.X20] /// </summary> public string? PurchaseOrRefinanceDescription { get => _purchaseOrRefinanceDescription; set => SetField(ref _purchaseOrRefinanceDescription, value); } /// <summary> /// USDA - RD SFH Refinance Loan Indicator [USDA.X8] /// </summary> public StringEnumValue<RdsfhRefinancedLoanIndicatorType> RdsfhRefinancedLoanIndicatorType { get => _rdsfhRefinancedLoanIndicatorType; set => SetField(ref _rdsfhRefinancedLoanIndicatorType, value); } /// <summary> /// USDA Refinance Loan Indicator [USDA.X7] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RefinanceLoanIndicator { get => _refinanceLoanIndicator; set => SetField(ref _refinanceLoanIndicator, value); } /// <summary> /// USDA - Refinance Type [USDA.X218] /// </summary> public StringEnumValue<UsdaRefinanceType> RefinanceType { get => _refinanceType; set => SetField(ref _refinanceType, value); } /// <summary> /// USDA - Repair / Other Amount [USDA.X24] /// </summary> public decimal? RepairOtherAmount { get => _repairOtherAmount; set => SetField(ref _repairOtherAmount, value); } /// <summary> /// USDA - Repair / Other Description [USDA.X23] /// </summary> public string? RepairOtherDescription { get => _repairOtherDescription; set => SetField(ref _repairOtherDescription, value); } /// <summary> /// USDA - Reservation Amount Requested [USDA.X33] /// </summary> public decimal? ReservationAmountRequested { get => _reservationAmountRequested; set => SetField(ref _reservationAmountRequested, value); } /// <summary> /// USDA - Loan Closing - Reserved [USDA.X141] /// </summary> public string? Reserved { get => _reserved; set => SetField(ref _reserved, value); } /// <summary> /// USDA - Loan Closing - Servicing Office [USDA.X128] /// </summary> public string? ServicingOfficeName { get => _servicingOfficeName; set => SetField(ref _servicingOfficeName, value); } /// <summary> /// USDA - Annual Adjusted Income - Applicants Eligible for SFHGLP [USDA.X181] /// </summary> public bool? SfhglpIndicator { get => _sfhglpIndicator; set => SetField(ref _sfhglpIndicator, value); } /// <summary> /// USDA - Source of Funds [USDA.X166] /// </summary> public StringEnumValue<SourceOfFundsType> SourceOfFundsType { get => _sourceOfFundsType; set => SetField(ref _sourceOfFundsType, value); } /// <summary> /// USDA - Annual Adjusted Income - Stable Dependable Monthly Income (parties to note only) [USDA.X182] /// </summary> public decimal? StableDependableMonthlyIncome { get => _stableDependableMonthlyIncome; set => SetField(ref _stableDependableMonthlyIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Borrower Calculation of Other Income Description [USDA.X200] /// </summary> public string? StableOtherIncomeDesc { get => _stableOtherIncomeDesc; set => SetField(ref _stableOtherIncomeDesc, value); } /// <summary> /// USDA - Submitting Lender Information - Address [USDA.X36] /// </summary> public string? SubmittingLenderAddress { get => _submittingLenderAddress; set => SetField(ref _submittingLenderAddress, value); } /// <summary> /// USDA - Submitting Lender Information - City [USDA.X37] /// </summary> public string? SubmittingLenderCity { get => _submittingLenderCity; set => SetField(ref _submittingLenderCity, value); } /// <summary> /// USDA - Submitting Lender Information - Contact Fax Number [USDA.X42] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? SubmittingLenderContactFax { get => _submittingLenderContactFax; set => SetField(ref _submittingLenderContactFax, value); } /// <summary> /// USDA - Submitting Lender Information - Contact Name [USDA.X40] /// </summary> public string? SubmittingLenderContactName { get => _submittingLenderContactName; set => SetField(ref _submittingLenderContactName, value); } /// <summary> /// USDA - Submitting Lender Information - Contact Phone Number [USDA.X41] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? SubmittingLenderContactPhone { get => _submittingLenderContactPhone; set => SetField(ref _submittingLenderContactPhone, value); } /// <summary> /// USDA - Submitting Lender Information - Name [USDA.X34] /// </summary> public string? SubmittingLenderName { get => _submittingLenderName; set => SetField(ref _submittingLenderName, value); } /// <summary> /// USDA - Submitting Lender Information - State [USDA.X38] /// </summary> public StringEnumValue<State> SubmittingLenderState { get => _submittingLenderState; set => SetField(ref _submittingLenderState, value); } /// <summary> /// USDA - Submitting Lender Information - Tax ID No. [USDA.X35] /// </summary> public string? SubmittingLenderTaxId { get => _submittingLenderTaxId; set => SetField(ref _submittingLenderTaxId, value); } /// <summary> /// USDA - Submitting Lender Information - Zip [USDA.X39] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? SubmittingLenderZip { get => _submittingLenderZip; set => SetField(ref _submittingLenderZip, value); } /// <summary> /// USDA - Loan Closing - Term of Buydown / Interest Assistance Years [USDA.X135] /// </summary> [LoanFieldProperty(OptionsJson = "{\"1\":\"1\",\"2\":\"2\",\"3\":\"3\",\"4\":\"4\",\"5\":\"5\",\"6\":\"6\",\"7\":\"7\",\"8\":\"8\",\"9\":\"9\",\"10\":\"10\"}")] public int? TermOfBuydown { get => _termOfBuydown; set => SetField(ref _termOfBuydown, value); } /// <summary> /// USDA - Third Party Originator (TPO) [USDA.X27] /// </summary> public string? ThirdPartyOriginator { get => _thirdPartyOriginator; set => SetField(ref _thirdPartyOriginator, value); } /// <summary> /// USDA - Loan Closing - Title [USDA.X149] /// </summary> public string? Title { get => _title; set => SetField(ref _title, value); } /// <summary> /// USDA - Annual Adjusted Income - Total of Borrower and Coborrower Stable Base Income [USDA.X207] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalBorrowerStableBaseIncome { get => _totalBorrowerStableBaseIncome; set => SetField(ref _totalBorrowerStableBaseIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Total of Borrower and Coborrower Stable Other Income [USDA.X208] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalBorrowerStableOtherIncome { get => _totalBorrowerStableOtherIncome; set => SetField(ref _totalBorrowerStableOtherIncome, value); } /// <summary> /// USDA - Annual Adjusted Income - Total Household Deduction [USDA.X177] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalHouseholdDeduction { get => _totalHouseholdDeduction; set => SetField(ref _totalHouseholdDeduction, value); } /// <summary> /// USDA - Total Request Amount [USDA.X26] /// </summary> public decimal? TotalRequestAmount { get => _totalRequestAmount; set => SetField(ref _totalRequestAmount, value); } /// <summary> /// USDA - Third Party Originator (TPO) Tax ID No. [USDA.X28] /// </summary> public string? TpoTaxId { get => _tpoTaxId; set => SetField(ref _tpoTaxId, value); } /// <summary> /// USDA - Tracking - Underwriting Decision By [USDA.X151] /// </summary> public string? UnderwritingDecisionBy { get => _underwritingDecisionBy; set => SetField(ref _underwritingDecisionBy, value); } /// <summary> /// USDA - Tracking - Underwriting Decision Date [USDA.X150] /// </summary> public DateTime? UnderwritingDecisionDate { get => _underwritingDecisionDate; set => SetField(ref _underwritingDecisionDate, value); } /// <summary> /// USDA - Tracking - Underwriting Decision [USDA.X152] /// </summary> public StringEnumValue<UnderwritingDecisionType> UnderwritingDecisionType { get => _underwritingDecisionType; set => SetField(ref _underwritingDecisionType, value); } /// <summary> /// Usda UsdaHouseholdIncomes /// </summary> [AllowNull] public IList<UsdaHouseholdIncome> UsdaHouseholdIncomes { get => GetField(ref _usdaHouseholdIncomes); set => SetField(ref _usdaHouseholdIncomes, value); } /// <summary> /// USDA - Tracking - Verification Code [USDA.X163] /// </summary> public string? VerificationCode { get => _verificationCode; set => SetField(ref _verificationCode, value); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.ResourcesHandler.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { /// <summary> A utility class to get strings from the ExceptionMessages and /// ResultCodeMessages resources. /// </summary> public class ResourcesHandler { // Cannot create an instance of this class private ResourcesHandler() { return ; } /* * Initialized when the first result string is requested */ private static System.Resources.ResourceManager defaultResultCodes = null; /// <summary> Initialized when the first Exception message string is requested</summary> private static System.Resources.ResourceManager defaultMessages = null; /// <summary> Package where resources are found</summary> private static System.String pkg = "Novell.Directory.Ldap.Utilclass."; /// <summary> The default Locale</summary> private static System.Globalization.CultureInfo defaultLocale; /// <summary> Returns a string using the MessageOrKey as a key into /// ExceptionMessages or, if the Key does not exist, returns the /// string messageOrKey. In addition it formats the arguments into the message /// according to MessageFormat. /// /// </summary> /// <param name="messageOrKey"> Key string for the resource. /// /// </param> /// <param name="">arguments /// /// </param> /// <returns> the text for the message specified by the MessageKey or the Key /// if it there is no message for that key. /// </returns> public static System.String getMessage(System.String messageOrKey, System.Object[] arguments) { return getMessage(messageOrKey, arguments, null); } /// <summary> Returns the message stored in the ExceptionMessages resource for the /// specified locale using messageOrKey and argments passed into the /// constructor. If no string exists in the resource then this returns /// the string stored in message. (This method is identical to /// getLdapErrorMessage(Locale locale).) /// /// </summary> /// <param name="messageOrKey"> Key string for the resource. /// /// </param> /// <param name="">arguments /// /// </param> /// <param name="locale"> The Locale that should be used to pull message /// strings out of ExceptionMessages. /// /// </param> /// <returns> the text for the message specified by the MessageKey or the Key /// if it there is no message for that key. /// </returns> public static System.String getMessage(System.String messageOrKey, System.Object[] arguments, System.Globalization.CultureInfo locale) { System.String pattern; System.Resources.ResourceManager messages = null; if ((System.Object) messageOrKey == null) { messageOrKey = ""; } try { if ((locale == null) || defaultLocale.Equals(locale)) { locale = defaultLocale; // Default Locale if (defaultMessages == null) { System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale; defaultMessages = System.Resources.ResourceManager.CreateFileBasedResourceManager(pkg + "ExceptionMessages", "", null); } messages = defaultMessages; } else { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; messages = System.Resources.ResourceManager.CreateFileBasedResourceManager(pkg + "ExceptionMessages", "", null); } pattern = messages.GetString(messageOrKey); } catch (System.Resources.MissingManifestResourceException mre) { pattern = messageOrKey; } // Format the message if arguments were passed if (arguments != null) { // MessageFormat mf = new MessageFormat(pattern); pattern=System.String.Format(locale,pattern,arguments); // mf.setLocale(locale); //this needs to be reset with the new local - i18n defect in java // mf.applyPattern(pattern); // pattern = mf.format(arguments); } return pattern; } /// <summary> Returns a string representing the Ldap result code from the /// default ResultCodeMessages resource. /// /// </summary> /// <param name="code"> the result code /// /// </param> /// <returns> the String representing the result code. /// </returns> public static System.String getResultString(int code) { return getResultString(code, null); } /// <summary> Returns a string representing the Ldap result code. The message /// is obtained from the locale specific ResultCodeMessage resource. /// /// </summary> /// <param name="code"> the result code /// /// </param> /// <param name="locale"> The Locale that should be used to pull message /// strings out of ResultMessages. /// /// </param> /// <returns> the String representing the result code. /// </returns> public static System.String getResultString(int code, System.Globalization.CultureInfo locale) { System.Resources.ResourceManager messages; System.String result; try { if ((locale == null) || defaultLocale.Equals(locale)) { locale = defaultLocale; // Default Locale if (defaultResultCodes == null) { // System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale; defaultResultCodes = System.Resources.ResourceManager.CreateFileBasedResourceManager(pkg + "ResultCodeMessages", "", null); } messages = defaultResultCodes; } else { System.Threading.Thread.CurrentThread.CurrentUICulture = locale; messages = System.Resources.ResourceManager.CreateFileBasedResourceManager(pkg + "ResultCodeMessages", "", null); } // result = messages.GetString(System.Convert.ToString(code)); result = Convert.ToString(code); } catch (System.Resources.MissingManifestResourceException mre) { result = getMessage(ExceptionMessages.UNKNOWN_RESULT, new System.Object[]{code}, locale); } return result; } static ResourcesHandler() { // defaultLocale = System.Globalization.CultureInfo.CurrentCulture; } } //end class ResourcesHandler }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Implementation of task continuations, TaskContinuation, and its descendants. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.CompilerServices; using Internal.Runtime.Augments; using AsyncStatus = Internal.Runtime.Augments.AsyncStatus; using CausalityRelation = Internal.Runtime.Augments.CausalityRelation; using CausalitySource = Internal.Runtime.Augments.CausalitySource; using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel; using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task,...>) internal sealed class ContinuationTaskFromTask : Task { private Task m_antecedent; public ContinuationTaskFromTask( Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task> || action is Action<Task, object>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); var action = m_action as Action<Task>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task m_antecedent; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); var func = m_action as Func<Task, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult> m_antecedent; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); var action = m_action as Action<Task<TAntecedentResult>>; if (action != null) { action(antecedent); return; } var actionWithState = m_action as Action<Task<TAntecedentResult>, object>; if (actionWithState != null) { actionWithState(antecedent, m_stateObject); return; } Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult> m_antecedent; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; PossiblyCaptureContext(); } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); var func = m_action as Func<Task<TAntecedentResult>, TResult>; if (func != null) { m_result = func(antecedent); return; } var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>; if (funcWithState != null) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); } } // For performance reasons, we don't just have a single way of representing // a continuation object. Rather, we have a hierarchy of types: // - TaskContinuation: abstract base that provides a virtual Run method // - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration // - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default // - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler // - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx /// <summary>Represents a continuation.</summary> internal abstract class TaskContinuation { /// <summary>Inlines or schedules the continuation.</summary> /// <param name="completedTask">The antecedent task that has completed.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal abstract void Run(Task completedTask, bool bCanInlineContinuationTask); /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary> /// <param name="task">The task to run</param> /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Debug.Assert(task != null); Debug.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it // that may try to execute it. if (needsProtection) { if (!task.MarkStarted()) return; // task has been previously started or canceled. Stop processing. } else { task.m_stateFlags |= Task.TASK_STATE_STARTED; } // Try to inline it but queue if we can't try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.QueueTask(task); } } catch (Exception e) { // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted. // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, // because it would already have been handled in Task.Execute() //if (!(e is ThreadAbortException && // (task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0)) // this ensures TAEs from QueueTask will be wrapped in TSE { TaskSchedulerException tse = new TaskSchedulerException(e); task.AddException(tse); task.Finish(false); } // Don't re-throw. } } // // This helper routine is targeted by the debugger. // [DependencyReductionRoot] internal abstract Delegate[] GetDelegateContinuationsForDebugger(); } /// <summary>Provides the standard implementation of a task continuation.</summary> internal class StandardTaskContinuation : TaskContinuation { /// <summary>The unstarted continuation task.</summary> internal readonly Task m_task; /// <summary>The options to use with the continuation task.</summary> internal readonly TaskContinuationOptions m_options; /// <summary>The task scheduler with which to run the continuation task.</summary> private readonly TaskScheduler m_taskScheduler; /// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Debug.Assert(task != null, "TaskContinuation ctor: task is null"); Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, m_task, "Task.ContinueWith: " + task.m_action, 0); DebuggerSupport.AddToActiveTasks(m_task); } /// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool bCanInlineContinuationTask) { Debug.Assert(completedTask != null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsRanToCompletion ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. Task continuationTask = m_task; if (isRightKind) { if (!continuationTask.IsCanceled && DebuggerSupport.LoggingOn) { // Log now that we are sure that this continuation is being ran DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (bCanInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } // Otherwise, the final state of this task does not match the desired // continuation activation criteria; cancel it to denote this. else continuationTask.InternalCancel(false); } internal override Delegate[] GetDelegateContinuationsForDebugger() { if (m_task.m_action == null) { return m_task.GetDelegateContinuationsForDebugger(); } return new Delegate[] { m_task.m_action }; } } /// <summary>Task continuation for awaiting with a current synchronization context.</summary> internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private static readonly SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical /// <summary>Cached delegate for PostAction</summary> private static ContextCallback s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="stackMark">The captured stack mark.</param> internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); } // Otherwise, Post the action back to the SynchronizationContext. else { RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } // Any exceptions will be handled by RunCallback. } /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> private static void PostAction(object state) { var c = (SynchronizationContextAwaitTaskContinuation)state; c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method } /// <summary>Gets a cached delegate for the PostAction method.</summary> /// <returns> /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() { ContextCallback callback = s_postActionCallback; if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate return callback; } } /// <summary>Task continuation for awaiting with a task scheduler.</summary> internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>The scheduler on which to run the action.</summary> private readonly TaskScheduler m_scheduler; /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary> /// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="stackMark">The captured stack mark.</param> internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(scheduler != null); m_scheduler = scheduler; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're targeting the default scheduler, we can use the faster path provided by the base class. if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); } else { // We permit inlining if the caller allows us to, and // either we're on a thread pool thread (in which case we're fine running arbitrary code) // or we're already on the target scheduler (in which case we'll just ask the scheduler // whether it's ok to run here). We include the IsThreadPoolThread check here, whereas // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed // to in AwaitTaskContinuation.Run where it restricts what's allowed. bool inlineIfPossible = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || ThreadPool.IsThreadPoolThread); // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. var task = CreateTask(state => { try { ((Action)state)(); } catch (Exception exc) { ThrowAsyncIfNecessary(exc); } }, m_action, m_scheduler); if (inlineIfPossible) { InlineIfPossibleOrElseQueue(task, needsProtection: false); } else { // We need to run asynchronously, so just schedule the task. try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted } } } } /// <summary>Base task continuation class used for await continuations.</summary> internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { /// <summary>The ExecutionContext with which to run the continuation.</summary> private readonly ExecutionContext m_capturedContext; /// <summary>The action to invoke.</summary> protected readonly Action m_action; /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Debug.Assert(action != null); m_action = action; if (flowExecutionContext) m_capturedContext = ExecutionContext.Capture(); } /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary> /// <param name="action">The action to run. Must not be null.</param> /// <param name="state">The state to pass to the action. Must not be null.</param> /// <param name="scheduler">The scheduler to target.</param> /// <returns>The created task.</returns> protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler) { Debug.Assert(action != null); Debug.Assert(scheduler != null); return new Task( action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler); } /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal override void Run(Task ignored, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it // and if we're in a "valid location" for it. See the comments on // IsValidLocationForInlining for more about what's valid. For performance // reasons we would like to always inline, but we don't in some cases to avoid // running arbitrary amounts of work in suspected "bad locations", like UI threads. if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction } else { // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false); } } /// <summary> /// Gets whether the current thread is an appropriate location to inline a continuation's execution. /// </summary> /// <remarks> /// Returns whether SynchronizationContext is null and we're in the default scheduler. /// If the await had a SynchronizationContext/TaskScheduler where it began and the /// default/ConfigureAwait(true) was used, then we won't be on this path. If, however, /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were /// naturally null/Default, then we might end up here. If we do, we need to make sure /// that we don't execute continuations in a place that isn't set up to handle them, e.g. /// running arbitrary amounts of code on the UI thread. It would be "correct", but very /// expensive, to always run the continuations asynchronously, incurring lots of context /// switches and allocations and locks and the like. As such, we employ the heuristic /// that if the current thread has a non-null SynchronizationContext or a non-default /// scheduler, then we better not run arbitrary continuations here. /// </remarks> internal static bool IsValidLocationForInlining { get { // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. var ctx = SynchronizationContext.Current; if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. var sched = TaskScheduler.InternalCurrent; return sched == null || sched == TaskScheduler.Default; } } /// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary> void IThreadPoolWorkItem.ExecuteWorkItem() { // inline the fast path if (m_capturedContext == null) m_action(); else ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action); } ///// <summary> ///// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. ///// </summary> //void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> private static ContextCallback s_invokeActionCallback; /// <summary>Runs an action provided as an object parameter.</summary> /// <param name="state">The Action to invoke.</param> private static void InvokeAction(object state) { ((Action)state)(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() { ContextCallback callback = s_invokeActionCallback; if (callback == null) { s_invokeActionCallback = callback = InvokeAction; } // lazily initialize SecurityCritical delegate return callback; } /// <summary>Runs the callback synchronously with the provided state.</summary> /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { Debug.Assert(callback != null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information var prevCurrentTask = currentTask; var prevSyncCtx = SynchronizationContext.CurrentExplicit; try { if (prevCurrentTask != null) currentTask = null; callback(state); } catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs { ThrowAsyncIfNecessary(exc); } finally { // Restore the current task information if (prevCurrentTask != null) currentTask = prevCurrentTask; // Restore the SynchronizationContext SynchronizationContext.SetSynchronizationContext(prevSyncCtx); } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the action to run asynchronously. /// </param> /// <param name="currentTask"> /// A reference to the t_currentTask thread static value. /// This is passed by-ref rather than accessed in the method in order to avoid /// unnecessary thread-static writes. /// </param> /// <remarks> /// No ExecutionContext work is performed used. This method is only used in the /// case where a raw Action continuation delegate was stored into the Task, which /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask) { Debug.Assert(currentTask == Task.t_currentTask); // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action); return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution Task prevCurrentTask = currentTask; try { if (prevCurrentTask != null) currentTask = null; action(); } catch (Exception exception) { ThrowAsyncIfNecessary(exception); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> internal static void UnsafeScheduleAction(Action action) { ThreadPool.UnsafeQueueCustomWorkItem( new AwaitTaskContinuation(action, flowExecutionContext: false), forceGlobal: false); } /// <summary>Throws the exception asynchronously on the ThreadPool.</summary> /// <param name="exc">The exception to throw.</param> protected static void ThrowAsyncIfNecessary(Exception exc) { // Awaits should never experience an exception (other than an TAE or ADUE), // unless a malicious user is explicitly passing a throwing action into the TaskAwaiter. // We don't want to allow the exception to propagate on this stack, as it'll emerge in random places, // and we can't fail fast, as that would allow for elevation of privilege. Instead, since this // would have executed on the thread pool otherwise, let it propagate there. //if (!(exc is ThreadAbortException || exc is AppDomainUnloadedException)) { RuntimeAugments.ReportUnhandledException(exc); } } internal override Delegate[] GetDelegateContinuationsForDebugger() { Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.IO.Ports.SerialPort.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.IO.Ports { public partial class SerialPort : System.ComponentModel.Component { #region Methods and constructors public void Close() { } public void DiscardInBuffer() { } public void DiscardOutBuffer() { } protected override void Dispose(bool disposing) { } public static string[] GetPortNames() { Contract.Ensures(Contract.Result<string[]>() != null); return default(string[]); } public void Open() { } public int Read(byte[] buffer, int offset, int count) { return default(int); } public int Read(char[] buffer, int offset, int count) { return default(int); } public int ReadByte() { return default(int); } public int ReadChar() { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 65535); return default(int); } public string ReadExisting() { return default(string); } public string ReadLine() { return default(string); } public string ReadTo(string value) { return default(string); } public SerialPort() { } public SerialPort(string portName) { Contract.Ensures(0 <= portName.Length); } public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) { } public SerialPort(string portName, int baudRate) { Contract.Ensures(0 <= portName.Length); } public SerialPort(string portName, int baudRate, Parity parity, int dataBits) { Contract.Ensures(0 <= portName.Length); } public SerialPort(System.ComponentModel.IContainer container) { Contract.Requires(container != null); } public SerialPort(string portName, int baudRate, Parity parity) { Contract.Ensures(0 <= portName.Length); } public void Write(byte[] buffer, int offset, int count) { } public void Write(string text) { } public void Write(char[] buffer, int offset, int count) { } public void WriteLine(string text) { } #endregion #region Properties and indexers public Stream BaseStream { get { Contract.Ensures(this.IsOpen == true); return default(Stream); } } public int BaudRate { get { return default(int); } set { } } public bool BreakState { get { Contract.Ensures(this.IsOpen == true); return default(bool); } set { Contract.Ensures(this.IsOpen == true); } } public int BytesToRead { get { Contract.Ensures(this.IsOpen == true); return default(int); } } public int BytesToWrite { get { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(this.IsOpen == true); return default(int); } } public bool CDHolding { get { Contract.Ensures(this.IsOpen == true); return default(bool); } } public bool CtsHolding { get { Contract.Ensures(this.IsOpen == true); return default(bool); } } public int DataBits { get { return default(int); } set { } } public bool DiscardNull { get { return default(bool); } set { } } public bool DsrHolding { get { Contract.Ensures(this.IsOpen == true); return default(bool); } } public bool DtrEnable { get { return default(bool); } set { } } public Encoding Encoding { get { return default(Encoding); } set { } } public Handshake Handshake { get { return default(Handshake); } set { } } public bool IsOpen { get { return default(bool); } } public string NewLine { get { return default(string); } set { } } public Parity Parity { get { return default(Parity); } set { } } public byte ParityReplace { get { return default(byte); } set { } } public string PortName { get { return default(string); } set { } } public int ReadBufferSize { get { return default(int); } set { } } public int ReadTimeout { get { return default(int); } set { } } public int ReceivedBytesThreshold { get { return default(int); } set { } } public bool RtsEnable { get { return default(bool); } set { } } public StopBits StopBits { get { return default(StopBits); } set { } } public int WriteBufferSize { get { return default(int); } set { } } public int WriteTimeout { get { return default(int); } set { } } #endregion #region Events public event SerialDataReceivedEventHandler DataReceived { add { } remove { } } public event SerialErrorReceivedEventHandler ErrorReceived { add { } remove { } } public event SerialPinChangedEventHandler PinChanged { add { } remove { } } #endregion #region Fields public static int InfiniteTimeout; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using size_t = System.UInt64; using curl_socket_t = System.Int32; internal static partial class Interop { internal static partial class libcurl { // Class for constants defined for the global flags in curl.h internal static partial class CurlGlobalFlags { internal const long CURL_GLOBAL_SSL = 1L; internal const long CURL_GLOBAL_WIN32 = 2L; internal const long CURL_GLOBAL_ALL = (CURL_GLOBAL_SSL | CURL_GLOBAL_WIN32); } // Class for constants defined for the enum CURLoption in curl.h internal static partial class CURLoption { // Curl options are of the format <type base> + <n> private const int CurlOptionLongBase = 0; private const int CurlOptionObjectPointBase = 10000; private const int CurlOptionFunctionPointBase = 20000; internal const int CURLOPT_NOBODY = CurlOptionLongBase + 44; internal const int CURLOPT_UPLOAD = CurlOptionLongBase + 46; internal const int CURLOPT_POST = CurlOptionLongBase + 47; internal const int CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52; internal const int CURLOPT_PROXYPORT = CurlOptionLongBase + 59; internal const int CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60; internal const int CURLOPT_MAXREDIRS = CurlOptionLongBase + 68; internal const int CURLOPT_PROXYTYPE = CurlOptionLongBase + 101; internal const int CURLOPT_HTTPAUTH = CurlOptionLongBase + 107; internal const int CURLOPT_WRITEDATA = CurlOptionObjectPointBase + 1; internal const int CURLOPT_URL = CurlOptionObjectPointBase + 2; internal const int CURLOPT_PROXY = CurlOptionObjectPointBase + 4; internal const int CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6; internal const int CURLOPT_READDATA = CurlOptionObjectPointBase + 9; internal const int CURLOPT_POSTFIELDS = CurlOptionObjectPointBase + 15; internal const int CURLOPT_COOKIE = CurlOptionObjectPointBase + 22; internal const int CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23; internal const int CURLOPT_HEADERDATA = CurlOptionObjectPointBase + 29; internal const int CURLOPT_ACCEPTENCODING = CurlOptionObjectPointBase + 102; internal const int CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103; internal const int CURLOPT_IOCTLDATA = CurlOptionObjectPointBase + 131; internal const int CURLOPT_USERNAME = CurlOptionObjectPointBase + 173; internal const int CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174; internal const int CURLOPT_WRITEFUNCTION = CurlOptionFunctionPointBase + 11; internal const int CURLOPT_READFUNCTION = CurlOptionFunctionPointBase + 12; internal const int CURLOPT_HEADERFUNCTION = CurlOptionFunctionPointBase + 79; internal const int CURLOPT_IOCTLFUNCTION = CurlOptionFunctionPointBase + 130; } // Class for constants defined for the enum CURLMoption in multi.h internal static partial class CURLMoption { // Curl options are of the format <type base> + <n> private const int CurlOptionObjectPointBase = 10000; private const int CurlOptionFunctionPointBase = 20000; internal const int CURLMOPT_TIMERDATA = CurlOptionObjectPointBase + 5; internal const int CURLMOPT_SOCKETFUNCTION = CurlOptionFunctionPointBase + 1; internal const int CURLMOPT_TIMERFUNCTION = CurlOptionFunctionPointBase + 4; } // Class for constants defined for the enum CURLINFO in curl.h internal static partial class CURLINFO { // Curl info are of the format <type base> + <n> private const int CurlInfoStringBase = 0x100000; private const int CurlInfoLongBase = 0x200000; internal const int CURLINFO_PRIVATE = CurlInfoStringBase + 21; internal const int CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23; } // Class for constants defined for the enum curl_proxytype in curl.h internal static partial class curl_proxytype { internal const int CURLPROXY_HTTP = 0; } // Class for constants defined for the enum CURLcode in curl.h internal static partial class CURLcode { internal const int CURLE_OK = 0; } // Class for constants defined for the enum CURLMcode in multi.h internal static partial class CURLMcode { internal const int CURLM_OK = 0; } // Class for constants defined for the enum curlioerr in curl.h internal static partial class curlioerr { internal const int CURLIOE_OK = 0; internal const int CURLIOE_UNKNOWNCMD = 1; internal const int CURLIOE_FAILRESTART = 2; } // Class for constants defined for the enum curliocmd in curl.h internal static partial class curliocmd { internal const int CURLIOCMD_RESTARTREAD = 1; } // Class for CURL_POLL_* macros in multi.h internal static partial class CurlPoll { internal const int CURL_POLL_REMOVE = 4; } // Class for CURL_CSELECT_* macros in multi.h internal static partial class CurlSelect { internal const int CURL_CSELECT_IN = 1; internal const int CURL_CSELECT_OUT = 2; } // Class for constants defined for the enum CURLMSG in multi.h internal static partial class CURLMSG { internal const int CURLMSG_DONE = 1; } // AUTH related constants internal static partial class CURLAUTH { internal const ulong None = 0; internal const ulong Basic = 1 << 0; internal const ulong Digest = 1 << 1; internal const ulong Negotiate = 1 << 2; internal const ulong DigestIE = 1 << 4; internal const ulong AuthAny = ~DigestIE; } internal static partial class CURL_VERSION_Features { internal const int CURL_VERSION_IPV6 = (1<<0); internal const int CURL_VERSION_KERBEROS4 = (1<<1); internal const int CURL_VERSION_SSL = (1<<2); internal const int CURL_VERSION_LIBZ = (1<<3); internal const int CURL_VERSION_NTLM = (1<<4); internal const int CURL_VERSION_GSSNEGOTIATE = (1<<5); internal const int CURL_VERSION_DEBUG = (1<<6); internal const int CURL_VERSION_ASYNCHDNS = (1<<7); internal const int CURL_VERSION_SPNEGO = (1<<8); internal const int CURL_VERSION_LARGEFILE = (1<<9); internal const int CURL_VERSION_IDN = (1<<10); internal const int CURL_VERSION_SSPI = (1<<11); internal const int CURL_VERSION_CONV = (1<<12); internal const int CURL_VERSION_CURLDEBUG = (1<<13); internal const int CURL_VERSION_TLSAUTH_SRP = (1<<14); internal const int CURL_VERSION_NTLM_WB = (1<<15); internal const int CURL_VERSION_HTTP2 = (1<<16); internal const int CURL_VERSION_GSSAPI = (1<<17); internal const int CURL_VERSION_KERBEROS5 = (1<<18); internal const int CURL_VERSION_UNIX_SOCKETS = (1<<19); } // Type definition of CURLMsg from multi.h [StructLayout(LayoutKind.Explicit)] internal struct CURLMsg { [FieldOffset(0)] internal int msg; [FieldOffset(8)] internal IntPtr easy_handle; [FieldOffset(16)] internal IntPtr data; [FieldOffset(16)] internal int result; } // NOTE: The definition of this structure in Curl/curl.h is larger than // than what is defined below. This definition is only valid for use with // Marshal.PtrToStructure and not for general use in P/Invoke signatures. [StructLayout(LayoutKind.Sequential)] internal struct curl_version_info_data { internal int age; private unsafe char *version; private int versionNum; private unsafe char *host; internal int features; } public delegate int curl_socket_callback( IntPtr handle, curl_socket_t sockfd, int what, IntPtr context, IntPtr sockptr); public delegate int curl_multi_timer_callback( IntPtr handle, long timeout_ms, IntPtr context); public delegate size_t curl_readwrite_callback( IntPtr buffer, size_t size, size_t nitems, IntPtr context); public unsafe delegate size_t curl_unsafe_write_callback( byte* buffer, size_t size, size_t nitems, IntPtr context); public delegate int curl_ioctl_callback( IntPtr handle, int cmd, IntPtr context); } }
using System.Net.Http; using Bandwidth.Net.Api; using Xunit; namespace Bandwidth.Net.Test { public class CallbackEventTests { [Fact] public void TestCreateFromJson() { var callbackEvent = CallbackEvent.CreateFromJson("{\"eventType\": \"speak\", \"state\": \"PLAYBACK_STOP\"}"); Assert.Equal(CallbackEventType.Speak, callbackEvent.EventType); Assert.Equal(CallbackEventState.PlaybackStop, callbackEvent.State); } [Fact] public void TestCreateFromJson2() { var callbackEvent = CallbackEvent.CreateFromJson("{\"eventType\": \"sms\", \"deliveryState\": \"not-delivered\"}"); Assert.Equal(CallbackEventType.Sms, callbackEvent.EventType); Assert.Equal(MessageDeliveryState.NotDelivered, callbackEvent.DeliveryState); } [Fact] public void TestCreateFromJson3() { var callbackEvent = CallbackEvent.CreateFromJson("{}"); Assert.Equal(CallbackEventType.Unknown, callbackEvent.EventType); } [Fact] public void TestSmsEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("SmsEvent")); Assert.Equal(CallbackEventType.Sms, callbackEvent.EventType); Assert.Equal("{messageId}", callbackEvent.MessageId); } [Fact] public void TestMmsEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("MmsEvent")); Assert.Equal(CallbackEventType.Mms, callbackEvent.EventType); Assert.Equal("m-dr4mcch2wfb6frcls677glq", callbackEvent.MessageId); } [Fact] public void TestAnswerEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("AnswerEvent")); Assert.Equal(CallbackEventType.Answer, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); } [Fact] public void TestPlaybackEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("PlaybackEvent")); Assert.Equal(CallbackEventType.Playback, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); } [Fact] public void TestTimeoutEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("TimeoutEvent")); Assert.Equal(CallbackEventType.Timeout, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); } [Fact] public void TestConferenceEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("ConferenceEvent")); Assert.Equal(CallbackEventType.Conference, callbackEvent.EventType); Assert.Equal("{conferenceId}", callbackEvent.ConferenceId); } [Fact] public void TestConferencePlaybackEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("ConferencePlaybackEvent")); Assert.Equal(CallbackEventType.ConferencePlayback, callbackEvent.EventType); Assert.Equal("{conferenceId}", callbackEvent.ConferenceId); } [Fact] public void TestConferenceMemberEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("ConferenceMemberEvent")); Assert.Equal(CallbackEventType.ConferenceMember, callbackEvent.EventType); Assert.Equal("{conferenceId}", callbackEvent.ConferenceId); Assert.Equal("{callId}", callbackEvent.CallId); } [Fact] public void TestConferenceSpeakEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("ConferenceSpeakEvent")); Assert.Equal(CallbackEventType.ConferenceSpeak, callbackEvent.EventType); Assert.Equal("{conferenceId}", callbackEvent.ConferenceId); } [Fact] public void TestDtmfEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("DtmfEvent")); Assert.Equal(CallbackEventType.Dtmf, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("5", callbackEvent.DtmfDigit); } [Fact] public void TestGatherEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("GatherEvent")); Assert.Equal(CallbackEventType.Gather, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("25", callbackEvent.Digits); } [Fact] public void TestIncomingCallEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("IncomingCallEvent")); Assert.Equal(CallbackEventType.Incomingcall, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("{appId}", callbackEvent.ApplicationId); } [Fact] public void TestHangupEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("HangupEvent")); Assert.Equal(CallbackEventType.Hangup, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("NORMAL_CLEARING", callbackEvent.Cause); } [Fact] public void TestRecordingEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("RecordingEvent")); Assert.Equal(CallbackEventType.Recording, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("{recordingId}", callbackEvent.RecordingId); } [Fact] public void TestRejectEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("RejectEvent")); Assert.Equal(CallbackEventType.Hangup, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal("CALL_REJECTED", callbackEvent.Cause); } [Fact] public void TestSpeakEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("SpeakEvent")); Assert.Equal(CallbackEventType.Speak, callbackEvent.EventType); Assert.Equal("{callId}", callbackEvent.CallId); Assert.Equal(CallbackEventStatus.Started, callbackEvent.Status); } [Fact] public void TestTranscriptionEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("TranscriptionEvent")); Assert.Equal(CallbackEventType.Transcription, callbackEvent.EventType); Assert.Equal("{recordingId}", callbackEvent.RecordingId); Assert.Equal("{transcriptionId}", callbackEvent.TranscriptionId); Assert.Equal(CallbackEventState.Completed, callbackEvent.State); } [Fact] public void TestTransferCompleteEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("TransferCompleteEvent")); Assert.Equal(CallbackEventType.TransferComplete, callbackEvent.EventType); Assert.Equal(CallState.Active, callbackEvent.CallState); } [Fact] public void TestRedirectEvent() { var callbackEvent = CallbackEvent.CreateFromJson(Helpers.GetJsonResourse("RedirectEvent")); Assert.Equal(CallbackEventType.Redirect, callbackEvent.EventType); Assert.Equal(CallState.Active, callbackEvent.CallState); } } public class CallbackEventHelpersTests { [Fact] public async void TestReadAsCallbackEvent() { var response = new HttpResponseMessage { Content = new JsonContent("{\"eventType\": \"speak\", \"state\": \"PLAYBACK_STOP\"}") }; var callbackEvent = await response.Content.ReadAsCallbackEventAsync(); Assert.Equal(CallbackEventType.Speak, callbackEvent.EventType); Assert.Equal(CallbackEventState.PlaybackStop, callbackEvent.State); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { using System; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Guid : IFormattable, IComparable , IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b==null) throw new ArgumentNullException("b"); if (b.Length != 16) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), "b"); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d==null) throw new ArgumentNullException("d"); // Check that array is not too big if(d.Length != 8) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), "d"); Contract.EndContractBlock(); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid parsedGuid; internal GuidParseThrowStyle throwStyle; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.NativeException: return m_innerException; default: Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized")); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(String g) { if (g==null) { throw new ArgumentNullException("g"); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException("input"); } Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(String input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException("input"); if (format == null) throw new ArgumentNullException("format"); if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(String input, String format, out Guid result) { if (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch(IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Check for '0x' if(!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; // Check for '{' if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for(int i = 0; i < 8; i++) { // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if(i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidComma"); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber"); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) { return false; } uint number = (uint)signedNumber; // check for overflow if(number > 255) { result.SetFailure(ParseFailureKind.Format, "Overflow_Byte"); return false; } bytes[i] = (byte)number; } result.parsedGuid._d = bytes[0]; result.parsedGuid._e = bytes[1]; result.parsedGuid._f = bytes[2]; result.parsedGuid._g = bytes[3]; result.parsedGuid._h = bytes[4]; result.parsedGuid._i = bytes[5]; result.parsedGuid._j = bytes[6]; result.parsedGuid._k = bytes[7]; // Check for last '}' if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace"); return false; } // Check if we have extra characters at the end if( numStart+numLen+1 != guidString.Length -1) { result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd"); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; if(guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } for(int i= 0; i< guidString.Length; i++) { char ch = guidString[i]; if(ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture); if(upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos!=12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0]=='{') { if (guidString.Length!=38 || guidString[37]!='}') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if (guidString[0]=='(') { if (guidString.Length!=38 || guidString[37]!=')') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if(guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } if (guidString[8+startPos] != '-' || guidString[13+startPos] != '-' || guidString[18+startPos] != '-' || guidString[23+startPos] != '-') { result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes"); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos=currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } result.parsedGuid._d = (byte)(temp>>8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp>>8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp>>24); result.parsedGuid._i = (byte)(temp>>16); result.parsedGuid._j = (byte)(temp>>8); result.parsedGuid._k = (byte)(temp); return true; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { return StringToShort(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { return StringToInt(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = (parsePos == null) ? 0 : (*parsePos); try { result = ParseNumbers.StringToInt(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } return true; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) { return StringToLong(str, null, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToLong(str, ppos, flags, out result, ref parseResult); } } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for(int i = 0; i < str.Length; i++) { curChar = str[i]; if(!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D",null); } [System.Security.SecuritySafeCritical] public unsafe override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. fixed (int* ptr = &this._a) return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3]; } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if(o == null || !(o is Guid)) return false; else g = (Guid) o; // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } private int GetResult(uint me, uint them) { if (me<them) { return -1; } return 1; } public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), "value"); } Guid g = (Guid)value; if (g._a!=this._a) { return GetResult((uint)this._a, (uint)g._a); } if (g._b!=this._b) { return GetResult((uint)this._b, (uint)g._b); } if (g._c!=this._c) { return GetResult((uint)this._c, (uint)g._c); } if (g._d!=this._d) { return GetResult((uint)this._d, (uint)g._d); } if (g._e!=this._e) { return GetResult((uint)this._e, (uint)g._e); } if (g._f!=this._f) { return GetResult((uint)this._f, (uint)g._f); } if (g._g!=this._g) { return GetResult((uint)this._g, (uint)g._g); } if (g._h!=this._h) { return GetResult((uint)this._h, (uint)g._h); } if (g._i!=this._i) { return GetResult((uint)this._i, (uint)g._i); } if (g._j!=this._j) { return GetResult((uint)this._j, (uint)g._j); } if (g._k!=this._k) { return GetResult((uint)this._k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. [System.Security.SecuritySafeCritical] // auto-generated public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some // uniqueness guarantees. It should also never return a known GUID, but it's unclear // how extensively it checks for known values. Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a>>4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b>>4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider [System.Security.SecuritySafeCritical] public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class Sys_VisibilityGroupDS { public Sys_VisibilityGroupDS() { } private const string THIS = "PCSComUtils.Admin.DS.Sys_VisibilityGroupDS"; //************************************************************************** /// <Description> /// This method uses to add data to Sys_VisibilityGroup /// </Description> /// <Inputs> /// Sys_VisibilityGroupVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, October 18, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_VisibilityGroupVO objObject = (Sys_VisibilityGroupVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_VisibilityGroup(" + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.CONTROLNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.CONTROLNAME_FLD].Value = objObject.ControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.PARENTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.PARENTID_FLD].Value = objObject.ParentID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.FORMNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.FORMNAME_FLD].Value = objObject.FormName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXT_FLD].Value = objObject.GroupText; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTVN_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTVN_FLD].Value = objObject.GroupTextVN; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTJP_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTJP_FLD].Value = objObject.GroupTextJP; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.TYPE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.TYPE_FLD].Value = objObject.Type; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from Sys_VisibilityGroup /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + Sys_VisibilityGroupTable.TABLE_NAME + " WHERE " + "VisibilityGroupID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from Sys_VisibilityGroup /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// Sys_VisibilityGroupVO /// </Outputs> /// <Returns> /// Sys_VisibilityGroupVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, October 18, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "," + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + " FROM " + Sys_VisibilityGroupTable.TABLE_NAME +" WHERE " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_VisibilityGroupVO objObject = new Sys_VisibilityGroupVO(); while (odrPCS.Read()) { objObject.VisibilityGroupID = int.Parse(odrPCS[Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD].ToString().Trim()); objObject.ControlName = odrPCS[Sys_VisibilityGroupTable.CONTROLNAME_FLD].ToString().Trim(); objObject.ParentID = int.Parse(odrPCS[Sys_VisibilityGroupTable.PARENTID_FLD].ToString().Trim()); objObject.FormName = odrPCS[Sys_VisibilityGroupTable.FORMNAME_FLD].ToString().Trim(); objObject.GroupText = odrPCS[Sys_VisibilityGroupTable.GROUPTEXT_FLD].ToString().Trim(); objObject.GroupTextVN = odrPCS[Sys_VisibilityGroupTable.GROUPTEXTVN_FLD].ToString().Trim(); objObject.GroupTextJP = odrPCS[Sys_VisibilityGroupTable.GROUPTEXTJP_FLD].ToString().Trim(); objObject.Type = int.Parse(odrPCS[Sys_VisibilityGroupTable.TYPE_FLD].ToString().Trim()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to Sys_VisibilityGroup /// </Description> /// <Inputs> /// Sys_VisibilityGroupVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_VisibilityGroupVO objObject = (Sys_VisibilityGroupVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_VisibilityGroup SET " + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "= ?" + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "= ?" + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "= ?" + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "= ?" + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "= ?" + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "= ?" + "," + Sys_VisibilityGroupTable.TYPE_FLD + "= ?" +" WHERE " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.CONTROLNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.CONTROLNAME_FLD].Value = objObject.ControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.PARENTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.PARENTID_FLD].Value = objObject.ParentID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.FORMNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.FORMNAME_FLD].Value = objObject.FormName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXT_FLD].Value = objObject.GroupText; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTVN_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTVN_FLD].Value = objObject.GroupTextVN; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTJP_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTJP_FLD].Value = objObject.GroupTextJP; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.TYPE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.TYPE_FLD].Value = objObject.Type; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD].Value = objObject.VisibilityGroupID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from Sys_VisibilityGroup /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, October 18, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "," + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + "ISNULL(" + Sys_VisibilityGroupTable.PARENTID_FLD + ",0) PARENTID," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + " FROM " + Sys_VisibilityGroupTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); //odadPCS.FillSchema() odadPCS.Fill(dstPCS,Sys_VisibilityGroupTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, October 18, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "," + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + " FROM " + Sys_VisibilityGroupTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,Sys_VisibilityGroupTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, October 18, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSetRoleAndItem(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_VisibilityItemTable.VISIBILITYITEMID_FLD + "," + Sys_VisibilityItemTable.NAME_FLD + "," + Sys_VisibilityItemTable.GROUPID_FLD + "," + Sys_VisibilityItemTable.TYPE_FLD + " FROM " + Sys_VisibilityItemTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityItemTable.TABLE_NAME]); pData.Tables[Sys_VisibilityItemTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityItemTable.TABLE_NAME]); strSql= "SELECT " + Sys_VisibilityGroup_RoleTable.VISIBILITYGROUP_ROLEID_FLD + "," + Sys_VisibilityGroup_RoleTable.GROUPID_FLD + "," + Sys_VisibilityGroup_RoleTable.ROLEID_FLD + " FROM " + Sys_VisibilityGroup_RoleTable.TABLE_NAME; odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME]); pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME]); strSql= "SELECT " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "," + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + " FROM " + Sys_VisibilityGroupTable.TABLE_NAME; odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME]); pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME]); pData.AcceptChanges(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int AddAndReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddAndReturnID()"; int intID; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_VisibilityGroupVO objObject = (Sys_VisibilityGroupVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_VisibilityGroup(" + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + ")" + "VALUES(?,?,?,?,?,?,?) " + "SELECT @@IDENTITY"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.CONTROLNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.CONTROLNAME_FLD].Value = objObject.ControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.PARENTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.PARENTID_FLD].Value = objObject.ParentID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.FORMNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.FORMNAME_FLD].Value = objObject.FormName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXT_FLD].Value = objObject.GroupText; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTVN_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTVN_FLD].Value = objObject.GroupTextVN; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.GROUPTEXTJP_FLD, OleDbType.WChar)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.GROUPTEXTJP_FLD].Value = objObject.GroupTextJP; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibilityGroupTable.TYPE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibilityGroupTable.TYPE_FLD].Value = objObject.Type; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); intID = Convert.ToInt32(ocmdPCS.ExecuteScalar().ToString()); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } return intID; } public void UpdateAllDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_VisibilityGroupTable.VISIBILITYGROUPID_FLD + "," + Sys_VisibilityGroupTable.CONTROLNAME_FLD + "," + Sys_VisibilityGroupTable.PARENTID_FLD + "," + Sys_VisibilityGroupTable.FORMNAME_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXT_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTVN_FLD + "," + Sys_VisibilityGroupTable.GROUPTEXTJP_FLD + "," + Sys_VisibilityGroupTable.TYPE_FLD + " FROM " + Sys_VisibilityGroupTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME]); pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityGroupTable.TABLE_NAME]); strSql= "SELECT " + Sys_VisibilityItemTable.VISIBILITYITEMID_FLD + "," + Sys_VisibilityItemTable.NAME_FLD + "," + Sys_VisibilityItemTable.GROUPID_FLD + "," + Sys_VisibilityItemTable.TYPE_FLD + " FROM " + Sys_VisibilityItemTable.TABLE_NAME; odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityItemTable.TABLE_NAME]); pData.Tables[Sys_VisibilityItemTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityItemTable.TABLE_NAME]); strSql= "SELECT " + Sys_VisibilityGroup_RoleTable.VISIBILITYGROUP_ROLEID_FLD + "," + Sys_VisibilityGroup_RoleTable.GROUPID_FLD + "," + Sys_VisibilityGroup_RoleTable.ROLEID_FLD + " FROM " + Sys_VisibilityGroup_RoleTable.TABLE_NAME; odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = true; odadPCS.Update(pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME]); pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME].Clear(); odadPCS.Fill(pData.Tables[Sys_VisibilityGroup_RoleTable.TABLE_NAME]); pData.AcceptChanges(); } // catch(OleDbException ex) // { // if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) // { // throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); // } // else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) // { // // throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); // } // // else // { // throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); // } // } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get hidden control /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// sonht /// </Authors> /// <History> /// Wednesday, April 12, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable GetVisibleControl(string pstrFormName,string pstrControlName,string[] pstrRoleIDs) { const string METHOD_NAME = THIS + ".GetHiddenControl()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; string strRoleIDs = string.Empty; for(int i = 0; i < pstrRoleIDs.Length; i++) { strRoleIDs += pstrRoleIDs[i] + ","; } strRoleIDs = strRoleIDs.Substring(0,strRoleIDs.Length - 1); // strSql= "SELECT VC." + Sys_VisibleControlTable.FORMNAME_FLD + ", VC." // + Sys_VisibleControlTable.CONTROLNAME_FLD + ", VC." // + Sys_VisibleControlTable.SUBCONTROLNAME_FLD // + " FROM " + Sys_Role_ControlGroupTable.TABLE_NAME + " RCG" // + " INNER JOIN " + Sys_ControlGroupTable.TABLE_NAME + " CG" // + " ON RCG." + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + "=" + " CG." + Sys_ControlGroupTable.CONTROLGROUPID_FLD // + " INNER JOIN " + Sys_VisibleControlTable.TABLE_NAME + " VC" // + " ON CG." + Sys_ControlGroupTable.CONTROLGROUPID_FLD + "=" + " VC." + Sys_ControlGroupTable.CONTROLGROUPID_FLD // + " WHERE VC." + Sys_VisibleControlTable.FORMNAME_FLD + "='" + pstrFormName + "'" // + " AND RCG." + Sys_Role_ControlGroupTable.ROLEID_FLD + " IN (" + strRoleIDs + ")"; strSql = "SELECT VG.FormName,VI.Name ControlName, ISNULL(VI.Type,0) Type" + " FROM sys_VisibilityGroup_Role VGR" + " INNER JOIN sys_VisibilityGroup VG ON VGR.GroupID=VG.VisibilityGroupID" + " INNER JOIN sys_VisibilityItem VI ON VG.VisibilityGroupID=VI.GroupID" + " WHERE VG.FormName = '" + pstrFormName + "'" + " AND VGR.RoleID IN (" + strRoleIDs + ")"; if(pstrControlName != string.Empty) { strSql += " AND VI.Name = '" + pstrControlName + "'"; } // HACK: SonHT 2005-11-08 if(pstrFormName != string.Empty) { strSql += " AND VG.FormName = '" + pstrFormName + "'"; } strSql += " ORDER BY VG.FormName, VI.Name"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_VisibleControlTable.TABLE_NAME); return dstPCS.Tables[0]; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; namespace MooGet { public class MissingDependencyException : Exception { public List<PackageDependency> Dependencies { get; set; } public MissingDependencyException(List<PackageDependency> missingDependencies) : base("No packages were found that satisfy these dependencies: " + string.Join(", ", missingDependencies.Select(dep => dep.ToString()).ToArray())) { Dependencies = new List<PackageDependency>(missingDependencies); } } /// <summary>Represents a Package Id and Version(s) that a Package depends on</summary> public class PackageDependency { string _rawVersionText; List<VersionAndOperator> _versions = new List<VersionAndOperator>(); public PackageDependency() {} public PackageDependency(string nameAndVersions) { var parts = new List<string>(nameAndVersions.Trim().Split(' ')); if (parts.Count > 0) { PackageId = parts.First().Trim(); parts.RemoveAt(0); } if (parts.Count > 0) if (parts.Count == 1 && ! Regex.IsMatch(parts.First(), "[=><~]")) VersionText = "=" + parts.First(); else VersionText = string.Join(" ", parts.ToArray()); } public List<VersionAndOperator> Versions { get { return _versions; } set { _versions = value; } } /// <summary>The Id of the Package this dependency is for</summary> public string PackageId { get; set; } /// <summary>Alias for PackageId</summary> public string Id { get { return PackageId; } set { PackageId = value; } } public bool Matches(IPackage package) { if (package.Id != Id) return false; else return (Versions.Count > 0) ? Matches(package.Version) : true; } public bool Matches(string version) { return Matches(new PackageVersion(version)); } public bool Matches(PackageVersion version) { foreach (var versionDependency in Versions) if (! versionDependency.Matches(version)) return false; return true; } public static bool MatchesAll(string version, params PackageDependency[] dependencies) { return MatchesAll(new PackageVersion(version), dependencies); } public static bool MatchesAll(IPackage package, params PackageDependency[] dependencies) { foreach (var dependency in dependencies) if (! dependency.Matches(package)) return false; return true; } public static bool MatchesAll(PackageVersion version, params PackageDependency[] dependencies) { foreach (var dependency in dependencies) if (! dependency.Matches(version)) return false; return true; } /// <summary>String representation of this PackageDependency showing the PackageId and all Versions</summary> public override string ToString() { return string.Format("{0} {1}", PackageId, VersionsString).Trim(); } public string VersionsString { get { return string.Join(" ", Versions.Select(v => v.ToString()).ToArray()).Trim(); } } public static bool operator != (PackageDependency a, PackageDependency b) { return ! (a == b); } public static bool operator == (PackageDependency a, PackageDependency b) { if ((object) b == null) return ((object) a == null); else return a.Equals(b); } public override bool Equals(object o) { if (o == null) return false; if (this.GetType() != o.GetType()) return false; return this.ToString() == ((PackageDependency) o).ToString(); } /// <summary>Version string can be a specific version (eg. 1.0) or a matcher (eg. &gt;= 1.0)</summary> /// <remarks> /// Setting the VersionText to something like "&gt;=1.0" will parse the string and set MinVersion. /// /// Getting the VersionText returns the raw string that was set, eg. "&gt;=1.0" /// </remarks> public string VersionText { get { return _rawVersionText; } set { _rawVersionText = value; Parse(); } } /// <summary>Represents an *exact* version for this dependency, eg. 1.0</summary> public PackageVersion Version { get { var versionOperator = Versions.FirstOrDefault(v => v.Operator == Operators.EqualTo); return (versionOperator == null) ? null : versionOperator.Version; } set { AddVersion("=", value.ToString()); } } /// <summary>Represents an *exact* minumum version for this dependency, eg. 1.0</summary> public PackageVersion MinVersion { get { var versionOperator = Versions.FirstOrDefault(v => v.Operator == Operators.GreaterThanOrEqualTo); return (versionOperator == null) ? null : versionOperator.Version; } set { AddVersion(">=", value.ToString()); } } /// <summary>Represents an *exact* "sorta" minumum version for this dependency, eg. 1.0</summary> /// <remarks> /// If you set the VersionText to "~&gt;1.1.0" or "~&gt;1.1" that sets the SortaMinVersion to /// 1.1.0 or 1.1. /// /// Wheat does that mean? /// /// If the SortaMinVersion is 1.1 or 1.1.0, that says that this dependency can install any version /// of this package greater than or equal to 1.1.0 BUT less than 1.2. It will not install the next /// "minor" version of this package, but will allow for the installation of additional builds/revisions. /// </remarks> public PackageVersion SortaMinVersion { get { var versionOperator = Versions.FirstOrDefault(v => v.Operator == Operators.SortaGreaterThan); return (versionOperator == null) ? null : versionOperator.Version; } set { AddVersion("~>", value.ToString()); } } /// <summary>Represents an *exact* maximum version for this dependency, eg. 1.0</summary> public PackageVersion MaxVersion { get { var versionOperator = Versions.FirstOrDefault(v => v.Operator == Operators.LessThanOrEqualTo); return (versionOperator == null) ? null : versionOperator.Version; } set { AddVersion("<=", value.ToString()); } } /// <summary>Get or set string representing the *exact* MinVersion, eg. 1.0</summary> public string MinVersionText { get { if (MinVersion == null) return null; return MinVersion.ToString(); } set { MinVersion = new PackageVersion(value); } } /// <summary>Get or set string representing the *exact* SortaMinVersion, eg. 1.0</summary> public string SortaMinVersionText { get { if (SortaMinVersion == null) return null; return SortaMinVersion.ToString(); } set { SortaMinVersion = new PackageVersion(value); } } /// <summary>Get or set string representing the *exact* MaxVersion, eg. 1.0</summary> public string MaxVersionText { get { if (MaxVersion == null) return null; return MaxVersion.ToString(); } set { MaxVersion = new PackageVersion(value); } } // parses the VersionText // // NOTE do *NOT* set VersionText from this method, or you'll end up in an infinite loop! void Parse() { if (VersionText == null) return; // Parse all groups of (>=~<) operators followed by version numbers (1.2.3.4) foreach (Match match in Regex.Matches(VersionText, @"([><=~]+)\s*([\d\.]+)")) AddVersion(match.Groups[1].Value, match.Groups[2].Value); // If no matchers were found, no operator was provided (eg. "1.2") so we say that we must be equal to this version if (Versions.Count == 0) AddVersion("=", VersionText); } void AddVersion(string operatorString, string version) { Versions.Add(new VersionAndOperator { OperatorString = operatorString, VersionText = version }); } public static Operators ParseOperator(string op) { if (op == null) return Operators.EqualTo; op = op.Trim().Replace(" ",""); if (op.Contains(">")) if (op.Contains("=")) return Operators.GreaterThanOrEqualTo; else if (op.Contains("~")) return Operators.SortaGreaterThan; else return Operators.GreaterThan; else if (op.Contains("<")) if (op.Contains("=")) return Operators.LessThanOrEqualTo; else if (op.Contains("~")) return Operators.SortaLessThan; else return Operators.LessThan; else return Operators.EqualTo; } public static string GetOperatorString(Operators op) { switch (op) { case Operators.EqualTo: return "="; break; case Operators.GreaterThan: return ">"; break; case Operators.GreaterThanOrEqualTo: return ">="; break; case Operators.SortaGreaterThan: return "~>"; break; case Operators.LessThan: return "<"; break; case Operators.LessThanOrEqualTo: return "<="; break; case Operators.SortaLessThan: return "<~"; break; } return null; } public enum Operators { EqualTo, GreaterThan, GreaterThanOrEqualTo, SortaGreaterThan, LessThan, LessThanOrEqualTo, SortaLessThan }; /// <summary>Represents a paired Version string (eg. 1.0) and Operator (eg. GreaterThan)</summary> public class VersionAndOperator { public PackageVersion Version { get; set; } public Operators Operator { get; set; } public string VersionText { get { if (Version == null) return null; return Version.ToString(); } set { Version = new PackageVersion(value); } } public string OperatorString { get { return PackageDependency.GetOperatorString(Operator); } set { Operator = PackageDependency.ParseOperator(value); } } public override string ToString() { return string.Format("{0} {1}", PackageDependency.GetOperatorString(Operator), Version); } public bool Matches(string version) { return Matches(new PackageVersion(version)); } public bool Matches(PackageVersion version) { switch (Operator) { case Operators.EqualTo: return version == Version; case Operators.LessThan: return version < Version; case Operators.LessThanOrEqualTo: return version <= Version; case Operators.SortaLessThan: return version.SortaLessThan(Version); case Operators.GreaterThan: return version > Version; case Operators.GreaterThanOrEqualTo: return version >= Version; case Operators.SortaGreaterThan: return version.SortaGreaterThan(Version); default: throw new Exception("Unknown operator: " + Operator.ToString()); } } } } }
// 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.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Notes about TaiwanLunisolarCalendar // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/02/18 2051/02/10 ** TaiwanLunisolar 1912/01/01 2050/13/29 */ [Serializable] public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1912; internal const int MAX_LUNISOLAR_YEAR = 2050; internal const int MIN_GREGORIAN_YEAR = 1912; internal const int MIN_GREGORIAN_MONTH = 2; internal const int MIN_GREGORIAN_DAY = 18; internal const int MAX_GREGORIAN_YEAR = 2051; internal const int MAX_GREGORIAN_MONTH = 2; internal const int MAX_GREGORIAN_DAY = 10; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1911 from ChineseLunisolarCalendar return 384; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */}; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (taiwanLunisolarEraInfo); } } internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MIN_LUNISOLAR_YEAR) || (lunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.TAIWAN); } } internal override CalendarId ID { get { return (CalendarId.TAIWANLUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
// SqlLiteDatabaseTest.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using NUnit.Framework; using System; using System.Collections.Generic; using database; using Layout.data; using CoreUtilities; using Layout; namespace Testing { [TestFixture()] public class SqlLiteDatabaseTest { public SqlLiteDatabaseTest() { } #region SetupFunctions const string test_database_name ="UNITTESTING.s3db"; private FAKE_SqlLiteDatabase CreateTestDatabase (string primarykey) { FAKE_SqlLiteDatabase db = new FAKE_SqlLiteDatabase (test_database_name); try { // There was a lock on deleting the database but I realized that the call to new would // clear the database if paired with a delete? // We have to clear memory when deleting because the database might be lingering //GC.Collect(); //System.IO.File.Delete (test_database_name); } catch (Exception ex) { _w.output ("Unable to delete file " + ex.ToString ()); } try { db.DropTableIfExists(dbConstants.table_name); } catch (Exception ex) { _w.output (String.Format ("Unable to drop table {0}", ex.ToString())); } db.CreateTableIfDoesNotExist (dbConstants.table_name, new string[6] {dbConstants.ID, dbConstants.GUID, dbConstants.XML, dbConstants.STATUS, dbConstants.NAME, dbConstants.SUBPANEL}, new string[6] { "INTEGER", "TEXT UNIQUE", "LONGTEXT", "TEXT","TEXT","BOOLEAN" }, primarykey ); return db; } #endregion #region basedatabase [Test()] public void ColumnArrayToStringForInserting() { FAKE_SqlLiteDatabase test = new FAKE_SqlLiteDatabase("nUnitTest"); string columns = test.TestColumnArrayToStringForInserting(new string[3] {"dog", "cat", "fish"}); //Console.WriteLine(columns); Assert.AreEqual(columns, "dog,cat,fish"); } #endregion #region insert /// <summary> /// Addings to unique column. /// /// TEST: We are prevented from adding two columns with the same unique field /// </summary> [Test()] [ExpectedException] public void AddingToUniqueColumn () { // Create a test database FAKE_SqlLiteDatabase db = CreateTestDatabase (String.Format ("{0}", dbConstants.GUID)); Console.WriteLine ("First insert should work"); if (db.Exists ("boo", dbConstants.XML, "z")) { }; db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); Console.WriteLine("inserting a unique GUID_B is okay"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_B"}); Console.WriteLine("Second insert should fail "); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); } #endregion #region AddMissingColumns [Test()] public void AddMissingColumn_Test_ColumnDidNotExistAndWeDetectedItCorrectly() { // Create a test database FAKE_SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.ID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); _w.output(db.BackupDatabase()); // add ColumnA to it bool result = db.TestAddMissingColumn(dbConstants.table_name, new string[1] {"boomer"}, new string[1] {"TEXT"}); // check return value is true Assert.True(result); _w.output(db.BackupDatabase()); // add ColumnA to it again. This time return value should be false (because we did not need to add the column) result = db.TestAddMissingColumn(dbConstants.table_name, new string[1] {"boomer"}, new string[1] {"TEXT"}); Console.WriteLine ("Result #2 = " + result); Assert.False (result); } [Test()] [ExpectedException] public void AddMissingColumn_ListOfColumnsNotEqualToListOfTypes() { // Create a test database FAKE_SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.ID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); bool result = db.TestAddMissingColumn(dbConstants.table_name, new string[2] {"boomer","poob"}, new string[1] {"TEXT"}); } #endregion #region TableExists [Test] public void TableDoesExist () { FAKE_SqlLiteDatabase db = new FAKE_SqlLiteDatabase (test_database_name); db.DropTableIfExists(dbConstants.table_name); _w.output ("here1"); Assert.False (db.TableExists (dbConstants.table_name)); _w.output ("here"); CreateTestDatabase (String.Format ("{0}", dbConstants.ID)); _w.output ("here"); try { db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); Assert.True (db.TableExists (dbConstants.table_name)); } catch (Exception) { } } [Test] public void DropTableTest () { FAKE_SqlLiteDatabase db = CreateTestDatabase (String.Format ("{0}", dbConstants.ID)); _w.output ("here"); try { db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); Assert.True (db.TableExists (dbConstants.table_name)); db.DropTableIfExists (dbConstants.table_name); Assert.True (db.TableExists (dbConstants.table_name)); } catch (Exception) { } } #endregion #region Exists (NOT DONE) /// <summary> /// Tests that we detect CORRECTLY that a GUID IS present in the database /// </summary> [Test()] public void GuidDoesExist () { _w.output ("GUIDDOESEXIST"); bool result = false; _w.output ("here1"); // Create a test database FAKE_SqlLiteDatabase db = CreateTestDatabase (String.Format ("{0}", dbConstants.ID)); _w.output ("here"); try { db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); result = db.TestAddMissingColumn (dbConstants.table_name, new string[1] {"boomer"}, new string[1] {"TEXT"}); } catch (Exception ex) { _w.output(ex.ToString ()); } _w.output ("here"); Assert.True (db.Exists(dbConstants.table_name, dbConstants.GUID, "GUID_A")); _w.output (result); } [Test()] public void GuidDoesNotExist() { // Create a test database FAKE_SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.ID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); bool result = db.TestAddMissingColumn(dbConstants.table_name, new string[1] {"boomer"}, new string[1] {"TEXT"}); Console.WriteLine ("GuidDoesNotExist"); Assert.False (db.Exists(dbConstants.table_name, dbConstants.GUID, "GUID_B")); } #endregion #region GetValues (NOT DONE) [Test] public void GetMultipleRowsWhenMultipleRowsMatch () { _w.output ("**Get data Test**"); SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xml", "GUID_A"}); _w.output("first roww"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS, dbConstants.XML, dbConstants.GUID } , new object[3] {"boo status", "boo xmlB", "GUID_B"}); System.Collections.Generic.List<object[]> results = db.GetValues (dbConstants.table_name, new string[1] { dbConstants.GUID }, dbConstants.STATUS, "boo status"); int count = 0; if (results != null) { foreach (object[] o in results) { count++; foreach (object oo in o) { Console.WriteLine (oo.ToString ()); } } } Console.WriteLine(count); Assert.AreEqual(count,2); /*// need to find 2 rows if (2 == count) { Console.WriteLine ("success"); } else { Console.WriteLine(count + " rows found instead of 2"); Assert.True(false); }*/ } [Test()] [ExpectedException] public void GetText_NoTable() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues("", new string[1]{"irrelevant"}, dbConstants.GUID, "GUID_A"); } [Test()] [ExpectedException] public void GetText_NoGetColumn() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues(dbConstants.table_name, new string[1]{""}, dbConstants.GUID, "GUID_A"); } [Test()] [ExpectedException] public void GetText_GetColumnIsNull() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues(dbConstants.table_name, new string[1]{""}, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] [ExpectedException] public void GetText_NoTestColumn() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, "", "GUID_A"); db.Dispose(); } [Test()] public void GetText_TestShouldHaveNoProblems() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] [ExpectedException] public void GetText_NoTestValue() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, ""); db.Dispose(); } [Test()] //[ExpectedException] public void GetText_ReturnColumnDoesNotExists() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); // db.GetValues(tmpDatabaseConstants.table_name, new string[1]{"booboo"}, tmpDatabaseConstants.GUID, "GUID_A"); // just trying another way to structure the test. see http://nunit.net/blogs/?p=63 Assert.That (delegate {db.GetValues(dbConstants.table_name, new string[1]{"booboo"}, dbConstants.GUID, "GUID_A"); },Throws.Exception ); db.Dispose(); } /// <summary> /// table has no rows in it? /// Return a blank /// </summary> [Test()] public void BlankTable_GetValues () { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); //db.InsertData (tmpDatabaseConstants.table_name, new string[3] { tmpDatabaseConstants.STATUS,tmpDatabaseConstants.XML,tmpDatabaseConstants.GUID //}, new object[3] {"boo status", "boo xml", "GUID_A"}); Assert.True (db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A").Count== 0); //Assert.That (delegate {db.GetValues(tmpDatabaseConstants.table_name, new string[1]{"a"}, tmpDatabaseConstants.GUID, "GUID_A"); },Throws.Exception ); //Assert.Throws(typeof(Exception), db.GetValues(tmpDatabaseConstants.table_name, new string[1]{"a"}, tmpDatabaseConstants.GUID, "a")); db.Dispose(); } [Test()] public void GetText_ExpectBlankString() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); System.Collections.Generic.List<object[]> list = db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_B"); // expect an empty list Assert.AreEqual(list.Count, 0); //Assert.IsNull(list); db.Dispose(); } [Test()] public void GetText_ExpectExactResult() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); System.Collections.Generic.List<object[]> list = db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A"); _w.output (list[0][0].ToString()); if (list == null) Assert.True (false); Assert.AreEqual(list[0][0].ToString(), "boo status"); db.Dispose(); } [Test] public void GetText_MultipleRowsExactMatch() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); _w.output("database made"); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_B"}); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_C"}); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status2", "boo xml", "GUID_D"}); System.Collections.Generic.List<object[]> list = db.GetValues(dbConstants.table_name, new string[1]{dbConstants.GUID}, dbConstants.STATUS, "boo status"); _w.output (list.Count); Assert.AreEqual (3, list.Count); db.Dispose(); } /*if (CoreUtilities.Constants.BLANK == tableName) { throw new Exception("You must provide a table to query"); } if (CoreUtilities.Constants.BLANK == Test || CoreUtilities.Constants.BLANK == columnToTest) { throw new Exception ("Must define a Test criteria for retrieving text"); } if (columnToReturn == null || columnToReturn.Length <= 0) { throw new Exception("At least one column is required, to know what you want from the database."); }*/ #endregion #region general /// <summary> /// Should test with at least 3 tables /// </summary> [Test()] public void CreateFakeDatabaseAndBackup() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status2", "boo xml2", "GUID_A2"}); db.Dispose(); db = new FAKE_SqlLiteDatabase (test_database_name); try { db.DropTableIfExists(dbConstants.table_name+"_b"); } catch (Exception ex) { _w.output (String.Format ("Unable to drop table {0}", ex.ToString())); } db.CreateTableIfDoesNotExist (dbConstants.table_name+"_b", new string[4] {dbConstants.ID, dbConstants.GUID, dbConstants.XML, dbConstants.STATUS}, new string[4] { "INTEGER", "TEXT UNIQUE", "LONGTEXT", "TEXT" }, dbConstants.GUID ); db.InsertData (dbConstants.table_name+"_b", new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_B"}); db.Dispose(); db = new FAKE_SqlLiteDatabase (test_database_name); try { db.DropTableIfExists(dbConstants.table_name+"_c"); } catch (Exception ex) { _w.output (String.Format ("Unable to drop table {0}", ex.ToString())); } db.CreateTableIfDoesNotExist (dbConstants.table_name+"_c", new string[4] {dbConstants.ID, dbConstants.GUID, dbConstants.XML, dbConstants.STATUS}, new string[4] { "INTEGER", "TEXT UNIQUE", "LONGTEXT", "TEXT" }, dbConstants.GUID ); db.InsertData (dbConstants.table_name+"_c", new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_C"}); // get rid of full text database too db.DropTableIfExists("fulltextsearch"); //not sure how to set this test up. Force File Write? Then test if file exists? // or shoudl this return a Stream? string result = db.BackupDatabase(); _w.output(result.Length); _w.output(result); db.DropTableIfExists(dbConstants.table_name+"_b"); db.DropTableIfExists(dbConstants.table_name+"_c"); db.Dispose(); Assert.AreEqual(526, result.Length); //Assert.False (true); } /// <summary> /// If a primary key is not specified then it should throw an exception /// </summary> [Test()] [ExpectedException] public void CreateTableWithNoPrimaryKey() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", "")); db.Dispose(); } /// <summary> /// Should be no problems if creating two tables one after another, if they are the same table /// </summary> [Test()] public void CreateTableIfDoesNotExist_Test() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); } [Test()] [ExpectedException] public void Test_FailOnInvalidDatabaseName() { FAKE_SqlLiteDatabase db = new FAKE_SqlLiteDatabase (""); db.Dispose(); } [Test()] public void DatabaseIsDisposed() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.Dispose(); Assert.That (delegate {db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A"); }, Throws.Exception ); } [Test()] [ExpectedException] public void CreateTableIfDoesNotExist_CreateUnevenTable() { FAKE_SqlLiteDatabase db = new FAKE_SqlLiteDatabase (test_database_name); try { db.DropTableIfExists(dbConstants.table_name); } catch (Exception ex) { _w.output (String.Format ("Unable to drop table {0}", ex.ToString())); } db.CreateTableIfDoesNotExist (dbConstants.table_name, new string[4] {dbConstants.ID, dbConstants.GUID, dbConstants.XML, dbConstants.STATUS}, new string[3] { "INTEGER", "TEXT UNIQUE", "LONGTEXT" }, dbConstants.GUID ); db.Dispose(); } #endregion #region update /// <summary> /// Nothing should be updated if entered the wrong GUID to update (and it shoudl return false) /// </summary> [Test()] public void RowDoesNotExistOnUpdate() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); // we fail to update Assert.AreEqual(false, db.UpdateSpecificColumnData(dbConstants.table_name, new string[1] {dbConstants.STATUS}, new object[1] {"snakes!"}, dbConstants.GUID, "GUID_B")); // there is a problem with updating specific column data AND not having the right GUID. Crashes rest of unit tests Assert.AreEqual("boo status", db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A")[0][0].ToString()); db.Dispose(); } [Test()] [ExpectedException] public void UpdateSpecificColumnData_FailsWhenUnevenColumns() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name, new string[2] {dbConstants.XML, dbConstants.STATUS}, new object[1] {"snakes!"}, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] public void UpdateDataWorks () { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name, new string[1] {dbConstants.STATUS}, new object[1] {"snakes!"}, dbConstants.GUID, "GUID_A"); Assert.AreEqual("snakes!", db.GetValues(dbConstants.table_name, new string[1]{dbConstants.STATUS}, dbConstants.GUID, "GUID_A")[0][0].ToString()); db.Dispose(); } [Test()] [ExpectedException()] public void UpdateInvalidTable() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData("", new string[1] {dbConstants.STATUS}, new object[1] {"snakes!"}, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] [ExpectedException()] public void UpdateNullColumns() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name,null, new object[1] {"snakes!"}, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] [ExpectedException()] public void UpdateNullValues() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name, new string[1] {dbConstants.STATUS}, null, dbConstants.GUID, "GUID_A"); db.Dispose(); } [Test()] [ExpectedException()] public void UpdateEmptyWhereColumn() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name, new string[1] {dbConstants.STATUS}, new object[1] {"snakes!"}, "", "GUID_A"); db.Dispose(); } [Test()] [ExpectedException()] public void UpdateEmptyWhereValue() { SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); db.InsertData (dbConstants.table_name, new string[3] { dbConstants.STATUS,dbConstants.XML,dbConstants.GUID }, new object[3] {"boo status", "boo xml", "GUID_A"}); db.UpdateSpecificColumnData(dbConstants.table_name, new string[1] {dbConstants.STATUS}, new object[1] {"snakes!"}, dbConstants.GUID, ""); db.Dispose(); } #endregion #region sorting [Test()] public void TestSortingOnGetValues () { Layout.LayoutDetails.Instance.YOM_DATABASE =test_database_name; SqlLiteDatabase db = CreateTestDatabase (String.Format ("{0}", dbConstants.ID)); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Zum", "boo xml", "GUID_DDA",0}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Alexander", "boo xml", "GUID_B",0}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"aboo", "boo xml", "GUID_A",0}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Calv", "boo xml", "GUID_C",0}); // Layout.MasterOfLayouts mastery = new Layout.MasterOfLayouts (); List<Layout.MasterOfLayouts.NameAndGuid> list = MasterOfLayouts.GetListOfLayouts (Constants.BLANK); foreach (Layout.MasterOfLayouts.NameAndGuid guid in list) { _w.output (guid.Caption); } Assert.AreEqual(4, list.Count); Assert.AreEqual ("aboo", list[0].Caption); Assert.AreEqual ("Alexander", list[1].Caption); Assert.AreEqual ("Calv", list[2].Caption); Assert.AreEqual ("Zum", list[3].Caption); //mastery.Dispose (); db.Dispose(); } [Test()] public void TestSortingOnGetValues_ShouldFailBecauseAreSubPanels () { Layout.LayoutDetails.Instance.YOM_DATABASE =test_database_name; SqlLiteDatabase db = CreateTestDatabase (String.Format ("{0}", dbConstants.ID)); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Zum", "boo xml", "GUID_DDA",1}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Alexander", "boo xml", "GUID_B",1}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"aboo", "boo xml", "GUID_A",1}); db.InsertData (dbConstants.table_name, new string[4] { dbConstants.NAME,dbConstants.XML,dbConstants.GUID, dbConstants.SUBPANEL }, new object[4] {"Calv", "boo xml", "GUID_C",1}); // Layout.MasterOfLayouts mastery = new Layout.MasterOfLayouts (); List<Layout.MasterOfLayouts.NameAndGuid> list = MasterOfLayouts.GetListOfLayouts (Constants.BLANK); foreach (Layout.MasterOfLayouts.NameAndGuid guid in list) { _w.output (guid.Caption); } Assert.AreEqual(0, list.Count); /*Assert.AreEqual ("aboo", list[0].Caption); Assert.AreEqual ("Alexander", list[1].Caption); Assert.AreEqual ("Calv", list[2].Caption); Assert.AreEqual ("Zum", list[3].Caption); */ // mastery.Dispose (); db.Dispose(); } #endregion // [Test] - Removed this, won't be using FullTextSearch unless I REALLY need it. Just using standard search seems sufficient. // public void TestFullTextSearch() // { // Assert.True (false); // // This test seems to cause mdhost.exe crashes!?!? Wasn't finished anyways so aborted it // return; // // FAKE_SqlLiteDatabase db =CreateTestDatabase(String.Format ("{0}", dbConstants.GUID)); // db.DropTableIfExists("fulltextsearch"); // db.CreateFullSearchDatabase(); // db.InsertData("fulltextsearch", new string[1] {"texttosearch"}, new object[1] {"blah blah hello there"}); // db.InsertData("fulltextsearch", new string[1] {"texttosearch"}, new object[1] {"blah blah fish hello there"}); // db.InsertData("fulltextsearch", new string[1] {"texttosearch"}, new object[1] {"blah blah hello there"}); // db.InsertData("fulltextsearch", new string[1] {"texttosearch"}, new object[1] {"blah blah dog fish hello there"}); // _w.output("now search"); // db.SearchFullSearchDatabase (); // _w.output("now search over"); // Console.WriteLine (db.BackupDatabase()); // db.Dispose(); // Assert.True (false); // } } }
using System; using System.Collections.Generic; using NSubstitute.Exceptions; using NUnit.Framework; namespace NSubstitute.Acceptance.Specs { public class FormattingCallsWhenThrowingReceivedCallsExceptions { public interface ISample { void SampleMethod(); void SampleMethod(int i); void SampleMethod(string s, int i, IList<string> strings); void AnotherMethod(IList<string> strings); int AProperty { get; set; } int this[string a, string b] { get; set; } void ParamsMethod(int a, params string[] strings); } public class When_no_calls_are_made_to_the_expected_member : Context { protected override void ConfigureContext() { Sample.AnotherMethod(new List<string>()); Sample.AnotherMethod(new List<string>()); } protected override void ExpectedCall() { Sample.Received().SampleMethod(5); } [Test] public void Should_report_the_method_we_were_expecting() { ExceptionMessageContains(ExpectedCallMessagePrefix + "SampleMethod(5)"); } } public class When_calls_have_been_made_to_expected_member_but_with_different_arg : Context { protected override void ConfigureContext() { Sample.SampleMethod(1); Sample.SampleMethod(2); } protected override void ExpectedCall() { Sample.Received().SampleMethod(5); } [Test] public void Should_report_the_method_we_were_expecting() { ExceptionMessageContains(ExpectedCallMessagePrefix + "SampleMethod(5)"); } [Test] public void Should_report_non_matching_calls() { ExceptionMessageContains("Received 2 non-matching calls (non-matching arguments indicated with '*' characters):"); ExceptionMessageContains("SampleMethod(*1*)"); ExceptionMessageContains("SampleMethod(*2*)"); } } public class When_calls_have_been_made_to_expected_member_but_with_some_different_args : Context { readonly IList<string> _strings = new List<string> { "a", "b" }; protected override void ConfigureContext() { Sample.SampleMethod("different", 1, new List<string>()); Sample.SampleMethod("string", 7, new List<string>()); } protected override void ExpectedCall() { Sample.Received().SampleMethod("string", 1, _strings); } [Test] public void Should_report_the_method_we_were_expecting() { ExceptionMessageContains(ExpectedCallMessagePrefix + "SampleMethod(\"string\", 1, List<String>)"); } [Test] public void Should_indicate_which_args_are_different() { ExceptionMessageContains("SampleMethod(*\"different\"*, 1, *List<String>*)"); ExceptionMessageContains("SampleMethod(\"string\", *7*, *List<String>*)"); } } public class When_not_enough_matching_calls_were_made_to_a_method : Context { protected override void ConfigureContext() { Sample.SampleMethod(1); Sample.SampleMethod(2); } protected override void ExpectedCall() { Sample.Received(2).SampleMethod(2); } [Test] public void Should_show_expected_call() { ExceptionMessageContains("Expected to receive exactly 2 calls matching:\n\t" + "SampleMethod(2)"); } [Test] public void Should_list_matching_calls() { ExceptionMessageContains("Actually received 1 matching call:\r\n\t" + "SampleMethod(2)"); } [Test] public void Should_list_actual_related_calls() { ExceptionMessageContains("Received 1 non-matching call (non-matching arguments indicated with '*' characters):\r\n\t" + "SampleMethod(*1*)"); } } public class When_too_many_matching_calls_were_made_to_a_method : Context { protected override void ConfigureContext() { Sample.SampleMethod(1); Sample.SampleMethod(2); Sample.SampleMethod(2); Sample.SampleMethod(2); } protected override void ExpectedCall() { Sample.Received(2).SampleMethod(2); } [Test] public void Should_show_expected_call() { ExceptionMessageContains("Expected to receive exactly 2 calls matching:\n\t" + "SampleMethod(2)"); } [Test] public void Should_list_matching_calls() { ExceptionMessageContains("Actually received 3 matching calls:\r\n\t" + "SampleMethod(2)"); } [Test] public void Should_not_list_non_matching_calls() { ExceptionMessageDoesNotContain("Received 1 related call"); ExceptionMessageDoesNotContain("SampleMethod(*1*)"); } } public class When_checking_call_to_a_property_setter : Context { protected override void ConfigureContext() { Sample.AProperty = 1; } protected override void ExpectedCall() { Sample.Received().AProperty = 5; } [Test] public void Should_list_expected_property_set() { ExceptionMessageContains(ExpectedCallMessagePrefix + "AProperty = 5"); } [Test] public void Should_list_actual_calls() { ExceptionMessageContains("Property = *1*"); } } public class When_checking_call_to_a_property_getter : Context { protected int _ignored; protected override void ExpectedCall() { _ignored = Sample.Received().AProperty; } [Test] public void Should_list_expected_property_get() { ExceptionMessageContains(ExpectedCallMessagePrefix + "AProperty"); } } public class When_checking_call_to_an_indexer_setter : Context { protected override void ConfigureContext() { Sample["c", "d"] = 5; Sample["a", "z"] = 2; Sample["a", "b"] = 1; } protected override void ExpectedCall() { Sample.Received()["a", "b"] = 5; } [Test] public void Should_list_expected_indexer_set() { ExceptionMessageContains(ExpectedCallMessagePrefix + "this[\"a\", \"b\"] = 5"); } [Test] public void Should_list_non_matching_calls() { ExceptionMessageContains("this[*\"c\"*, *\"d\"*] = 5"); ExceptionMessageContains("this[\"a\", *\"z\"*] = *2*"); ExceptionMessageContains("this[\"a\", \"b\"] = *1*"); } } public class When_checking_call_to_an_indexer_getter : Context { protected int _ignored; protected override void ConfigureContext() { _ignored = Sample["c", "d"]; _ignored = Sample["a", "d"]; } protected override void ExpectedCall() { _ignored = Sample.Received()["a", "b"]; } [Test] public void Should_list_expected_indexer_get() { ExceptionMessageContains(ExpectedCallMessagePrefix + "this[\"a\", \"b\"]"); } [Test] public void Should_list_non_matching_calls() { ExceptionMessageContains("this[*\"c\"*, *\"d\"*]"); ExceptionMessageContains("this[\"a\", *\"d\"*]"); } } public class When_checking_call_to_method_with_params : Context { protected override void ConfigureContext() { Sample.ParamsMethod(2, "hello", "everybody"); Sample.ParamsMethod(1, new[] {"hello", "everybody"}); Sample.ParamsMethod(1, "hello"); Sample.ParamsMethod(3, "1", "2", "3"); } protected override void ExpectedCall() { Sample.Received().ParamsMethod(1, "hello", "world"); } [Test] public void Should_show_expected_call() { ExceptionMessageContains("ParamsMethod(1, \"hello\", \"world\")"); } [Test] public void Should_show_non_matching_calls_with_params_expanded() { ExceptionMessageContains("ParamsMethod(*2*, \"hello\", *\"everybody\"*)"); ExceptionMessageContains("ParamsMethod(1, \"hello\", *\"everybody\"*)"); ExceptionMessageContains("ParamsMethod(1, \"hello\")"); ExceptionMessageContains("ParamsMethod(*3*, *\"1\"*, *\"2\"*, *\"3\"*)"); } } public class When_checking_call_to_method_with_params_specified_as_an_array : Context { protected override void ConfigureContext() { Sample.ParamsMethod(2, "hello", "everybody"); } protected override void ExpectedCall() { Sample.Received().ParamsMethod(1, Arg.Is(new[] {"hello", "world"})); } [Test] public void Should_show_expected_call() { ExceptionMessageContains("ParamsMethod(1, String[])"); } [Test] public void Should_show_non_matching_calls_as_per_specification_rather_than_as_individual_params() { ExceptionMessageContains("ParamsMethod(*2*, *String[]*)"); } } public class When_checking_delegate_call : Context { private Func<int, string, string> _func; protected override void ConfigureContext() { _func = Substitute.For<Func<int, string, string>>(); _func(1, "def"); _func(2, "def"); _func(3, "abc"); } protected override void ExpectedCall() { _func.Received()(1, "abc"); } [Test] public void Should_show_expected_call() { ExceptionMessageContains("Invoke(1, \"abc\")"); } [Test] public void Should_show_non_matching_calls() { ExceptionMessageContains("Invoke(1, *\"def\"*)"); ExceptionMessageContains("Invoke(*2*, *\"def\"*)"); ExceptionMessageContains("Invoke(*3*, \"abc\")"); } } public abstract class Context { protected const string ExpectedCallMessagePrefix = "Expected to receive a call matching:\n\t"; protected ISample Sample; private ReceivedCallsException _exception; [SetUp] public void SetUp() { Sample = Substitute.For<ISample>(); ConfigureContext(); try { ExpectedCall(); } catch (ReceivedCallsException ex) { _exception = ex; } } protected abstract void ExpectedCall(); protected virtual void ConfigureContext() { } protected void ExceptionMessageContains(string expected) { Assert.That(_exception.Message, Is.StringContaining(expected)); } protected void ExceptionMessageDoesNotContain(string s) { Assert.That(_exception.Message, Is.Not.StringContaining(s)); } protected void ExceptionMessageMatchesRegex(string pattern) { Assert.That(_exception.Message, Is.StringMatching(pattern)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared] internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { private const string Default = "*"; private readonly object _gate; private readonly SolutionCrawlerProgressReporter _progressReporter; private readonly IAsynchronousOperationListener _listener; private readonly ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders; private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap; [ImportingConstructor] public SolutionCrawlerRegistrationService( [ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _gate = new object(); _analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray()); AssertAnalyzerProviders(_analyzerProviders); _documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance); _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.SolutionCrawler); _progressReporter = new SolutionCrawlerProgressReporter(_listener); } public void Register(Workspace workspace) { var correlationId = LogAggregator.GetNextId(); lock (_gate) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { // already registered. return; } var coordinator = new WorkCoordinator( _listener, GetAnalyzerProviders(workspace), new Registration(correlationId, workspace, _progressReporter)); _documentWorkCoordinatorMap.Add(workspace, coordinator); } SolutionCrawlerLogger.LogRegistration(correlationId, workspace); } public void Unregister(Workspace workspace, bool blockingShutdown = false) { var coordinator = default(WorkCoordinator); lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator)) { // already unregistered return; } _documentWorkCoordinatorMap.Remove(workspace); coordinator.Shutdown(blockingShutdown); } SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId); } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId> projectIds, IEnumerable<DocumentId> documentIds, bool highPriority) { lock (_gate) { var coordinator = default(WorkCoordinator); if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator)) { throw new ArgumentException("workspace"); } // no specific projects or documents provided if (projectIds == null && documentIds == null) { coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(), highPriority); return; } // specific documents provided if (projectIds == null) { coordinator.Reanalyze(analyzer, documentIds.ToSet(), highPriority); return; } var solution = workspace.CurrentSolution; var set = new HashSet<DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable<DocumentId>()); set.UnionWith(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds)); coordinator.Reanalyze(analyzer, set, highPriority); } } internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { _documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(workers); } } internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { _documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(); } } private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(Workspace workspace) { Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider; foreach (var kv in _analyzerProviders) { var lazyProviders = kv.Value; // try get provider for the specific workspace kind if (TryGetProvider(workspace.Kind, lazyProviders, out lazyProvider)) { yield return lazyProvider; continue; } // try get default provider if (TryGetProvider(Default, lazyProviders, out lazyProvider)) { yield return lazyProvider; } } } private bool TryGetProvider( string kind, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders, out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider) { // set out param lazyProvider = null; // try find provider for specific workspace kind if (kind != Default) { foreach (var provider in lazyProviders) { if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true) { lazyProvider = provider; return true; } } return false; } // try find default provider foreach (var provider in lazyProviders) { if (IsDefaultProvider(provider.Metadata)) { lazyProvider = provider; return true; } return false; } return false; } [Conditional("DEBUG")] private static void AssertAnalyzerProviders( ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders) { #if DEBUG // make sure there is duplicated provider defined for same workspace. var set = new HashSet<string>(); foreach (var kv in analyzerProviders) { foreach (var lazyProvider in kv.Value) { if (IsDefaultProvider(lazyProvider.Metadata)) { Contract.Requires(set.Add(Default)); continue; } foreach (var kind in lazyProvider.Metadata.WorkspaceKinds) { Contract.Requires(set.Add(kind)); } } set.Clear(); } #endif } private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata) { return providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Length == 0; } private class Registration { public readonly int CorrelationId; public readonly Workspace Workspace; public readonly SolutionCrawlerProgressReporter ProgressReporter; public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter) { CorrelationId = correlationId; Workspace = workspace; ProgressReporter = progressReporter; } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public TService GetService<TService>() where TService : IWorkspaceService { return Workspace.Services.GetService<TService>(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Xunit; namespace System.Linq.Tests { public class GroupByTests : EnumerableTests { public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping) { AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default); } public static void AssertGroupingCorrect<TKey, TElement>(IEnumerable<TKey> keys, IEnumerable<TElement> elements, IEnumerable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer) { if (grouping == null) { Assert.Null(elements); Assert.Null(keys); return; } Assert.NotNull(elements); Assert.NotNull(keys); Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer); List<TElement> groupingForNullKeys = new List<TElement>(); using (IEnumerator<TElement> elEn = elements.GetEnumerator()) using (IEnumerator<TKey> keyEn = keys.GetEnumerator()) { while (keyEn.MoveNext()) { Assert.True(elEn.MoveNext()); TKey key = keyEn.Current; if (key == null) { groupingForNullKeys.Add(elEn.Current); } else { List<TElement> list; if (!dict.TryGetValue(key, out list)) dict.Add(key, list = new List<TElement>()); list.Add(elEn.Current); } } Assert.False(elEn.MoveNext()); } foreach (IGrouping<TKey, TElement> group in grouping) { Assert.NotEmpty(group); TKey key = group.Key; List<TElement> list; if (key == null) { Assert.Equal(groupingForNullKeys, group); groupingForNullKeys.Clear(); } else { Assert.True(dict.TryGetValue(key, out list)); Assert.Equal(list, group); dict.Remove(key); } } Assert.Empty(dict); Assert.Empty(groupingForNullKeys); } public struct Record { public string Name; public int Score; } [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.NotNull(q.GroupBy(e => e.a1, e => e.a2)); Assert.Equal(q.GroupBy(e => e.a1, e => e.a2), q.GroupBy(e => e.a1, e => e.a2)); } [Fact] public void Grouping_IList_IsReadOnly() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.True(grouping.IsReadOnly); } } [Fact] public void Grouping_IList_NotSupported() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); foreach (IList<int> grouping in oddsEvens) { Assert.Throws<NotSupportedException>(() => grouping.Add(5)); Assert.Throws<NotSupportedException>(() => grouping.Clear()); Assert.Throws<NotSupportedException>(() => grouping.Insert(0, 1)); Assert.Throws<NotSupportedException>(() => grouping.Remove(1)); Assert.Throws<NotSupportedException>(() => grouping.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => grouping[0] = 1); } } [Fact] public void Grouping_IList_IndexerGetter() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(1, odds[0]); Assert.Equal(3, odds[1]); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(2, evens[0]); Assert.Equal(4, evens[1]); } [Fact] public void Grouping_IList_IndexGetterOutOfRange() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Throws<ArgumentOutOfRangeException>("index", () => odds[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => odds[23]); } [Fact] public void Grouping_ICollection_Contains() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); ICollection<int> odds = (IList<int>)e.Current; Assert.True(odds.Contains(1)); Assert.True(odds.Contains(3)); Assert.False(odds.Contains(2)); Assert.False(odds.Contains(4)); Assert.True(e.MoveNext()); ICollection<int> evens = (IList<int>)e.Current; Assert.True(evens.Contains(2)); Assert.True(evens.Contains(4)); Assert.False(evens.Contains(1)); Assert.False(evens.Contains(3)); } [Fact] public void Grouping_IList_IndexOf() { IEnumerable<IGrouping<bool, int>> oddsEvens = new int[] { 1, 2, 3, 4 }.GroupBy(i => i % 2 == 0); var e = oddsEvens.GetEnumerator(); Assert.True(e.MoveNext()); IList<int> odds = (IList<int>)e.Current; Assert.Equal(0, odds.IndexOf(1)); Assert.Equal(1, odds.IndexOf(3)); Assert.Equal(-1, odds.IndexOf(2)); Assert.Equal(-1, odds.IndexOf(4)); Assert.True(e.MoveNext()); IList<int> evens = (IList<int>)e.Current; Assert.Equal(0, evens.IndexOf(2)); Assert.Equal(1, evens.IndexOf(4)); Assert.Equal(-1, evens.IndexOf(1)); Assert.Equal(-1, evens.IndexOf(3)); } [Fact] public void SingleNullKeySingleNullElement() { string[] key = { null }; string[] element = { null }; AssertGroupingCorrect(key, element, new string[] { null }.GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default); } [Fact] public void EmptySource() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void EmptySourceRunOnce() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.RunOnce().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNull() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsed() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparer() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum())); } [Fact] public void SourceIsNullResultSelectorUsedNoComparerOrElementSelector() { Record[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score))); } [Fact] public void KeySelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, new AnagramEqualityComparer())); Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsed() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void KeySelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, string> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); } [Fact] public void KeySelectorNullResultSelectorUsedNoElementSelector() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Assert.Throws<ArgumentNullException>("keySelector", () => source.GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer())); } [Fact] public void ElementSelectorNullResultSelectorUsedNoComparer() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<Record, int> elementSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum())); } [Fact] public void ResultSelectorNull() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNullNoComparer() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<int>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, e => e.Score, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelector() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Func<string, IEnumerable<Record>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelectorCustomComparer() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Func<string, IEnumerable<Record>, long> resultSelector = null; Assert.Throws<ArgumentNullException>("resultSelector", () => source.GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer())); } [Fact] public void EmptySourceWithResultSelector() { string[] key = { }; int[] element = { }; Record[] source = { }; Assert.Empty(new Record[] { }.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparer() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparerRunOnce() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void NullComparer() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void NullComparerRunOnce() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.RunOnce().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void SingleNonNullElement() { string[] key = { "Tim" }; Record[] source = { new Record { Name = key[0], Score = 60 } }; AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name)); } [Fact] public void AllElementsSameKey() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] scores = { 60, -10, 40, 100 }; var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, source, source.GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Fact] public void AllElementsDifferentKeyElementSelectorUsed() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeys() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SomeDuplicateKeysIncludingNulls() { string[] key = { null, null, "Chris", "Chris", "Prakash", "Prakash" }; int[] element = { 55, 25, 49, 24, 9, 9 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key, element, source.GroupBy(e => e.Name, e => e.Score)); } [Fact] public void SingleElementResultSelectorUsed() { string[] key = { "Tim" }; int[] element = { 60 }; long[] expected = { 180 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => (long)(k ?? " ").Length * es.Sum(e => e.Score))); } [Fact] public void GroupedResultCorrectSize() { var elements = Enumerable.Repeat('q', 5); var result = elements.GroupBy(e => e, (e, f) => new { Key = e, Element = f }); Assert.Equal(1, result.Count()); var grouping = result.First(); Assert.Equal(5, grouping.Element.Count()); Assert.Equal('q', grouping.Key); Assert.True(grouping.Element.All(e => e == 'q')); } [Fact] public void AllElementsDifferentKeyElementSelectorUsedResultSelector() { string[] key = { "Tim", "Chris", "Robert", "Prakash" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); long[] expected = { 180, -50, 240, 700 }; Assert.Equal(expected, source.GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum())); } [Fact] public void AllElementsSameKeyResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; long[] expected = { 570 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] } }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer())); } [Fact] public void NullComparerResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] }, }; long[] expected = { 150, 420 }; Assert.Equal(expected, source.GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null)); } [Fact] public void GroupingToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IGrouping<string, Record>[] groupedArray = source.GroupBy(r => r.Name).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name), groupedArray); } [Fact] public void GroupingWithElementSelectorToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IGrouping<string, int>[] groupedArray = source.GroupBy(r => r.Name, e => e.Score).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedArray); } [Fact] public void GroupingWithResultsToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, (r, e) => e).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedArray); } [Fact] public void GroupingWithElementSelectorAndResultsToArray() { Record[] source = new Record[] { new Record{ Name = "Tim", Score = 55 }, new Record{ Name = "Chris", Score = 49 }, new Record{ Name = "Robert", Score = -100 }, new Record{ Name = "Chris", Score = 24 }, new Record{ Name = "Prakash", Score = 9 }, new Record{ Name = "Tim", Score = 25 } }; IEnumerable<Record>[] groupedArray = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToArray(); Assert.Equal(4, groupedArray.Length); Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedArray); } [Fact] public void GroupingToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IGrouping<string, Record>> groupedList = source.GroupBy(r => r.Name).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name), groupedList); } [Fact] public void GroupingWithElementSelectorToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IGrouping<string, int>> groupedList = source.GroupBy(r => r.Name, e => e.Score).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, e => e.Score), groupedList); } [Fact] public void GroupingWithResultsToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, (r, e) => e).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, (r, e) => e), groupedList); } [Fact] public void GroupingWithElementSelectorAndResultsToList() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; List<IEnumerable<Record>> groupedList = source.GroupBy(r => r.Name, e => e, (r, e) => e).ToList(); Assert.Equal(4, groupedList.Count); Assert.Equal(source.GroupBy(r => r.Name, e => e, (r, e) => e), groupedList); } [Fact] public void GroupingCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name).Count()); } [Fact] public void GroupingWithElementSelectorCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, e => e.Score).Count()); } [Fact] public void GroupingWithResultsCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, (r, e) => e).Count()); } [Fact] public void GroupingWithElementSelectorAndResultsCount() { Record[] source = new Record[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Assert.Equal(4, source.GroupBy(r => r.Name, e=> e, (r, e) => e).Count()); } [Fact] public void EmptyGroupingToArray() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToArray()); } [Fact] public void EmptyGroupingToList() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i).ToList()); } [Fact] public void EmptyGroupingCount() { Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i).Count()); } [Fact] public void EmptyGroupingWithResultToArray() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToArray()); } [Fact] public void EmptyGroupingWithResultToList() { Assert.Empty(Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).ToList()); } [Fact] public void EmptyGroupingWithResultCount() { Assert.Equal(0, Enumerable.Empty<int>().GroupBy(i => i, (x, y) => x + y.Count()).Count()); } [Fact] public static void GroupingKeyIsPublic() { // Grouping.Key needs to be public (not explicitly implemented) for the sake of WPF. object[] objs = { "Foo", 1.0M, "Bar", new { X = "X" }, 2.00M }; object group = objs.GroupBy(x => x.GetType()).First(); Type grouptype = group.GetType(); PropertyInfo key = grouptype.GetProperty("Key", BindingFlags.Instance | BindingFlags.Public); Assert.NotNull(key); } [Theory] [MemberData(nameof(DebuggerAttributesValid_Data))] public void DebuggerAttributesValid<TKey, TElement>(IGrouping<TKey, TElement> grouping, string keyString, TKey dummy1, TElement dummy2) { // The dummy parameters can be removed once https://github.com/dotnet/buildtools/pull/1300 is brought in. Assert.Equal($"Key = {keyString}", DebuggerAttributes.ValidateDebuggerDisplayReferences(grouping)); object proxyObject = DebuggerAttributes.GetProxyObject(grouping); // Validate proxy fields Assert.Empty(DebuggerAttributes.GetDebuggerVisibleFields(proxyObject)); // Validate proxy properties IDictionary<string, PropertyInfo> properties = DebuggerAttributes.GetDebuggerVisibleProperties(proxyObject); Assert.Equal(2, properties.Count); // Key TKey key = (TKey)properties["Key"].GetValue(proxyObject); Assert.Equal(grouping.Key, key); // Values PropertyInfo valuesProperty = properties["Values"]; Assert.Equal(DebuggerBrowsableState.RootHidden, DebuggerAttributes.GetDebuggerBrowsableState(valuesProperty)); TElement[] values = (TElement[])valuesProperty.GetValue(proxyObject); Assert.IsType<TElement[]>(values); // Arrays can be covariant / of assignment-compatible types Assert.Equal(grouping, values); Assert.Same(values, valuesProperty.GetValue(proxyObject)); // The result should be cached, as Grouping is immutable. } public static IEnumerable<object[]> DebuggerAttributesValid_Data() { IEnumerable<int> source = new[] { 1 }; yield return new object[] { source.GroupBy(i => i).Single(), "1", 0, 0 }; yield return new object[] { source.GroupBy(i => i.ToString(), i => i).Single(), @"""1""", string.Empty, 0 }; yield return new object[] { source.GroupBy(i => TimeSpan.FromSeconds(i), i => i).Single(), "{00:00:01}", TimeSpan.Zero, 0 }; yield return new object[] { new string[] { null }.GroupBy(x => x).Single(), "null", string.Empty, string.Empty }; // This test won't even work with the work-around because nullables lose their type once boxed, so xUnit sees an `int` and thinks // we're trying to pass an IGrouping<int, int> rather than an IGrouping<int?, int?>. // However, it should also be fixed once that PR is brought in, so leaving in this comment. // yield return new object[] { new int?[] { null }.GroupBy(x => x).Single(), "null", new int?(0), new int?(0) }; } } }
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 SAASKit.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <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) 2012-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; namespace OpenGL.Objects.State { /// <summary> /// State tracking the transformation state. /// </summary> /// <remarks> /// <para> /// The transform state exposes a set of matrices that are dedicated of the transformation of three-dimensional /// points and vectors in order to project them onto the screen: /// - Projection /// - Model-view /// - Normal /// </para> /// </remarks> [DebuggerDisplay("TransformState: Projection={Projection} ModelView={ModelView}")] public class TransformState : ShaderUniformStateBase { #region Constructors /// <summary> /// Static constructor. /// </summary> static TransformState() { // Statically initialize uniform properties _UniformProperties = DetectUniformProperties(typeof(TransformState)); } #endregion #region Default State /// <summary> /// The system default state for PixelAlignmentState. /// </summary> public static TransformState DefaultState { get { return (new TransformState()); } } #endregion #region Transform State /// <summary> /// The actual model-view matrix used for transforming vertex arrays space. /// </summary> [ShaderUniformState] public Matrix4x4f? Projection { get; set; } /// <summary> /// The actual model-view matrix used for transforming vertex arrays space. /// </summary> [ShaderUniformState] public Matrix4x4f ModelView { get; set; } = Matrix4x4f.Identity; /// <summary> /// The actual model-view-projection matrix used for drawing vertex arrays. /// </summary> [ShaderUniformState] public Matrix4x4f? ModelViewProjection { get { if (!_ModelViewProjection.HasValue && Projection.HasValue) return Projection.Value * ModelView; // Lazily computed return _ModelViewProjection; } set { _ModelViewProjection = value; } } /// <summary> /// Backend value for ModelViewProjection. /// </summary> private Matrix4x4f? _ModelViewProjection; /// <summary> /// The normal matrix, derived from <see cref="ModelView"/>. /// </summary> [ShaderUniformState] public Matrix3x3f NormalMatrix { get { return (new Matrix3x3f(ModelView, 3, 3).Inverse.Transposed); } } #endregion #region ShaderUniformState Overrides /// <summary> /// The identifier for the TransformState derived classes. /// </summary> public static string StateId = "OpenGL.TransformState"; /// <summary> /// The identifier of this GraphicsState. /// </summary> public override string StateIdentifier { get { return (StateId); } } /// <summary> /// Unique index assigned to this GraphicsState. /// </summary> public static int StateSetIndex { get { return (_StateIndex); } } /// <summary> /// Unique index assigned to this GraphicsState. /// </summary> public override int StateIndex { get { return (_StateIndex); } } /// <summary> /// The index for this GraphicsState. /// </summary> private static readonly int _StateIndex = NextStateIndex(); /// <summary> /// Flag indicating whether the state is context-bound. /// </summary> /// <remarks> /// It returns always true, since it supports also fixed pipeline. /// </remarks> public override bool IsContextBound { get { return (true); } } /// <summary> /// Flag indicating whether the state can be applied on a <see cref="ShaderProgram"/>. /// </summary> public override bool IsProgramBound { get { return (true); } } /// <summary> /// Apply this TransformState. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>. /// </param> /// <param name="shaderProgram"> /// The <see cref="ShaderProgram"/> which has the state set. /// </param> public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram) { GraphicsResource.CheckCurrentContext(ctx); if (shaderProgram == null) { // Fixed pipeline rendering requires server state #if !MONODROID Matrix4x4f p = Projection ?? Matrix4x4f.Identity; if (ctx.Extensions.DirectStateAccess_EXT) { // Set projection and model-view matrix Gl.MatrixLoadfEXT(MatrixMode.Projection, p); Gl.MatrixLoadfEXT(MatrixMode.Modelview, ModelView); } else { // Set projection matrix Gl.MatrixMode(MatrixMode.Projection); Gl.LoadMatrixf(p); // Set model-view matrix Gl.MatrixMode(MatrixMode.Modelview); Gl.LoadMatrixf(ModelView); } #else throw new NotSupportedException("fixed pipeline not supported"); #endif } else { // Shader implementation (TransformState.glsl) ctx.Bind(shaderProgram); // Usual matrices Debug.Assert(ModelViewProjection.HasValue); if (ModelViewProjection.HasValue) shaderProgram.SetUniform(ctx, "glo_ModelViewProjection", ModelViewProjection.Value); if (shaderProgram.IsActiveUniform("glo_NormalMatrix")) shaderProgram.SetUniform(ctx, "glo_NormalMatrix", NormalMatrix); if (shaderProgram.IsActiveUniform("glo_ModelView")) shaderProgram.SetUniform(ctx, "glo_ModelView", ModelView); } } /// <summary> /// Merge this state with another one. /// </summary> /// <param name="state"> /// A <see cref="IGraphicsState"/> having the same <see cref="StateIdentifier"/> of this state. /// </param> public override void Merge(IGraphicsState state) { if (state == null) throw new ArgumentNullException(nameof(state)); try { TransformState otherState = (TransformState)state; if (otherState.Projection.HasValue) Projection = otherState.Projection.Value; ModelView = ModelView * otherState.ModelView; if (_ModelViewProjection.HasValue && !otherState.Projection.HasValue) _ModelViewProjection = _ModelViewProjection.Value * otherState.ModelView; else _ModelViewProjection = otherState.ModelViewProjection.Value; Debug.Assert(_ModelViewProjection.HasValue); Debug.Assert(_ModelViewProjection.Value.Equals((Matrix4x4f)(Projection * ModelView), 1e-3f)); } catch (InvalidCastException) { throw new ArgumentException("not a TransformState", nameof(state)); } } /// <summary> /// Get the uniform state associated with this instance. /// </summary> protected override Dictionary<string, UniformStateMember> UniformState { get { return (_UniformProperties); } } /// <summary> /// Represents the current <see cref="GraphicsState"/> for logging. /// </summary> /// <returns> /// A <see cref="String"/> that represents the current <see cref="GraphicsState"/>. /// </returns> public override string ToString() { return (string.Empty); } /// <summary> /// The uniform state of this TransformState. /// </summary> private static readonly Dictionary<string, UniformStateMember> _UniformProperties; #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace RemoteEventsLabWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DowUtils; namespace Factotum { public partial class KitEdit : Form, IEntityEditForm { private EKit curKit; private DataTable inspectorAssignments; private DataTable meterAssignments; private DataTable ducerAssignments; private DataTable calBlockAssignments; private DataTable thermoAssignments; // Allow the calling form to access the entity public IEntity Entity { get { return curKit; } } //--------------------------------------------------------- // Initialization //--------------------------------------------------------- // If you are creating a new record, the ID should be null // Normally in this case, you will want to provide a parentID public KitEdit() : this(null){} public KitEdit(Guid? ID) { InitializeComponent(); curKit = new EKit(); curKit.Load(ID); InitializeControls(ID == null); } // Initialize the form control values private void InitializeControls(bool newRecord) { // Note: We only need to show active items are shown in the checked list boxes // because Items are removed from kits whenever they are inactivated. // For the special case of inspectors, we also want to exclude all inspectors // who are not assigned to the current outage. If an inspector is first assigned // to an outage and given a toolkit, then unassigned, his tool kit will be unassigned. GetInspectorAssignments(); GetMeterAssignments(); GetDucerAssignments(); GetCalBlockAssignments(); GetThermoAssignments(); SetControlValues(); this.Text = newRecord ? "New Kit" : "Edit Kit"; EInspector.Changed += new EventHandler<EntityChangedEventArgs>(EInspector_Changed); EMeter.Changed += new EventHandler<EntityChangedEventArgs>(EMeter_Changed); EDucer.Changed += new EventHandler<EntityChangedEventArgs>(EDucer_Changed); ECalBlock.Changed += new EventHandler<EntityChangedEventArgs>(ECalBlock_Changed); EThermo.Changed += new EventHandler<EntityChangedEventArgs>(EThermo_Changed); } void EThermo_Changed(object sender, EntityChangedEventArgs e) { GetThermoAssignments(); } void ECalBlock_Changed(object sender, EntityChangedEventArgs e) { GetCalBlockAssignments(); } void EDucer_Changed(object sender, EntityChangedEventArgs e) { GetDucerAssignments(); } void EMeter_Changed(object sender, EntityChangedEventArgs e) { GetMeterAssignments(); } void EInspector_Changed(object sender, EntityChangedEventArgs e) { GetInspectorAssignments(); } //--------------------------------------------------------- // Event Handlers //--------------------------------------------------------- // If the user cancels out, just close. private void btnCancel_Click(object sender, EventArgs e) { Close(); DialogResult = DialogResult.Cancel; } // If the user clicks OK, first validate and set the error text // for any controls with invalid values. // If it validates, try to save. private void btnOK_Click(object sender, EventArgs e) { SaveAndClose(); } // Each time the text changes, check to make sure its length is ok // If not, set the error. private void txtName_TextChanged(object sender, EventArgs e) { // Calling this method sets the ErrMsg property of the Object. curKit.ToolKitNameLengthOk(txtName.Text); errorProvider1.SetError(txtName, curKit.ToolKitNameErrMsg); } // The validating event gets called when the user leaves the control. // We handle it to perform all validation for the value. private void txtName_Validating(object sender, CancelEventArgs e) { // Calling this function will set the ErrMsg property of the object. curKit.ToolKitNameValid(txtName.Text); errorProvider1.SetError(txtName, curKit.ToolKitNameErrMsg); } //--------------------------------------------------------- // Helper functions //--------------------------------------------------------- // No prompting is performed. The user should understand the meanings of OK and Cancel. private void SaveAndClose() { if (AnyControlErrors()) return; // Set the entity values to match the form values UpdateRecord(); // Try to validate if (!curKit.Valid()) { setAllErrors(); return; } // The Save function returns a the Guid? of the record created or updated. Guid? tmpID = curKit.Save(); if (tmpID != null) { // We need to do these updates after saving because they require a valid Kit ID // Update Inspectors table from checkboxes for (int dmRow = 0; dmRow < inspectorAssignments.Rows.Count; dmRow++) { inspectorAssignments.Rows[dmRow]["IsAssigned"] = 0; } foreach (int idx in clbInspectors.CheckedIndices) { inspectorAssignments.Rows[idx]["IsAssigned"] = 1; } EInspector.UpdateAssignmentsToKit((Guid)curKit.ID, inspectorAssignments); // Update Meters table from checkboxes for (int dmRow = 0; dmRow < meterAssignments.Rows.Count; dmRow++) { meterAssignments.Rows[dmRow]["IsAssigned"] = 0; } foreach (int idx in clbMeters.CheckedIndices) { meterAssignments.Rows[idx]["IsAssigned"] = 1; } EMeter.UpdateAssignmentsToKit((Guid)curKit.ID, meterAssignments); // Update Ducers table from checkboxes for (int dmRow = 0; dmRow < ducerAssignments.Rows.Count; dmRow++) { ducerAssignments.Rows[dmRow]["IsAssigned"] = 0; } foreach (int idx in clbTransducers.CheckedIndices) { ducerAssignments.Rows[idx]["IsAssigned"] = 1; } EDucer.UpdateAssignmentsToKit((Guid)curKit.ID, ducerAssignments); // Update Thermos table from checkboxes for (int dmRow = 0; dmRow < thermoAssignments.Rows.Count; dmRow++) { thermoAssignments.Rows[dmRow]["IsAssigned"] = 0; } foreach (int idx in clbThermos.CheckedIndices) { thermoAssignments.Rows[idx]["IsAssigned"] = 1; } EThermo.UpdateAssignmentsToKit((Guid)curKit.ID, thermoAssignments); // Update CalBlocks table from checkboxes for (int dmRow = 0; dmRow < calBlockAssignments.Rows.Count; dmRow++) { calBlockAssignments.Rows[dmRow]["IsAssigned"] = 0; } foreach (int idx in clbCalBlocks.CheckedIndices) { calBlockAssignments.Rows[idx]["IsAssigned"] = 1; } ECalBlock.UpdateAssignmentsToKit((Guid)curKit.ID, calBlockAssignments); Close(); DialogResult = DialogResult.OK; } } // Set the form controls to the site object values. private void SetControlValues() { txtName.Text = curKit.ToolKitName; } // Set the error provider text for all controls that use it. private void setAllErrors() { errorProvider1.SetError(txtName, curKit.ToolKitNameErrMsg); } // Check all controls to see if any have errors. private bool AnyControlErrors() { return (errorProvider1.GetError(txtName).Length > 0); } // Update the object values from the form control values. private void UpdateRecord() { curKit.ToolKitName = txtName.Text; } private void GetInspectorAssignments() { // Inspector CheckedListbox inspectorAssignments = EInspector.GetWithAssignmentsForOutageAndKit( (Guid)Globals.CurrentOutageID, curKit.ID, false); clbInspectors.Items.Clear(); int rows = inspectorAssignments.Rows.Count; if (rows == 0) { clbInspectors.Visible = false; } else { for (int dmRow = 0; dmRow < inspectorAssignments.Rows.Count; dmRow++) { string inspectorName = (string)inspectorAssignments.Rows[dmRow]["InspectorName"]; string level = EInspector.InspectorLevelStringForLevel( (byte)inspectorAssignments.Rows[dmRow]["InspectorLevel"]); bool isActive = (bool)inspectorAssignments.Rows[dmRow]["InspectorIsActive"]; bool isAssigned = Convert.ToBoolean(inspectorAssignments.Rows[dmRow]["IsAssigned"]); clbInspectors.Items.Add(inspectorName + " " + level, isAssigned); } } } private void GetMeterAssignments() { // Meter CheckedListbox meterAssignments = EMeter.GetWithAssignmentsForKit(curKit.ID, false); clbMeters.Items.Clear(); int rows = meterAssignments.Rows.Count; if (rows == 0) { clbMeters.Visible = false; } else { for (int dmRow = 0; dmRow < meterAssignments.Rows.Count; dmRow++) { string modelName = (string)meterAssignments.Rows[dmRow]["MeterModelName"]; string serialNumber = (string)meterAssignments.Rows[dmRow]["MeterSerialNumber"]; bool isActive = (bool)meterAssignments.Rows[dmRow]["MeterIsActive"]; bool isAssigned = Convert.ToBoolean(meterAssignments.Rows[dmRow]["IsAssigned"]); clbMeters.Items.Add(modelName + " - S/N: " + serialNumber, isAssigned); } } } private void GetDucerAssignments() { // Ducer CheckedListbox ducerAssignments = EDucer.GetWithAssignmentsForKit(curKit.ID, false); clbTransducers.Items.Clear(); int rows = ducerAssignments.Rows.Count; if (rows == 0) { clbTransducers.Visible = false; } else { for (int dmRow = 0; dmRow < ducerAssignments.Rows.Count; dmRow++) { string modelName = (string)ducerAssignments.Rows[dmRow]["DucerModelName"]; string serialNumber = (string)ducerAssignments.Rows[dmRow]["DucerSerialNumber"]; bool isActive = (bool)ducerAssignments.Rows[dmRow]["DucerIsActive"]; bool isAssigned = Convert.ToBoolean(ducerAssignments.Rows[dmRow]["IsAssigned"]); clbTransducers.Items.Add(modelName + " - S/N: " + serialNumber, isAssigned); } } } private void GetCalBlockAssignments() { // Cal Block CheckedListbox calBlockAssignments = ECalBlock.GetWithAssignmentsForKit(curKit.ID, false); clbCalBlocks.Items.Clear(); int rows = calBlockAssignments.Rows.Count; if (rows == 0) { clbCalBlocks.Visible = false; } else { for (int dmRow = 0; dmRow < calBlockAssignments.Rows.Count; dmRow++) { string serialNumber = (string)calBlockAssignments.Rows[dmRow]["CalBlockSerialNumber"]; bool isActive = (bool)calBlockAssignments.Rows[dmRow]["CalBlockIsActive"]; bool isAssigned = Convert.ToBoolean(calBlockAssignments.Rows[dmRow]["IsAssigned"]); clbCalBlocks.Items.Add("S/N: " + serialNumber, isAssigned); } } } private void GetThermoAssignments() { // Thermos CheckedListbox thermoAssignments = EThermo.GetWithAssignmentsForKit(curKit.ID, false); clbThermos.Items.Clear(); int rows = thermoAssignments.Rows.Count; if (rows == 0) { clbThermos.Visible = false; } else { for (int dmRow = 0; dmRow < thermoAssignments.Rows.Count; dmRow++) { string serialNumber = (string)thermoAssignments.Rows[dmRow]["ThermoSerialNumber"]; bool isActive = (bool)thermoAssignments.Rows[dmRow]["ThermoIsActive"]; bool isAssigned = Convert.ToBoolean(thermoAssignments.Rows[dmRow]["IsAssigned"]); clbThermos.Items.Add("S/N: " + serialNumber, isAssigned); } } } } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DynamoDB.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DynamoDB.Model.Internal.MarshallTransformations { /// <summary> /// Query Request Marshaller /// </summary> internal class QueryRequestMarshaller : IMarshaller<IRequest, QueryRequest> { public IRequest Marshall(QueryRequest queryRequest) { IRequest request = new DefaultRequest(queryRequest, "AmazonDynamoDB"); string target = "DynamoDB_20111205.Query"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.0"; string uriResourcePath = ""; if (uriResourcePath.Contains("?")) { string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1); uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?")); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter()) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); if (queryRequest != null && queryRequest.IsSetTableName()) { writer.WritePropertyName("TableName"); writer.Write(queryRequest.TableName); } if (queryRequest != null && queryRequest.AttributesToGet != null && queryRequest.AttributesToGet.Count > 0) { List<string> attributesToGetList = queryRequest.AttributesToGet; writer.WritePropertyName("AttributesToGet"); writer.WriteArrayStart(); foreach (string attributesToGetListValue in attributesToGetList) { writer.Write(StringUtils.FromString(attributesToGetListValue)); } writer.WriteArrayEnd(); } if (queryRequest != null && queryRequest.IsSetLimit()) { writer.WritePropertyName("Limit"); writer.Write(queryRequest.Limit); } if (queryRequest != null && queryRequest.IsSetConsistentRead()) { writer.WritePropertyName("ConsistentRead"); writer.Write(queryRequest.ConsistentRead); } if (queryRequest != null && queryRequest.IsSetCount()) { writer.WritePropertyName("Count"); writer.Write(queryRequest.Count); } if (queryRequest != null) { AttributeValue hashKeyValue = queryRequest.HashKeyValue; if (hashKeyValue != null) { writer.WritePropertyName("HashKeyValue"); writer.WriteObjectStart(); if (hashKeyValue != null && hashKeyValue.IsSetS()) { writer.WritePropertyName("S"); writer.Write(hashKeyValue.S); } if (hashKeyValue != null && hashKeyValue.IsSetN()) { writer.WritePropertyName("N"); writer.Write(hashKeyValue.N); } if (hashKeyValue != null && hashKeyValue.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(hashKeyValue.B)); } if (hashKeyValue != null && hashKeyValue.SS != null && hashKeyValue.SS.Count > 0) { List<string> sSList = hashKeyValue.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (hashKeyValue != null && hashKeyValue.NS != null && hashKeyValue.NS.Count > 0) { List<string> nSList = hashKeyValue.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (hashKeyValue != null && hashKeyValue.BS != null && hashKeyValue.BS.Count > 0) { List<MemoryStream> bSList = hashKeyValue.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } } if (queryRequest != null) { Condition rangeKeyCondition = queryRequest.RangeKeyCondition; if (rangeKeyCondition != null) { writer.WritePropertyName("RangeKeyCondition"); writer.WriteObjectStart(); if (rangeKeyCondition != null && rangeKeyCondition.AttributeValueList != null && rangeKeyCondition.AttributeValueList.Count > 0) { List<AttributeValue> attributeValueListList = rangeKeyCondition.AttributeValueList; writer.WritePropertyName("AttributeValueList"); writer.WriteArrayStart(); foreach (AttributeValue attributeValueListListValue in attributeValueListList) { writer.WriteObjectStart(); if (attributeValueListListValue != null && attributeValueListListValue.IsSetS()) { writer.WritePropertyName("S"); writer.Write(attributeValueListListValue.S); } if (attributeValueListListValue != null && attributeValueListListValue.IsSetN()) { writer.WritePropertyName("N"); writer.Write(attributeValueListListValue.N); } if (attributeValueListListValue != null && attributeValueListListValue.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(attributeValueListListValue.B)); } if (attributeValueListListValue != null && attributeValueListListValue.SS != null && attributeValueListListValue.SS.Count > 0) { List<string> sSList = attributeValueListListValue.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (attributeValueListListValue != null && attributeValueListListValue.NS != null && attributeValueListListValue.NS.Count > 0) { List<string> nSList = attributeValueListListValue.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (attributeValueListListValue != null && attributeValueListListValue.BS != null && attributeValueListListValue.BS.Count > 0) { List<MemoryStream> bSList = attributeValueListListValue.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } writer.WriteArrayEnd(); } if (rangeKeyCondition != null && rangeKeyCondition.IsSetComparisonOperator()) { writer.WritePropertyName("ComparisonOperator"); writer.Write(rangeKeyCondition.ComparisonOperator); } writer.WriteObjectEnd(); } } if (queryRequest != null && queryRequest.IsSetScanIndexForward()) { writer.WritePropertyName("ScanIndexForward"); writer.Write(queryRequest.ScanIndexForward); } if (queryRequest != null) { Key exclusiveStartKey = queryRequest.ExclusiveStartKey; if (exclusiveStartKey != null) { writer.WritePropertyName("ExclusiveStartKey"); writer.WriteObjectStart(); if (exclusiveStartKey != null) { AttributeValue hashKeyElement = exclusiveStartKey.HashKeyElement; if (hashKeyElement != null) { writer.WritePropertyName("HashKeyElement"); writer.WriteObjectStart(); if (hashKeyElement != null && hashKeyElement.IsSetS()) { writer.WritePropertyName("S"); writer.Write(hashKeyElement.S); } if (hashKeyElement != null && hashKeyElement.IsSetN()) { writer.WritePropertyName("N"); writer.Write(hashKeyElement.N); } if (hashKeyElement != null && hashKeyElement.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(hashKeyElement.B)); } if (hashKeyElement != null && hashKeyElement.SS != null && hashKeyElement.SS.Count > 0) { List<string> sSList = hashKeyElement.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (hashKeyElement != null && hashKeyElement.NS != null && hashKeyElement.NS.Count > 0) { List<string> nSList = hashKeyElement.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (hashKeyElement != null && hashKeyElement.BS != null && hashKeyElement.BS.Count > 0) { List<MemoryStream> bSList = hashKeyElement.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } } if (exclusiveStartKey != null) { AttributeValue rangeKeyElement = exclusiveStartKey.RangeKeyElement; if (rangeKeyElement != null) { writer.WritePropertyName("RangeKeyElement"); writer.WriteObjectStart(); if (rangeKeyElement != null && rangeKeyElement.IsSetS()) { writer.WritePropertyName("S"); writer.Write(rangeKeyElement.S); } if (rangeKeyElement != null && rangeKeyElement.IsSetN()) { writer.WritePropertyName("N"); writer.Write(rangeKeyElement.N); } if (rangeKeyElement != null && rangeKeyElement.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(rangeKeyElement.B)); } if (rangeKeyElement != null && rangeKeyElement.SS != null && rangeKeyElement.SS.Count > 0) { List<string> sSList = rangeKeyElement.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (rangeKeyElement != null && rangeKeyElement.NS != null && rangeKeyElement.NS.Count > 0) { List<string> nSList = rangeKeyElement.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (rangeKeyElement != null && rangeKeyElement.BS != null && rangeKeyElement.BS.Count > 0) { List<MemoryStream> bSList = rangeKeyElement.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } } writer.WriteObjectEnd(); } } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
//--------------------------------------------------------------------- // <copyright file="ErrorCode.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner jeffreed // @backupOwner anpete //--------------------------------------------------------------------- namespace System.Data.EntityModel.SchemaObjectModel { // This file contains an enum for the errors generated by Metadata Loading (SOM) // // There is almost a one-to-one correspondence between these error codes // and the resource strings - so if you need more insight into what the // error code means, please see the code that uses the particular enum // AND the corresponding resource string // // error numbers end up being hard coded in test cases; they can be removed, but should not be changed. // reusing error numbers is probably OK, but not recommended. // // The acceptable range for this enum is // 0000 - 0999 // // The Range 10,000-15,000 is reserved for tools // /// <summary> /// Summary description for ErrorCode. /// </summary> internal enum ErrorCode { /// <summary></summary> InvalidErrorCodeValue = 0, // unused 1, /// <summary></summary> SecurityError = 2, // unused 3, /// <summary></summary> IOException = 4, /// <summary></summary> XmlError = 5, /// <summary></summary> TooManyErrors = 6, /// <summary></summary> MalformedXml = 7, /// <summary></summary> UnexpectedXmlNodeType = 8, /// <summary></summary> UnexpectedXmlAttribute = 9, /// <summary></summary> UnexpectedXmlElement = 10, /// <summary></summary> TextNotAllowed = 11, /// <summary></summary> EmptyFile = 12, /// <summary></summary> XsdError = 13, /// <summary></summary> InvalidAlias = 14, // unused 15, /// <summary></summary> IntegerExpected = 16, /// <summary></summary> InvalidName = 17, // unused 18, /// <summary></summary> AlreadyDefined = 19, /// <summary></summary> ElementNotInSchema = 20, // unused 21, /// <summary></summary> InvalidBaseType = 22, /// <summary></summary> NoConcreteDescendants = 23, /// <summary></summary> CycleInTypeHierarchy = 24, /// <summary></summary> InvalidVersionNumber = 25, /// <summary></summary> InvalidSize = 26, /// <summary></summary> InvalidBoolean = 27, // unused 28, /// <summary></summary> BadType = 29, // unused 30, // unused 31, /// <summary></summary> InvalidVersioningClass = 32, /// <summary></summary> InvalidVersionIntroduced = 33, /// <summary></summary> BadNamespace = 34, // unused 35, // unused 36, // unused 37, /// <summary></summary> UnresolvedReferenceSchema = 38, // unused 39, /// <summary></summary> NotInNamespace = 40, /// <summary></summary> NotUnnestedType = 41, /// <summary></summary> BadProperty = 42, /// <summary></summary> UndefinedProperty = 43, /// <summary></summary> InvalidPropertyType = 44, /// <summary></summary> InvalidAsNestedType = 45, /// <summary></summary> InvalidChangeUnit = 46, /// <summary></summary> UnauthorizedAccessException = 47, // unused 48, // unused 49, /// <summary>Namespace attribute must be specified.</summary> MissingNamespaceAttribute = 50, /// <summary> Precision out of range </summary> PrecisionOutOfRange = 51, /// <summary> Scale out of range </summary> ScaleOutOfRange = 52, /// <summary></summary> DefaultNotAllowed = 53, /// <summary></summary> InvalidDefault = 54, /// <summary>One of the required facets is missing</summary> RequiredFacetMissing = 55, /// <summary></summary> BadImageFormatException = 56, /// <summary></summary> MissingSchemaXml = 57, /// <summary></summary> BadPrecisionAndScale = 58, /// <summary></summary> InvalidChangeUnitUsage = 59, /// <summary></summary> NameTooLong = 60, /// <summary></summary> CircularlyDefinedType = 61, /// <summary></summary> InvalidAssociation = 62, /// <summary> /// The facet isn't allow by the property type. /// </summary> FacetNotAllowedByType = 63, /// <summary> /// This facet value is constant and is specified in the schema /// </summary> ConstantFacetSpecifiedInSchema = 64, // unused 65, // unused 66, // unused 67, // unused 68, // unused 69, // unused 70, // unused 71, // unused 72, // unused 73, /// <summary></summary> BadNavigationProperty = 74, /// <summary></summary> InvalidKey = 75, // unused 76, // unused 77, // unused 78, // unused 79, // unused 80, // unused 81, // unused 82, // unused 83, // unused 84, // unused 85, // unused 86, // unused 87, // unused 88, // unused 89, // unused 90, // unused 91, /// <summary>Multiplicity value was malformed</summary> InvalidMultiplicity = 92, // unused 93, // unused 94, // unused 95, /// <summary>The value for the Action attribute is invalid or not allowed in the current context</summary> InvalidAction = 96, /// <summary>An error occured processing the On&lt;Operation&gt; elements</summary> InvalidOperation = 97, // unused 98, /// <summary>Ends were given for the Property element of a EntityContainer that is not a RelationshipSet</summary> InvalidContainerTypeForEnd = 99, /// <summary>The extent name used in the EntittyContainerType End does not match the name of any of the EntityContainerProperties in the containing EntityContainer</summary> InvalidEndEntitySet = 100, /// <summary>An end element was not given, and cannot be inferred because too many EntityContainerEntitySet elements that are good possibilities.</summary> AmbiguousEntityContainerEnd = 101, /// <summary>An end element was not given, and cannot be infered because there is no EntityContainerEntitySets that are the correct type to be used as an EntitySet.</summary> MissingExtentEntityContainerEnd = 102, // unused 103, // unused 104, // unused 105, /// <summary>Not a valid parameter direction for the parameter in a function</summary> BadParameterDirection = 106, /// <summary>Unable to infer an optional schema part, to resolve this, be more explicit</summary> FailedInference = 107, // unused = 108, /// <summary> Invalid facet attribute(s) specified in provider manifest</summary> InvalidFacetInProviderManifest = 109, /// <summary> Invalid role value in the relationship constraint</summary> InvalidRoleInRelationshipConstraint = 110, /// <summary> Invalid Property in relationship constraint</summary> InvalidPropertyInRelationshipConstraint = 111, /// <summary> Type mismatch between ToProperty and FromProperty in the relationship constraint</summary> TypeMismatchRelationshipConstaint = 112, /// <summary> Invalid multiplicty in FromRole in the relationship constraint</summary> InvalidMultiplicityInRoleInRelationshipConstraint = 113, /// <summary> The number of properties in the FromProperty and ToProperty in the relationship constraint must be identical</summary> MismatchNumberOfPropertiesInRelationshipConstraint = 114, /// <summary> No Properties defined in either FromProperty or ToProperty in the relationship constraint</summary> MissingPropertyInRelationshipConstraint = 115, /// <summary> Missing constraint in relationship type in ssdl</summary> MissingConstraintOnRelationshipType = 116, // unused 117, // unused 118, /// <summary> Same role referred in the ToRole and FromRole of a referential constraint </summary> SameRoleReferredInReferentialConstraint = 119, /// <summary> Invalid value for attribute ParameterTypeSemantics </summary> InvalidValueForParameterTypeSemantics = 120, /// <summary> Invalid type used for a Relationship End Type</summary> InvalidRelationshipEndType = 121, /// <summary> Invalid PrimitiveTypeKind</summary> InvalidPrimitiveTypeKind = 122, // unused 123, /// <summary> Invalid TypeConversion DestinationType</summary> InvalidTypeConversionDestinationType = 124, /// <summary>Expected a integer value between 0 - 255</summary> ByteValueExpected = 125, /// <summary> Invalid Type specified in function</summary> FunctionWithNonPrimitiveTypeNotSupported = 126, /// <summary> Precision must not be greater than 28 </summary> PrecisionMoreThanAllowedMax = 127, /// <summary> Properties that are part of entity key must be of scalar type</summary> EntityKeyMustBeScalar = 128, /// <summary> Binary and spatial type properties which are part of entity key are currently not supported </summary> EntityKeyTypeCurrentlyNotSupported = 129, /// <summary>The primitive type kind does not have a prefered mapping</summary> NoPreferredMappingForPrimitiveTypeKind = 130, /// <summary>More than one PreferredMapping for a PrimitiveTypeKind</summary> TooManyPreferredMappingsForPrimitiveTypeKind = 131, /// <summary>End with * multiplicity cannot have operations specified</summary> EndWithManyMultiplicityCannotHaveOperationsSpecified = 132, /// <summary>EntitySet type has no keys</summary> EntitySetTypeHasNoKeys = 133, /// <summary>InvalidNumberOfParametersForAggregateFunction</summary> InvalidNumberOfParametersForAggregateFunction = 134, /// <summary>InvalidParameterTypeForAggregateFunction</summary> InvalidParameterTypeForAggregateFunction = 135, /// <summary>Composable functions and function imports must declare a return type.</summary> ComposableFunctionOrFunctionImportWithoutReturnType = 136, /// <summary>Non-composable functions must not declare a return type.</summary> NonComposableFunctionWithReturnType = 137, /// <summary>Non-composable functions do not permit the aggregate, niladic, or built-in attributes.</summary> NonComposableFunctionAttributesNotValid = 138, /// <summary>Composable functions can not include command text attribute.</summary> ComposableFunctionWithCommandText = 139, /// <summary>Functions should not declare both a store name and command text (only one or the other /// can be used).</summary> FunctionDeclaresCommandTextAndStoreFunctionName = 140, /// <summary>SystemNamespace</summary> SystemNamespace = 141, /// <summary>Empty DefiningQuery text</summary> EmptyDefiningQuery = 142, /// <summary>Schema, Table and DefiningQuery are all specified, and are mutualy exlusive</summary> TableAndSchemaAreMutuallyExclusiveWithDefiningQuery = 143, // unused 144, /// <summary>Conurency can't change for any sub types of an EntitySet type.</summary> ConcurrencyRedefinedOnSubTypeOfEntitySetType = 145, /// <summary>Function import return type must be either empty, a collection of entities, or a singleton scalar.</summary> FunctionImportUnsupportedReturnType = 146, /// <summary>Function import specifies a non-existent entity set.</summary> FunctionImportUnknownEntitySet = 147, /// <summary>Function import specifies entity type return but no entity set.</summary> FunctionImportReturnsEntitiesButDoesNotSpecifyEntitySet = 148, /// <summary>Function import specifies entity type that does not derive from element type of entity set.</summary> FunctionImportEntityTypeDoesNotMatchEntitySet = 149, /// <summary>Function import specifies a binding to an entity set but does not return entities.</summary> FunctionImportSpecifiesEntitySetButDoesNotReturnEntityType = 150, /// <summary>InternalError</summary> InternalError = 152, /// <summary>Same Entity Set Taking part in the same role of the relationship set in two different relationship sets</summary> SimilarRelationshipEnd = 153, /// <summary> Entity key refers to the same property twice</summary> DuplicatePropertySpecifiedInEntityKey = 154, /// <summary> Function declares a ReturnType attribute and element</summary> AmbiguousFunctionReturnType = 156, /// <summary> Nullable Complex Type not supported in Edm V1</summary> NullableComplexType = 157, /// <summary> Only Complex Collections supported in Edm V1.1</summary> NonComplexCollections = 158, /// <summary>No Key defined on Entity Type </summary> KeyMissingOnEntityType = 159, /// <summary> Invalid namespace specified in using element</summary> InvalidNamespaceInUsing = 160, /// <summary> Need not specify system namespace in using </summary> NeedNotUseSystemNamespaceInUsing = 161, /// <summary> Cannot use a reserved/system namespace as alias </summary> CannotUseSystemNamespaceAsAlias = 162, /// <summary> Invalid qualification specified for type </summary> InvalidNamespaceName = 163, /// <summary> Invalid Entity Container Name in extends attribute </summary> InvalidEntityContainerNameInExtends = 164, // unused 165, /// <summary> Must specify namespace or alias of the schema in which this type is defined </summary> InvalidNamespaceOrAliasSpecified = 166, /// <summary> Entity Container cannot extend itself </summary> EntityContainerCannotExtendItself = 167, /// <summary> Failed to retrieve provider manifest </summary> FailedToRetrieveProviderManifest = 168, /// <summary> Mismatched Provider Manifest token values in SSDL artifacts </summary> ProviderManifestTokenMismatch = 169, /// <summary> Missing Provider Manifest token value in SSDL artifact(s) </summary> ProviderManifestTokenNotFound = 170, /// <summary>Empty CommandText element</summary> EmptyCommandText = 171, /// <summary> Inconsistent Provider values in SSDL artifacts </summary> InconsistentProvider = 172, /// <summary> Inconsistent Provider Manifest token values in SSDL artifacts </summary> InconsistentProviderManifestToken = 173, /// <summary> Duplicated Function overloads </summary> DuplicatedFunctionoverloads = 174, /// <summary>InvalidProvider</summary> InvalidProvider = 175, /// <summary>FunctionWithNonEdmTypeNotSupported</summary> FunctionWithNonEdmTypeNotSupported = 176, /// <summary>ComplexTypeAsReturnTypeAndDefinedEntitySet</summary> ComplexTypeAsReturnTypeAndDefinedEntitySet = 177, /// <summary>ComplexTypeAsReturnTypeAndDefinedEntitySet</summary> ComplexTypeAsReturnTypeAndNestedComplexProperty = 178, // unused = 179, /// <summary>A function import can be either composable or side-effecting, but not both.</summary> FunctionImportComposableAndSideEffectingNotAllowed = 180, /// <summary>A function import can specify an entity set or an entity set path, but not both.</summary> FunctionImportEntitySetAndEntitySetPathDeclared = 181, /// <summary>In model functions facet attribute is allowed only on ScalarTypes</summary> FacetOnNonScalarType = 182, /// <summary>Captures several conditions where facets are placed on element where it should not exist.</summary> IncorrectlyPlacedFacet = 183, /// <summary>Return type has not been declared</summary> ReturnTypeNotDeclared = 184, TypeNotDeclared = 185, RowTypeWithoutProperty = 186, ReturnTypeDeclaredAsAttributeAndElement = 187, TypeDeclaredAsAttributeAndElement = 188, ReferenceToNonEntityType = 189, /// <summary>Collection and reference type parameters are not allowed in function imports.</summary> FunctionImportCollectionAndRefParametersNotAllowed = 190, IncompatibleSchemaVersion = 191, /// <summary> The structural annotation cannot use codegen namespaces </summary> NoCodeGenNamespaceInStructuralAnnotation = 192, /// <summary> Function and type cannot have the same fully qualified name</summary> AmbiguousFunctionAndType = 193, /// <summary> Cannot load different version of schema in the same ItemCollection</summary> CannotLoadDifferentVersionOfSchemaInTheSameItemCollection = 194, /// <summary> Expected bool value</summary> BoolValueExpected = 195, /// <summary> End without Multiplicity specified</summary> EndWithoutMultiplicity = 196, /// <summary>In SSDL, if composable function returns a collection of rows (TVF), all row properties must be of scalar types.</summary> TVFReturnTypeRowHasNonScalarProperty = 197, // FunctionUnknownEntityContainer = 198, // FunctionEntityContainerMustBeSpecified = 199, // FunctionUnknownEntitySet = 200, /// <summary>Only nullable parameters are supported in function imports.</summary> FunctionImportNonNullableParametersNotAllowed = 201, /// <summary>Defining expression and entity set can not be specified at the same time.</summary> FunctionWithDefiningExpressionAndEntitySetNotAllowed = 202, /// <summary>Function specifies return type that does not derive from element type of entity set.</summary> FunctionEntityTypeScopeDoesNotMatchReturnType = 203, /// <summary>The specified type cannot be used as the underlying type of Enum type.</summary> InvalidEnumUnderlyingType = 204, /// <summary>Duplicate enumeration member.</summary> DuplicateEnumMember = 205, /// <summary>The calculated value for an enum member is ouf of Int64 range.</summary> CalculatedEnumValueOutOfRange = 206, /// <summary>The enumeration value for an enum member is out of its underlying type range.</summary> EnumMemberValueOutOfItsUnderylingTypeRange = 207, /// <summary>The Srid value is out of range.</summary> InvalidSystemReferenceId = 208, /// <summary>A CSDL spatial type in a file without the UseSpatialUnionType annotation</summary> UnexpectedSpatialType = 209, } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Toucan.Sample.Data; namespace Toucan.Sample.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20901"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Toucan.Sample.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("Toucan.Sample.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("Toucan.Sample.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Toucan.Sample.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Services.Connectors { public class PresenceServicesConnector : IPresenceService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public PresenceServicesConnector() { } public PresenceServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public PresenceServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig == null) { m_log.Error("[PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini"); throw new Exception("Presence connector init error"); } string serviceURI = gridConfig.GetString("PresenceServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[PRESENCE CONNECTOR]: No Server URI named in section PresenceService"); throw new Exception("Presence connector init error"); } m_ServerURI = serviceURI; } #region IPresenceService public PresenceInfo GetAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagent"; sendData["SessionID"] = sessionID.ToString(); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); PresenceInfo pinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { pinfo = new PresenceInfo((Dictionary<string, object>)replyData["result"]); } } return pinfo; } public PresenceInfo[] GetAgents(string[] userIDs) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagents"; sendData["uuids"] = new List<string>(userIDs); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; //m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } List<PresenceInfo> rinfos = new List<PresenceInfo>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure")) { return new PresenceInfo[0]; } Dictionary<string, object>.ValueCollection pinfosList = replyData.Values; //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object presence in pinfosList) { if (presence is Dictionary<string, object>) { PresenceInfo pinfo = new PresenceInfo((Dictionary<string, object>)presence); rinfos.Add(pinfo); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received invalid response type {0}", presence.GetType()); } } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null response"); return rinfos.ToArray(); } public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "login"; sendData["UserID"] = userID; sendData["SessionID"] = sessionID.ToString(); sendData["SecureSessionID"] = secureSessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool LogoutAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logout"; sendData["SessionID"] = sessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool LogoutRegionAgents(UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logoutregion"; sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool ReportAgent(UUID sessionID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "report"; sendData["SessionID"] = sessionID.ToString(); sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } #endregion IPresenceService } }
#region WatiN Copyright (C) 2006-2009 Jeroen van Menen //Copyright 2006-2009 Jeroen van Menen // // 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 Copyright using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using WatiN.Core.Constraints; using WatiN.Core.Exceptions; using WatiN.Core.Interfaces; using WatiN.Core.Logging; using WatiN.Core.Native; //using WatiN.Core.Native.InternetExplorer; //using WatiN.Core.Native.Windows; using WatiN.Core.UtilityClasses; namespace WatiN.Core { public abstract class Browser : DomContainer { private static readonly Dictionary<Type, IAttachTo> AttachToHelpers = new Dictionary<Type, IAttachTo>(); static Browser() { // RegisterAttachToHelper(typeof (IE), new AttachToIeHelper()); } public abstract INativeBrowser NativeBrowser { get; } /// <summary> /// Brings the referenced Internet Explorer to the front (makes it the top window) /// </summary> // public virtual void BringToFront() // { // if (NativeMethods.GetForegroundWindow() == hWnd) return; // // var result = NativeMethods.SetForegroundWindow(hWnd); // // if (!result) // { // Logger.LogAction("Failed to set Firefox as the foreground window."); // } // } /// <summary> /// Gets the window style. /// </summary> /// <returns>The style currently applied to the ie window.</returns> // public virtual NativeMethods.WindowShowStyle GetWindowStyle() // { // var placement = new WINDOWPLACEMENT(); // placement.length = Marshal.SizeOf(placement); // // NativeMethods.GetWindowPlacement(hWnd, ref placement); // // return (NativeMethods.WindowShowStyle)placement.showCmd; // } /// <summary> /// Make the referenced Internet Explorer full screen, minimized, maximized and more. /// </summary> /// <param name="showStyle">The style to apply.</param> // public virtual void ShowWindow(NativeMethods.WindowShowStyle showStyle) // { // NativeMethods.ShowWindow(hWnd, (int) showStyle); // } /// <summary> /// Sends a Tab key to the IE window to simulate tabbing through /// the elements (and adres bar). /// </summary> public virtual void PressTab() { // if (Debugger.IsAttached) return; // // var currentStyle = GetWindowStyle(); // // ShowWindow(NativeMethods.WindowShowStyle.Restore); // BringToFront(); // // var intThreadIDIE = ProcessID; // var intCurrentThreadID = NativeMethods.GetCurrentThreadId(); // // NativeMethods.AttachThreadInput(intCurrentThreadID, intThreadIDIE, true); // // NativeMethods.keybd_event(NativeMethods.KEYEVENTF_TAB, 0x45, NativeMethods.KEYEVENTF_EXTENDEDKEY, 0); // NativeMethods.keybd_event(NativeMethods.KEYEVENTF_TAB, 0x45, NativeMethods.KEYEVENTF_EXTENDEDKEY | NativeMethods.KEYEVENTF_KEYUP, 0); // // NativeMethods.AttachThreadInput(intCurrentThreadID, intThreadIDIE, false); // // ShowWindow(currentStyle); } /// <summary> /// Navigates Internet Explorer to the given <paramref name="url" />. /// </summary> /// <param name="url">The URL specified as a wel formed Uri.</param> /// <example> /// The following example creates an Uri and Internet Explorer instance and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// using System; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// Uri URL = new Uri("http://watin.sourceforge.net"); /// IE ie = new IE(); /// ie.GoTo(URL); /// } /// } /// } /// </code> /// </example> public virtual void GoTo(Uri url) { Logger.LogAction("Navigating to '" + url.AbsoluteUri + "'"); NativeBrowser.NavigateTo(url); WaitForComplete(); } /// <summary> /// Navigates the browser to the given <paramref name="url" /> /// without waiting for the page load to be finished. /// </summary> /// <param name="url">The URL to GoTo.</param> /// <example> /// The following example creates a new Internet Explorer instance and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE(); /// ie.GoToNoWait("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public virtual void GoToNoWait(string url) { GoToNoWait(UtilityClass.CreateUri(url)); } /// <summary> /// Navigates the browser to the given <paramref name="url" /> /// without waiting for the page load to be finished. /// </summary> /// <param name="url">The URL to GoTo.</param> /// <example> /// The following example creates a new Internet Explorer instance and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// Uri URL = new Uri("http://watin.sourceforge.net"); /// IE ie = new IE(); /// ie.GoToNoWait(URL); /// } /// } /// } /// </code> /// </example> public virtual void GoToNoWait(Uri url) { NativeBrowser.NavigateToNoWait(url); } /// <summary> /// Navigates Internet Explorer to the given <paramref name="url" />. /// </summary> /// <param name="url">The URL to GoTo.</param> /// <example> /// The following example creates a new Internet Explorer instance and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE(); /// ie.GoTo("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public virtual void GoTo(string url) { GoTo(UtilityClass.CreateUri(url)); } /// <summary> /// Navigates the browser back to the previously displayed Url (like the back /// button in Internet Explorer). /// </summary> /// <returns><c>true</c> if navigating back to a previous url was possible, otherwise <c>false</c></returns> public virtual bool Back() { var succeeded = NativeBrowser.GoBack(); if (succeeded) { WaitForComplete(); Logger.LogAction("Navigated Back to '" + Url + "'"); } else { Logger.LogAction("No history available, didn't navigate Back."); } return succeeded; } /// <summary> /// Navigates the browser forward to the next displayed Url (like the forward /// button in Internet Explorer). /// </summary> /// <returns><c>true</c> if navigating forward to a previous url was possible, otherwise <c>false</c></returns> public virtual bool Forward() { var succeeded = NativeBrowser.GoForward(); if (succeeded) { WaitForComplete(); Logger.LogAction("Navigated Forward to '" + Url + "'"); } else { Logger.LogAction("No forward history available, didn't navigate Forward."); } return succeeded; } /// <summary> /// Closes and then reopens the browser with a blank page. /// </summary> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge and then reopens the browser. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE(new Uri("http://watin.sourceforge.net"), logon); /// ie.Reopen(); /// } /// } /// } /// </code> /// </example> public virtual void Reopen() { Logger.LogAction("Reopening browser (closing current and creating new instance)"); NativeBrowser.Reopen(); WaitForComplete(); } /// <summary> /// Reloads the currently displayed webpage (like the Refresh/reload button in /// a browser). /// </summary> public virtual void Refresh() { Logger.LogAction("Refreshing browser from '" + Url + "'"); NativeBrowser.Refresh(); WaitForComplete(); } /// <summary> /// Closes the browser. /// </summary> public abstract void Close(); //public override IntPtr hWnd //{ // get { return NativeBrowser.hWnd; } // } /// <inheritdoc /> public override INativeDocument OnGetNativeDocument() { return NativeBrowser.NativeDocument; } /// <inheritdoc /> protected override string GetAttributeValueImpl(string attributeName) { var name = attributeName.ToLowerInvariant(); string value = null; if (name.Equals("href")) { UtilityClass.TryActionIgnoreException(() => value = Url); } else if (name.Equals("title")) { UtilityClass.TryActionIgnoreException(() => value = Title); } //else if (name.Equals("hwnd")) //{ // UtilityClass.TryActionIgnoreException(() => value = hWnd.ToString()); //} else { throw new InvalidAttributeException(attributeName, "IE"); } return value; } public static T AttachTo<T>(Constraint constraint) where T : Browser { return AttachTo<T>(constraint, Settings.AttachToIETimeOut); } public static T AttachTo<T>(Constraint constraint, int timeout) where T : Browser { var helper = CreateHelper<T>(); return (T) helper.Find(constraint, timeout, true); } public static T AttachToNoWait<T>(Constraint constraint) where T : Browser { return AttachToNoWait<T>(constraint, Settings.AttachToIETimeOut); } public static T AttachToNoWait<T>(Constraint constraint, int timeout) where T : Browser { var helper = CreateHelper<T>(); return (T) helper.Find(constraint, timeout, false); } public static bool Exists<T>(Constraint constraint) where T : Browser { var helper = CreateHelper<T>(); return helper.Exists(constraint); } private static IAttachTo CreateHelper<T>() where T : Browser { if (!AttachToHelpers.ContainsKey(typeof(T))) throw new WatiNException("No AttachToHelper registered for type " + typeof(T)); return AttachToHelpers[typeof (T)]; } public static void RegisterAttachToHelper(Type browserType, IAttachTo attachToHelper) { AttachToHelpers.Add(browserType, attachToHelper); } } }
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 _2016MT45WebApi.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; } } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Diagnostics; using System.Text; using System.Threading; using Belikov.GenuineChannels.Logbook; namespace Belikov.GenuineChannels.Utilities { /// <summary> /// Implements a custom thread pool logic. /// All methods and properties are thread-safe. /// </summary> public class GenuineThreadPool { /// <summary> /// To prevent creating instances of the GenuineThreadPool class. /// </summary> private GenuineThreadPool() { } /// <summary> /// Gets or sets the minimum number of threads in the ThreadPool since that /// GenuineThreadPool will create threads. /// </summary> public static int ThreadPoolAvailableThreads { get { lock(_threadPoolAvailableThreadsLock) return _threadPoolAvailableThreads; } set { lock(_threadPoolAvailableThreadsLock) _threadPoolAvailableThreads = value; } } private static int _threadPoolAvailableThreads = 12; private static object _threadPoolAvailableThreadsLock = new object(); /// <summary> /// The maximum number of allowed threads held by GenuineThreadPool. /// </summary> public static int MaximumThreads { get { lock(_maximumThreadsLock) return _maximumThreads; } set { lock(_maximumThreadsLock) _maximumThreads = value; } } private static int _maximumThreads = 500; private static object _maximumThreadsLock = new object(); /// <summary> /// Working threads will be terminated after this time of inactiviy. /// </summary> public static TimeSpan CloseAfterInactivity { get { lock(_closeAfterInactivityLock) return _closeAfterInactivity; } set { lock(_closeAfterInactivityLock) _closeAfterInactivity = value; } } private static TimeSpan _closeAfterInactivity = TimeSpan.FromMinutes(4); private static object _closeAfterInactivityLock = new object(); /// <summary> /// Gets or sets an indication of whether GenuineThreadPool will use ThreadPool.UnsafeQueueUserWorkItem /// while working with the native ThreadPool. /// </summary> public static bool UnsafeQueuing { get { lock(_unsafeQueuingLock) return _unsafeQueuing; } set { lock(_unsafeQueuingLock) _unsafeQueuing = value; } } private static bool _unsafeQueuing = true; private static object _unsafeQueuingLock = new object(); /// <summary> /// Represents an integer value indicating the maximum allowed number of queued requests if the number of the Genuine Thread /// Pool's threads has exceeded GenuineThreadPool.MaximumThreads. /// </summary> public static int MaximumRequestsQueued { get { lock(_unsafeQueuingLock) return _maximumRequestsQueued; } set { lock(_unsafeQueuingLock) _maximumRequestsQueued = value; } } private static int _maximumRequestsQueued = 500; /// <summary> /// Represents a boolean value indicating whether requests may be queued when the number of the Genuine Thread /// Pool's threads is close to GenuineThreadPool.MaximumThreads. /// </summary> public static bool AllowRequestQueuing { get { lock(_unsafeQueuingLock) return _allowRequestQueuing; } set { lock(_unsafeQueuingLock) _allowRequestQueuing = value; } } private static bool _allowRequestQueuing = true; /// <summary> /// Queued requests. /// </summary> internal static Queue _requestsQueued = new Queue(); /// <summary> /// Work threads. /// </summary> private static ArrayList _threads = new ArrayList(); /// <summary> /// A lock for accessing the thread array and each thread structure. /// </summary> private static object _threadsLock = new object(); /// <summary> /// Specifies the Thread Pool Strategy used by Genuine Channels solution. /// </summary> public static GenuineThreadPoolStrategy GenuineThreadPoolStrategy { get { lock (_genuineThreadPoolStrategyLock) return _genuineThreadPoolStrategy; } set { lock (_genuineThreadPoolStrategyLock) _genuineThreadPoolStrategy = value; } } private static GenuineThreadPoolStrategy _genuineThreadPoolStrategy = GenuineThreadPoolStrategy.AlwaysThreads; private static object _genuineThreadPoolStrategyLock = new object(); /// <summary> /// This variable contains the total number of attempts to queue a task through GenuineThreadPool. /// It is used to monitor the number of threads to the log file. /// </summary> private static int _QueueUserWorkItem_OperationNumber = 0; /// <summary> /// Queues a user work item to the thread pool. /// </summary> /// <param name="callback">A WaitCallback representing the method to execute.</param> /// <param name="state">An object containing data to be used by the method.</param> /// <param name="longDuration">Indicates whether the item depends on other working threads or can take a long period to finish.</param> public static void QueueUserWorkItem(WaitCallback callback, object state, bool longDuration) { GenuineThreadPoolStrategy theStrategy = GenuineThreadPool.GenuineThreadPoolStrategy; if (callback == null) throw new NullReferenceException("callback"); CustomThreadInfo customThreadInfo = null; lock(_threadsLock) { BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter; if (binaryLogWriter != null && binaryLogWriter[LogCategory.StatisticCounters] > 0 && (Interlocked.Increment(ref _QueueUserWorkItem_OperationNumber) % GenuineThreadPool.ThreadStatisticFrequency) == 0) { binaryLogWriter.WriteEvent(LogCategory.StatisticCounters, "GenuineThreadPool.QueueUserWorkItem", LogMessageType.ThreadPoolUsage, null, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, _QueueUserWorkItem_OperationNumber, GenuineThreadPool._threads.Count, 0, null, null, null, null, "GenuineThreadPool has received a request #{0} (object \"{1}\" entry \"{2}\"). The current number of working threads: {3}. ThreadPoolAvailableThreads: {4}. MaximumThreads: {5}. CloseAfterInactivity: {6}. UnsafeQueuing: {7}. GenuineThreadPoolStrategy: {8}.", _QueueUserWorkItem_OperationNumber, callback.Method.ReflectedType.ToString(), callback.Method.ToString(), GenuineThreadPool._threads.Count, GenuineThreadPool.ThreadPoolAvailableThreads, GenuineThreadPool.MaximumThreads, GenuineThreadPool.CloseAfterInactivity.TotalMilliseconds, GenuineThreadPool.UnsafeQueuing, Enum.Format(typeof(GenuineThreadPoolStrategy), GenuineThreadPool.GenuineThreadPoolStrategy, "g") ); } if ( !( theStrategy == GenuineThreadPoolStrategy.AlwaysThreads || (theStrategy == GenuineThreadPoolStrategy.OnlyLongDuration && longDuration ) ) ) { // try to use native ThreadPool if it's possible int workerThreads = 0; int completionPortThreads = 0; if (theStrategy == GenuineThreadPoolStrategy.SwitchAfterExhaustion) ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); if (theStrategy == GenuineThreadPoolStrategy.AlwaysNative || theStrategy == GenuineThreadPoolStrategy.OnlyLongDuration || (Math.Min(workerThreads, completionPortThreads) >= GenuineThreadPool.ThreadPoolAvailableThreads && theStrategy == GenuineThreadPoolStrategy.SwitchAfterExhaustion) ) { if (GenuineThreadPool.UnsafeQueuing) ThreadPool.UnsafeQueueUserWorkItem(callback, state); else ThreadPool.QueueUserWorkItem(callback, state); return ; } } // look for an available worker thread for ( int i = 0; i < _threads.Count; ) { // get the next thread customThreadInfo = (CustomThreadInfo) _threads[i]; // check if it's alive if (! customThreadInfo.IsAlive) { _threads.RemoveAt(i); customThreadInfo = null; continue; } if (customThreadInfo.IsIdle) break; customThreadInfo = null; i++; } // if the limit is exceeded if (customThreadInfo == null && _threads.Count >= GenuineThreadPool.MaximumThreads) { if (GenuineThreadPool.AllowRequestQueuing) { _requestsQueued.Enqueue( new GenuineThreadPoolWorkItem(callback, state) ); return ; } else throw GenuineExceptions.Get_Processing_ThreadPoolLimitExceeded(); } // create a new one, if it's necessary if (customThreadInfo == null) { customThreadInfo = new CustomThreadInfo(_threadsLock); _threads.Add(customThreadInfo); } // give out the work customThreadInfo.WorkCallback = callback; customThreadInfo.CallbackState = state; customThreadInfo.IsIdle = false; customThreadInfo.ManualResetEvent.Set(); } } /// <summary> /// Gets a request from the queue or a null reference if the queue is empty. /// </summary> /// <returns>The request or a null reference.</returns> internal static GenuineThreadPoolWorkItem GetQueuedRequestIfPossible() { lock(_threadsLock) { if (_requestsQueued.Count > 0) return (GenuineThreadPoolWorkItem) _requestsQueued.Dequeue(); } return null; } #region -- Debugging Stuff ----------------------------------------------------------------- /// <summary> /// Gets or sets an integer value that determines how often Genuine Thread Pool will write log records describing the /// current state and tasks performed. 1 means that each GenuineThreadPool.QueueUserWorkItem will be saved in the log. /// 10 means that every 10th request will be indicated in the log file. /// </summary> public static int ThreadStatisticFrequency { get { lock (_threadStatisticFrequencyLock) return _threadStatisticFrequency; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); lock (_threadStatisticFrequencyLock) _threadStatisticFrequency = value; } } private static int _threadStatisticFrequency = 50; private static object _threadStatisticFrequencyLock = new object(); /// <summary> /// Returns a string containing the list of active threads and their tasks. /// It is not recommended to invoke this method very often. /// </summary> /// <returns>A string containing the list of active threads and their tasks.</returns> public static string TakeSnapshot() { StringBuilder threadList = new StringBuilder(); lock (_threadsLock) { // look for an available worker thread for ( int i = 0; i < _threads.Count; i++ ) { // get the next thread CustomThreadInfo customThreadInfo = (CustomThreadInfo) _threads[i]; // check if it's alive if (! customThreadInfo.IsAlive) continue; if (customThreadInfo.IsIdle) continue; threadList.AppendFormat("Thread {0} executes \"{1}\" entry \"{2}\".{3}", customThreadInfo.Thread.Name, customThreadInfo.WorkCallback.Method.ReflectedType.ToString(), customThreadInfo.WorkCallback.Method.ToString(), Environment.NewLine); } } return threadList.ToString(); } /// <summary> /// Calculates and returns the number of occupied threads. /// It is not recommended to invoke this method very often. /// </summary> /// <returns>The number of occupied threads.</returns> public static int CalculateOccupiedThreads() { int threadsOccupied = 0; lock (_threadsLock) { // look for an available worker thread for ( int i = 0; i < _threads.Count; i++ ) { CustomThreadInfo customThreadInfo = (CustomThreadInfo) _threads[i]; if ( ! (customThreadInfo.IsIdle || ! customThreadInfo.IsAlive) ) threadsOccupied++; } } return threadsOccupied; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using NUnit.Framework; using NUnit.Framework.Constraints; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Tests.Common; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace OpenSim.Data.Tests { public static class Constraints { //This is here because C# has a gap in the language, you can't infer type from a constructor public static PropertyCompareConstraint<T> PropertyCompareConstraint<T>(T expected) { return new PropertyCompareConstraint<T>(expected); } } public class PropertyCompareConstraint<T> : NUnit.Framework.Constraints.Constraint { private readonly object _expected; //the reason everywhere uses propertyNames.Reverse().ToArray() is because the stack is backwards of the order we want to display the properties in. private string failingPropertyName = string.Empty; private object failingExpected; private object failingActual; public PropertyCompareConstraint(T expected) { _expected = expected; } public override bool Matches(object actual) { return ObjectCompare(_expected, actual, new Stack<string>()); } private bool ObjectCompare(object expected, object actual, Stack<string> propertyNames) { //If they are both null, they are equal if (actual == null && expected == null) return true; //If only one is null, then they aren't if (actual == null || expected == null) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } //prevent loops... if (propertyNames.Count > 50) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } if (actual.GetType() != expected.GetType()) { propertyNames.Push("GetType()"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actual.GetType(); failingExpected = expected.GetType(); return false; } if (actual.GetType() == typeof(Color)) { Color actualColor = (Color)actual; Color expectedColor = (Color)expected; if (actualColor.R != expectedColor.R) { propertyNames.Push("R"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.R; failingExpected = expectedColor.R; return false; } if (actualColor.G != expectedColor.G) { propertyNames.Push("G"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.G; failingExpected = expectedColor.G; return false; } if (actualColor.B != expectedColor.B) { propertyNames.Push("B"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.B; failingExpected = expectedColor.B; return false; } if (actualColor.A != expectedColor.A) { propertyNames.Push("A"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.A; failingExpected = expectedColor.A; return false; } return true; } IComparable comp = actual as IComparable; if (comp != null) { if (comp.CompareTo(expected) != 0) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } return true; } //Now try the much more annoying IComparable<T> Type icomparableInterface = actual.GetType().GetInterface("IComparable`1"); if (icomparableInterface != null) { int result = (int)icomparableInterface.GetMethod("CompareTo").Invoke(actual, new[] { expected }); if (result != 0) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } return true; } IEnumerable arr = actual as IEnumerable; if (arr != null) { List<object> actualList = arr.Cast<object>().ToList(); List<object> expectedList = ((IEnumerable)expected).Cast<object>().ToList(); if (actualList.Count != expectedList.Count) { propertyNames.Push("Count"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actualList.Count; failingExpected = expectedList.Count; propertyNames.Pop(); return false; } //actualList and expectedList should be the same size. for (int i = 0; i < actualList.Count; i++) { propertyNames.Push("[" + i + "]"); if (!ObjectCompare(expectedList[i], actualList[i], propertyNames)) return false; propertyNames.Pop(); } //Everything seems okay... return true; } //Skip static properties. I had a nasty problem comparing colors because of all of the public static colors. PropertyInfo[] properties = expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (ignores.Contains(property.Name)) continue; object actualValue = property.GetValue(actual, null); object expectedValue = property.GetValue(expected, null); propertyNames.Push(property.Name); if (!ObjectCompare(expectedValue, actualValue, propertyNames)) return false; propertyNames.Pop(); } return true; } public override void WriteDescriptionTo(MessageWriter writer) { writer.WriteExpectedValue(failingExpected); } public override void WriteActualValueTo(MessageWriter writer) { writer.WriteActualValue(failingActual); writer.WriteLine(); writer.Write(" On Property: " + failingPropertyName); } //These notes assume the lambda: (x=>x.Parent.Value) //ignores should really contain like a fully dotted version of the property name, but I'm starting with small steps private readonly List<string> ignores = new List<string>(); public PropertyCompareConstraint<T> IgnoreProperty(Expression<Func<T, object>> func) { Expression express = func.Body; PullApartExpression(express); return this; } private void PullApartExpression(Expression express) { //This deals with any casts... like implicit casts to object. Not all UnaryExpression are casts, but this is a first attempt. if (express is UnaryExpression) PullApartExpression(((UnaryExpression)express).Operand); if (express is MemberExpression) { //If the inside of the lambda is the access to x, we've hit the end of the chain. // We should track by the fully scoped parameter name, but this is the first rev of doing this. ignores.Add(((MemberExpression)express).Member.Name); } } } [TestFixture] public class PropertyCompareConstraintTest : OpenSimTestCase { public class HasInt { public int TheValue { get; set; } } [Test] public void IntShouldMatch() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 5 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void IntShouldNotMatch() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 4 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void IntShouldIgnore() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 4 }; var constraint = Constraints.PropertyCompareConstraint(expected).IgnoreProperty(x => x.TheValue); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void AssetShouldMatch() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); AssetBase expected = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void AssetShouldNotMatch() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); AssetBase expected = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void AssetShouldNotMatch2() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, UUID.Zero.ToString()); AssetBase expected = new AssetBase(uuid1, "asset two", (sbyte)AssetType.Texture, UUID.Zero.ToString()); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void UUIDShouldMatch() { UUID uuid1 = UUID.Random(); UUID uuid2 = UUID.Parse(uuid1.ToString()); var constraint = Constraints.PropertyCompareConstraint(uuid1); Assert.That(constraint.Matches(uuid2), Is.True); } [Test] public void UUIDShouldNotMatch() { UUID uuid1 = UUID.Random(); UUID uuid2 = UUID.Random(); var constraint = Constraints.PropertyCompareConstraint(uuid1); Assert.That(constraint.Matches(uuid2), Is.False); } [Test] public void TestColors() { Color actual = Color.Red; Color expected = Color.FromArgb(actual.A, actual.R, actual.G, actual.B); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void ShouldCompareLists() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2, 3 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void ShouldFailToCompareListsThatAreDifferent() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2, 4 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void ShouldFailToCompareListsThatAreDifferentLengths() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } public class Recursive { public Recursive Other { get; set; } } [Test] public void ErrorsOutOnRecursive() { Recursive parent = new Recursive(); Recursive child = new Recursive(); parent.Other = child; child.Other = parent; var constraint = Constraints.PropertyCompareConstraint(child); Assert.That(constraint.Matches(child), Is.False); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Microsoft.Deployment.WindowsInstaller; namespace WixSharp { /// <summary> /// Defines System.Windows.Forms.<see cref="T:System.Windows.Forms.Form" />, which is to be used as the for custom MSI dialog. /// <para> /// As opposite to the WixSharp.<see cref="T:WixSharp.WixForm" /> based custom dialogs <c>WixCLRDialog</c> is instantiated not at /// compile but at run time. Thus it is possible to implement comprehensive deployment algorithms in any of the available Form event handlers. /// </para> /// <para> /// The usual usability scenario is the injection of the managed Custom Action (for displaying the <c>WixCLRDialog</c>) /// into the sequence of the standard dialogs (WixSharp.<see cref="T:WixSharp.CustomUI"/>). /// </para> /// <para> /// While it is possible to construct <see cref="T:WixSharp.CustomUI"/> instance manually it is preferred to use /// Factory methods of <see cref="T:WixSharp.CustomUIBuilder"/> (e.g. InjectPostLicenseClrDialog) for this. /// </para> /// <code> /// static public void Main() /// { /// ManagedAction showDialog; /// /// var project = new Project("CustomDialogTest", /// showDialog = new ShowClrDialogAction("ShowProductActivationDialog")); /// /// project.UI = WUI.WixUI_Common; /// project.CustomUI = CustomUIBuilder.InjectPostLicenseClrDialog(showDialog.Id, " LicenseAccepted = \"1\""); /// /// Compiler.BuildMsi(project); /// } /// ... /// public class CustomActions /// { /// [CustomAction] /// public static ActionResult ShowProductActivationDialog(Session session) /// { /// return WixCLRDialog.ShowAsMsiDialog(new CustomDialog(session)); /// } /// } /// ... /// public partial class CustomDialog : WixCLRDialog /// { /// private GroupBox groupBox1; /// private Button cancelBtn; /// ... /// </code> /// <para> /// The all communications with the installation in progress are to be done by modifying the MSI properties or executing MSI actions /// via <c>Session</c> object.</para> /// <para> /// When closing the dialog make sure you set the DeialogResul properly. <c>WixCLRDialog</c> offers three predefined routines for setting the /// DialogResult: /// <para>- MSINext</para> /// <para>- MSIBack</para> /// <para>- MSICancel</para> /// By invoking these routines from the corresponding event handlers you can control your MSI UI sequence: /// <code> /// void cancelBtn_Click(object sender, EventArgs e) /// { /// MSICancel(); /// } /// /// void nextBtn_Click(object sender, EventArgs e) /// { /// MSINext(); /// } /// /// void backBtn_Click(object sender, EventArgs e) /// { /// MSIBack(); /// } /// </code> /// </para> /// </summary> public partial class WixCLRDialog : Form { /// <summary> /// The MSI session /// </summary> public Session session; /// <summary> /// The WIN32 handle to the host window (parent MSI dialog). /// </summary> protected IntPtr hostWindow; /// <summary> /// Initializes a new instance of the <see cref="WixCLRDialog"/> class. /// <remarks> /// This constructor is to be used by the Visual Studio Form designer only. /// You should always use <c>WixCLRDialog(Session session)</c> constructor instead. /// </remarks> /// </summary> public WixCLRDialog() { InitializeComponent(); } /// <summary> /// Initializes a new instance of the <see cref="WixCLRDialog"/> class. /// </summary> /// <param name="session">The session.</param> public WixCLRDialog(Session session) { this.session = session; InitializeComponent(); } void InitializeComponent() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); } catch { } if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { try { if (this.DesignMode) return; this.VisibleChanged += form_VisibleChanged; this.FormClosed += WixPanel_FormClosed; this.Load += WixDialog_Load; Init(); } catch { } } } void WixDialog_Load(object sender, EventArgs e) { this.Text = Win32.GetWindowText(this.hostWindow); } /// <summary> /// Inits this instance. /// </summary> protected void Init() { //Debug.Assert(false); this.hostWindow = GetMsiForegroundWindow(); this.Opacity = 0.0005; this.Text = Win32.GetWindowText(this.hostWindow); #if DEBUG //System.Diagnostics.Debugger.Launch(); #endif foreach (Process p in Process.GetProcessesByName("msiexec")) try { this.Icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName); //service process throws on accessing MainModule break; } catch { } } /// <summary> /// Gets the msi foreground window. /// </summary> /// <returns></returns> protected virtual IntPtr GetMsiForegroundWindow() { Process proc = null; var bundleUI = Environment.GetEnvironmentVariable("WIXSHARP_SILENT_BA_PROC_ID"); if (bundleUI != null) { int id = 0; if (int.TryParse(bundleUI, out id)) proc = Process.GetProcessById(id); } var bundlePath = session["WIXBUNDLEORIGINALSOURCE"]; if (bundlePath.IsNotEmpty()) { try { proc = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(bundlePath)).Where(p => p.MainWindowHandle != IntPtr.Zero).FirstOrDefault(); } catch { } } if (proc == null) { proc = Process.GetProcessesByName("msiexec").Where(p => p.MainWindowHandle != IntPtr.Zero).FirstOrDefault(); } if (proc != null) { //IntPtr handle = proc.MainWindowHandle; //old algorithm IntPtr handle = MsiWindowFinder.GetMsiDialog(proc.Id); Win32.ShowWindow(handle, Win32.SW_RESTORE); Win32.SetForegroundWindow(handle); return handle; } else return IntPtr.Zero; } /// <summary> /// There is some strange resizing artifact (at least on Win7) when MoveWindow does not resize the window accurately. /// Thus special adjustment ('delta') is needed to fix the problem. /// <para> /// The delta value is used in the ReplaceHost method.</para> /// </summary> protected int delta = 4; /// <summary> /// 'Replaces' the current step dialog with the "itself". /// <para>It uses WIN32 API to hide the parent native MSI dialog and place managed form dialog (itself) /// at the same desktop location and with the same size as the parent.</para> /// </summary> protected void ReplaceHost() { try { Win32.RECT r; Win32.GetWindowRect(hostWindow, out r); Win32.MoveWindow(this.Handle, r.Left - delta, r.Top - delta, r.Right - r.Left + delta * 2, r.Bottom - r.Top + delta * 2, true); this.Opacity = 1; Application.DoEvents(); this.MaximumSize = this.MinimumSize = new Size(this.Width, this.Height); //prevent resizing hostWindow.Hide(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } /// <summary> /// Restores parent native MSI dialog after the previous <c>ReplaceHost</c> call. /// </summary> protected void RestoreHost() { Win32.RECT r; Win32.GetWindowRect(this.Handle, out r); Win32.RECT rHost; Win32.GetWindowRect(hostWindow, out rHost); Win32.MoveWindow(hostWindow, r.Left + delta, r.Top + delta, rHost.Right - rHost.Left, rHost.Bottom - rHost.Top, true); hostWindow.Show(); this.Opacity = 0.01; Application.DoEvents(); } private void WixPanel_FormClosed(object sender, FormClosedEventArgs e) { RestoreHost(); } bool initialized = false; private void form_VisibleChanged(object sender, EventArgs e) { if (Visible) { if (!initialized) { initialized = true; ReplaceHost(); this.Visible = true; Application.DoEvents(); } } } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.Cancel' value ensuring the /// setup is canceled. /// </summary> public void MSICancel() { this.DialogResult = DialogResult.Cancel; Close(); } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.Retry' value ensuring the /// setup is resumed with the previous UI sequence dialog is displayed. /// </summary> public void MSIBack() { this.DialogResult = DialogResult.Retry; Close(); } /// <summary> /// Closes the dialog and sets the <c>this.DialogResult</c> to the 'DialogResult.OK' value ensuring the /// setup is resumed and the UI sequence advanced to the next step. /// </summary> public void MSINext() { this.DialogResult = DialogResult.OK; Close(); } /// <summary> /// Shows as specified managed dialog. /// <para>It uses WIN32 API to hide the parent native MSI dialog and place managed form dialog /// at the same desktop location and with the same size as the parent.</para> /// <para>It also ensures that after the managed dialog is closed the proper ActionResult is returned.</para> /// </summary> /// <param name="dialog">The dialog.</param> /// <returns>ActionResult value</returns> public static ActionResult ShowAsMsiDialog(WixCLRDialog dialog) { ActionResult retval = ActionResult.Success; try { using (dialog) { DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { dialog.session["Custom_UI_Command"] = "next"; retval = ActionResult.Success; } else if (result == DialogResult.Cancel) { dialog.session["Custom_UI_Command"] = "abort"; retval = ActionResult.UserExit; } if (result == DialogResult.Retry) { dialog.session["Custom_UI_Command"] = "back"; retval = ActionResult.Success; } } } catch (Exception e) { dialog.session.Log("Error: " + e.ToString()); retval = ActionResult.Failure; } #if DEBUG //System.Diagnostics.Debugger.Launch(); #endif return retval; } /// <summary> /// Gets the embedded MSI binary stream. /// </summary> /// <param name="binaryId">The binary id.</param> /// <returns>Stream instance</returns> public Stream GetMSIBinaryStream(string binaryId) { using (var sqlView = this.session.Database.OpenView("select Data from Binary where Name = '" + binaryId + "'")) { sqlView.Execute(); Stream data = sqlView.Fetch().GetStream(1); var retval = new MemoryStream(); int Length = 256; var buffer = new Byte[Length]; int bytesRead = data.Read(buffer, 0, Length); while (bytesRead > 0) { retval.Write(buffer, 0, bytesRead); bytesRead = data.Read(buffer, 0, Length); } return retval; } } } } internal class MsiWindowFinder { public static IntPtr GetMsiDialog(int processId) { var windows = EnumerateProcessWindowHandles(processId).Select(h => { var message = new StringBuilder(1000); SendMessage(h, WM_GETTEXT, message.Capacity, message); var wndText = message.ToString(); message.Length = 0; //clear prev content GetClassName(h, message, message.Capacity); var wndClass = message.ToString(); return new { Class = wndClass, Title = wndText, Handle = h }; }); var interactiveWindows = windows.Where(x => !string.IsNullOrEmpty(x.Title)); if (interactiveWindows.Any()) { if (interactiveWindows.Count() == 1) return interactiveWindows.First().Handle; else { var wellKnownDialogWindow = interactiveWindows.FirstOrDefault(x => x.Class == "MsiDialogCloseClass"); if (wellKnownDialogWindow != null) return wellKnownDialogWindow.Handle; } } return IntPtr.Zero; } private const uint WM_GETTEXT = 0x000D; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam); [DllImport("user32.dll")] static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam); static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processId) { var handles = new List<IntPtr>(); foreach (ProcessThread thread in Process.GetProcessById(processId).Threads) EnumThreadWindows(thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero); return handles; } } //public static class ProcessExtensions //{ // private static string FindIndexedProcessName(int pid) // { // var processName = Process.GetProcessById(pid).ProcessName; // var processesByName = Process.GetProcessesByName(processName); // string processIndexdName = null; // for (var index = 0; index < processesByName.Length; index++) // { // processIndexdName = index == 0 ? processName : processName + "#" + index; // var processId = new PerformanceCounter("Process", "ID Process", processIndexdName); // if ((int) processId.NextValue() == pid) // { // return processIndexdName; // } // } // return processIndexdName; // } // private static Process FindPidFromIndexedProcessName(string indexedProcessName) // { // var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName); // return Process.GetProcessById((int) parentId.NextValue()); // } // public static Process Parent(this Process process) // { // return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id)); // } //}
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualNetworkGatewaysOperations operations. /// </summary> public partial interface IVirtualNetworkGatewaysOperations { /// <summary> /// Creates or updates a virtual network gateway in the specified /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified virtual network gateway by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Resets the primary of the virtual network gateway in the specified /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of /// the active-active feature enabled gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Generates VPN client package for P2S client of the virtual network /// gateway in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN /// client package operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway /// in the specified resource group. Used for IKEV2 and radius based /// authentication. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN /// client package operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<string>> GenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP /// peers. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<BgpPeerStatusListResult>> GetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// This operation retrieves a list of routes the virtual network /// gateway has learned, including routes learned from BGP peers. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<GatewayRouteListResult>> GetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// This operation retrieves a list of routes the virtual network /// gateway is advertising to the specified peer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<GatewayRouteListResult>> GetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a virtual network gateway in the specified /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Resets the primary of the virtual network gateway in the specified /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of /// the active-active feature enabled gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Generates VPN client package for P2S client of the virtual network /// gateway in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN /// client package operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<string>> BeginGeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Generates VPN profile for P2S client of the virtual network gateway /// in the specified resource group. Used for IKEV2 and radius based /// authentication. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN /// client package operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<string>> BeginGenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP /// peers. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<BgpPeerStatusListResult>> BeginGetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// This operation retrieves a list of routes the virtual network /// gateway has learned, including routes learned from BGP peers. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// This operation retrieves a list of routes the virtual network /// gateway is advertising to the specified peer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the connections in a virtual network gateway. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * 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 Ionic.Zlib; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Security.Cryptography; // for computing md5 hash using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType; // You will need to uncomment these lines if you are adding a region module to some other assembly which does not already // specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans // the available DLLs //[assembly: Addin("MaterialsModule", "1.0")] //[assembly: AddinDependency("OpenSim", "0.5")] namespace OpenSim.Region.CoreModules.Materials { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")] public class MaterialsModule : INonSharedRegionModule { public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>(); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_enabled = false; private Scene m_scene = null; public string Name { get { return "MaterialsModule"; } } public Type ReplaceableInterface { get { return null; } } public static OSD ZCompressOSD(OSD inOsd, bool useHeader) { OSD osd = null; byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader); using (MemoryStream msSinkCompressed = new MemoryStream()) { using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed, Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true)) { zOut.Write(data, 0, data.Length); } msSinkCompressed.Seek(0L, SeekOrigin.Begin); osd = OSD.FromBinary(msSinkCompressed.ToArray()); } return osd; } public static OSD ZDecompressBytesToOsd(byte[] input) { OSD osd = null; using (MemoryStream msSinkUnCompressed = new MemoryStream()) { using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true)) { zOut.Write(input, 0, input.Length); } msSinkUnCompressed.Seek(0L, SeekOrigin.Begin); osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray()); } return osd; } public void AddRegion(Scene scene) { if (!m_enabled) return; m_scene = scene; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene; } public void Close() { if (!m_enabled) return; } public void Initialise(IConfigSource source) { IConfig config = source.Configs["Materials"]; if (config == null) return; m_enabled = config.GetBoolean("enable_materials", true); if (!m_enabled) return; m_log.DebugFormat("[Materials]: Initialized"); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!m_enabled) return; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; } public string RenderMaterialsGetCap(string request) { OSDMap resp = new OSDMap(); int matsCount = 0; OSDArray allOsd = new OSDArray(); lock (m_regionMaterials) { foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes()); matMap["Material"] = kvp.Value; allOsd.Add(matMap); matsCount++; } } resp["Zipped"] = ZCompressOSD(allOsd, false); return OSDParser.SerializeLLSDXmlString(resp); } public string RenderMaterialsPostCap(string request, UUID agentID) { OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray(); if (req.ContainsKey("Zipped")) { OSD osd = null; byte[] inBytes = req["Zipped"].AsBinary(); try { osd = ZDecompressBytesToOsd(inBytes); if (osd != null) { if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID(elem.AsBinary(), 0); lock (m_regionMaterials) { if (m_regionMaterials.ContainsKey(id)) { OSDMap matMap = new OSDMap(); matMap["ID"] = OSD.FromBinary(id.GetBytes()); matMap["Material"] = m_regionMaterials[id]; respArr.Add(matMap); } else { m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); // Theoretically we could try to load the material from the assets service, // but that shouldn't be necessary because the viewer should only request // materials that exist in a prim on the region, and all of these materials // are already stored in m_regionMaterials. } } } catch (Exception e) { m_log.Error("Error getting materials in response to viewer request", e); continue; } } } else if (osd is OSDMap) // request to assign a material { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) { OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; if (matsOsd is OSDArray) { OSDArray matsArr = matsOsd as OSDArray; try { foreach (OSDMap matsMap in matsArr) { uint primLocalID = 0; try { primLocalID = matsMap["ID"].AsUInteger(); } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); continue; } OSDMap mat = null; try { mat = matsMap["Material"] as OSDMap; } catch (Exception e) { m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); if (sop == null) { m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); continue; } if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) { m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); continue; } Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); continue; } UUID id; if (mat == null) { // This happens then the user removes a material from a prim id = UUID.Zero; } else { id = StoreMaterialAsAsset(agentID, mat, sop); } int face = -1; if (matsMap.ContainsKey("Face")) { face = matsMap["Face"].AsInteger(); Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face); faceEntry.MaterialID = id; } else { if (te.DefaultTexture == null) m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID); else te.DefaultTexture.MaterialID = id; } //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually sop.Shape.TextureEntry = te.GetBytes(); if (sop.ParentGroup != null) { sop.TriggerScriptChangedEvent(Changed.TEXTURE); sop.UpdateFlag = UpdateRequired.FULL; sop.ParentGroup.HasGroupChanged = true; sop.ScheduleFullUpdate(); } } } catch (Exception e) { m_log.Warn("[Materials]: exception processing received material ", e); } } } } } } catch (Exception e) { m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); //return ""; } } resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); //m_log.Debug("[Materials]: cap request: " + request); //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); //m_log.Debug("[Materials]: cap response: " + response); return response; } /// <summary> /// computes a UUID by hashing a OSD object /// </summary> /// <param name="osd"></param> /// <returns></returns> private static UUID HashOsd(OSD osd) { byte[] data = OSDParser.SerializeLLSDBinary(osd, false); using (var md5 = MD5.Create()) return new UUID(md5.ComputeHash(data), 0); } private static string ZippedOsdBytesToString(byte[] bytes) { try { return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes)); } catch (Exception e) { return "ZippedOsdBytesToString caught an exception: " + e.ToString(); } } /// <summary> /// Use heuristics to choose a good name for the material. /// </summary> private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop) { UUID normMap = mat["NormMap"].AsUUID(); if (normMap != UUID.Zero) { AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString()); if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR")) return asset.Name; } UUID specMap = mat["SpecMap"].AsUUID(); if (specMap != UUID.Zero) { AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString()); if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR")) return asset.Name; } if (sop.Name != "Primitive") return sop.Name; if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive")) return sop.ParentGroup.Name; return ""; } private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) { foreach (var part in obj.Parts) if (part != null) GetStoredMaterialsInPart(part); } /// <summary> /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'. /// </summary> /// <param name="part"></param> private void GetLegacyStoredMaterialsInPart(SceneObjectPart part) { if (part.DynAttrs == null) return; OSD OSMaterials = null; OSDArray matsArr = null; lock (part.DynAttrs) { if (part.DynAttrs.ContainsStore("OpenSim", "Materials")) { OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials"); if (materialsStore == null) return; materialsStore.TryGetValue("Materials", out OSMaterials); } if (OSMaterials != null && OSMaterials is OSDArray) matsArr = OSMaterials as OSDArray; else return; } if (matsArr == null) return; foreach (OSD elemOsd in matsArr) { if (elemOsd != null && elemOsd is OSDMap) { OSDMap matMap = elemOsd as OSDMap; if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material")) { try { lock (m_regionMaterials) m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"]; } catch (Exception e) { m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString()); } } } } } /// <summary> /// Find the materials used in one Face, and add them to 'm_regionMaterials'. /// </summary> private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face) { UUID id = face.MaterialID; if (id == UUID.Zero) return; lock (m_regionMaterials) { if (m_regionMaterials.ContainsKey(id)) return; byte[] data = m_scene.AssetService.GetData(id.ToString()); if (data == null) { m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id); return; } OSDMap mat; try { mat = (OSDMap)OSDParser.DeserializeLLSDXml(data); } catch (Exception e) { m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message); return; } m_regionMaterials[id] = mat; } } /// <summary> /// Find the materials used in the SOP, and add them to 'm_regionMaterials'. /// </summary> private void GetStoredMaterialsInPart(SceneObjectPart part) { if (part.Shape == null) return; var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length); if (te == null) return; GetLegacyStoredMaterialsInPart(part); GetStoredMaterialInFace(part, te.DefaultTexture); foreach (Primitive.TextureEntryFace face in te.FaceTextures) { if (face != null) GetStoredMaterialInFace(part, face); } } private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps) { string capsBase = "/CAPS/" + caps.CapsObjectPath; IRequestHandler renderMaterialsPostHandler = new RestStreamHandler("POST", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsPostCap(request, agentID), "RenderMaterials", null); caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler); // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET // and POST handlers, (at least at the time this was originally written), so we first set up a POST // handler normally and then add a GET handler via MainServer IRequestHandler renderMaterialsGetHandler = new RestStreamHandler("GET", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsGetCap(request), "RenderMaterials", null); MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler); // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well IRequestHandler renderMaterialsPutHandler = new RestStreamHandler("PUT", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsPostCap(request, agentID), "RenderMaterials", null); MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler); } private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop) { UUID id; // Material UUID = hash of the material's data. // This makes materials deduplicate across the entire grid (but isn't otherwise required). byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); using (var md5 = MD5.Create()) id = new UUID(md5.ComputeHash(data), 0); lock (m_regionMaterials) { if (!m_regionMaterials.ContainsKey(id)) { m_regionMaterials[id] = mat; // This asset might exist already, but it's ok to try to store it again string name = "Material " + ChooseMaterialName(mat, sop); name = name.Substring(0, Math.Min(64, name.Length)).Trim(); AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); } } return id; } } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.OpsWorks.Model { /// <summary> /// <para>Describes an instance.</para> /// </summary> public class Instance { private string instanceId; private string ec2InstanceId; private string hostname; private string stackId; private List<string> layerIds = new List<string>(); private List<string> securityGroupIds = new List<string>(); private string instanceType; private string instanceProfileArn; private string status; private string os; private string amiId; private string availabilityZone; private string subnetId; private string publicDns; private string privateDns; private string publicIp; private string privateIp; private string elasticIp; private string autoScalingType; private string sshKeyName; private string sshHostRsaKeyFingerprint; private string sshHostDsaKeyFingerprint; private string createdAt; private string lastServiceErrorId; private string architecture; private string rootDeviceType; private string rootDeviceVolumeId; private bool? installUpdatesOnBoot; /// <summary> /// The instance ID. /// /// </summary> public string InstanceId { get { return this.instanceId; } set { this.instanceId = value; } } /// <summary> /// Sets the InstanceId property /// </summary> /// <param name="instanceId">The value to set for the InstanceId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithInstanceId(string instanceId) { this.instanceId = instanceId; return this; } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this.instanceId != null; } /// <summary> /// The ID of the associated Amazon EC2 instance. /// /// </summary> public string Ec2InstanceId { get { return this.ec2InstanceId; } set { this.ec2InstanceId = value; } } /// <summary> /// Sets the Ec2InstanceId property /// </summary> /// <param name="ec2InstanceId">The value to set for the Ec2InstanceId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithEc2InstanceId(string ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; return this; } // Check to see if Ec2InstanceId property is set internal bool IsSetEc2InstanceId() { return this.ec2InstanceId != null; } /// <summary> /// The instance host name. /// /// </summary> public string Hostname { get { return this.hostname; } set { this.hostname = value; } } /// <summary> /// Sets the Hostname property /// </summary> /// <param name="hostname">The value to set for the Hostname property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithHostname(string hostname) { this.hostname = hostname; return this; } // Check to see if Hostname property is set internal bool IsSetHostname() { return this.hostname != null; } /// <summary> /// The stack ID. /// /// </summary> public string StackId { get { return this.stackId; } set { this.stackId = value; } } /// <summary> /// Sets the StackId property /// </summary> /// <param name="stackId">The value to set for the StackId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithStackId(string stackId) { this.stackId = stackId; return this; } // Check to see if StackId property is set internal bool IsSetStackId() { return this.stackId != null; } /// <summary> /// An array containing the instance layer IDs. /// /// </summary> public List<string> LayerIds { get { return this.layerIds; } set { this.layerIds = value; } } /// <summary> /// Adds elements to the LayerIds collection /// </summary> /// <param name="layerIds">The values to add to the LayerIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithLayerIds(params string[] layerIds) { foreach (string element in layerIds) { this.layerIds.Add(element); } return this; } /// <summary> /// Adds elements to the LayerIds collection /// </summary> /// <param name="layerIds">The values to add to the LayerIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithLayerIds(IEnumerable<string> layerIds) { foreach (string element in layerIds) { this.layerIds.Add(element); } return this; } // Check to see if LayerIds property is set internal bool IsSetLayerIds() { return this.layerIds.Count > 0; } /// <summary> /// An array containing the instance security group IDs. /// /// </summary> public List<string> SecurityGroupIds { get { return this.securityGroupIds; } set { this.securityGroupIds = value; } } /// <summary> /// Adds elements to the SecurityGroupIds collection /// </summary> /// <param name="securityGroupIds">The values to add to the SecurityGroupIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSecurityGroupIds(params string[] securityGroupIds) { foreach (string element in securityGroupIds) { this.securityGroupIds.Add(element); } return this; } /// <summary> /// Adds elements to the SecurityGroupIds collection /// </summary> /// <param name="securityGroupIds">The values to add to the SecurityGroupIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSecurityGroupIds(IEnumerable<string> securityGroupIds) { foreach (string element in securityGroupIds) { this.securityGroupIds.Add(element); } return this; } // Check to see if SecurityGroupIds property is set internal bool IsSetSecurityGroupIds() { return this.securityGroupIds.Count > 0; } /// <summary> /// The instance type. AWS OpsWorks supports all instance types except Cluster Compute, Cluster GPU, and High Memory Cluster. For more /// information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance Families and Types</a>. The /// parameter values that specify the various types are in the API Name column of the Available Instance Types table. /// /// </summary> public string InstanceType { get { return this.instanceType; } set { this.instanceType = value; } } /// <summary> /// Sets the InstanceType property /// </summary> /// <param name="instanceType">The value to set for the InstanceType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithInstanceType(string instanceType) { this.instanceType = instanceType; return this; } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this.instanceType != null; } /// <summary> /// The ARN of the instance's IAM profile. For more information about IAM ARNs, see <a /// href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using Identifiers</a>. /// /// </summary> public string InstanceProfileArn { get { return this.instanceProfileArn; } set { this.instanceProfileArn = value; } } /// <summary> /// Sets the InstanceProfileArn property /// </summary> /// <param name="instanceProfileArn">The value to set for the InstanceProfileArn property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithInstanceProfileArn(string instanceProfileArn) { this.instanceProfileArn = instanceProfileArn; return this; } // Check to see if InstanceProfileArn property is set internal bool IsSetInstanceProfileArn() { return this.instanceProfileArn != null; } /// <summary> /// The instance status: <ul> <li>requested</li> <li>booting</li> <li>running_setup</li> <li>online</li> <li>setup_failed</li> /// <li>start_failed</li> <li>terminating</li> <li>terminated</li> <li>stopped</li> <li>connection_lost</li> </ul> /// /// </summary> public string Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Sets the Status property /// </summary> /// <param name="status">The value to set for the Status property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithStatus(string status) { this.status = status; return this; } // Check to see if Status property is set internal bool IsSetStatus() { return this.status != null; } /// <summary> /// The instance operating system. /// /// </summary> public string Os { get { return this.os; } set { this.os = value; } } /// <summary> /// Sets the Os property /// </summary> /// <param name="os">The value to set for the Os property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithOs(string os) { this.os = os; return this; } // Check to see if Os property is set internal bool IsSetOs() { return this.os != null; } /// <summary> /// A custom AMI ID to be used to create the instance. The AMI should be based on one of the standard AWS OpsWorks APIs: Amazon Linux or Ubuntu /// 12.04 LTS. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances.html">Instances</a> /// /// </summary> public string AmiId { get { return this.amiId; } set { this.amiId = value; } } /// <summary> /// Sets the AmiId property /// </summary> /// <param name="amiId">The value to set for the AmiId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithAmiId(string amiId) { this.amiId = amiId; return this; } // Check to see if AmiId property is set internal bool IsSetAmiId() { return this.amiId != null; } /// <summary> /// The instance Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and /// Endpoints</a>. /// /// </summary> public string AvailabilityZone { get { return this.availabilityZone; } set { this.availabilityZone = value; } } /// <summary> /// Sets the AvailabilityZone property /// </summary> /// <param name="availabilityZone">The value to set for the AvailabilityZone property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithAvailabilityZone(string availabilityZone) { this.availabilityZone = availabilityZone; return this; } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this.availabilityZone != null; } /// <summary> /// The instance's subnet ID, if the stack is running in a VPC. /// /// </summary> public string SubnetId { get { return this.subnetId; } set { this.subnetId = value; } } /// <summary> /// Sets the SubnetId property /// </summary> /// <param name="subnetId">The value to set for the SubnetId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSubnetId(string subnetId) { this.subnetId = subnetId; return this; } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this.subnetId != null; } /// <summary> /// The instance public DNS name. /// /// </summary> public string PublicDns { get { return this.publicDns; } set { this.publicDns = value; } } /// <summary> /// Sets the PublicDns property /// </summary> /// <param name="publicDns">The value to set for the PublicDns property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithPublicDns(string publicDns) { this.publicDns = publicDns; return this; } // Check to see if PublicDns property is set internal bool IsSetPublicDns() { return this.publicDns != null; } /// <summary> /// The instance private DNS name. /// /// </summary> public string PrivateDns { get { return this.privateDns; } set { this.privateDns = value; } } /// <summary> /// Sets the PrivateDns property /// </summary> /// <param name="privateDns">The value to set for the PrivateDns property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithPrivateDns(string privateDns) { this.privateDns = privateDns; return this; } // Check to see if PrivateDns property is set internal bool IsSetPrivateDns() { return this.privateDns != null; } /// <summary> /// The instance public IP address. /// /// </summary> public string PublicIp { get { return this.publicIp; } set { this.publicIp = value; } } /// <summary> /// Sets the PublicIp property /// </summary> /// <param name="publicIp">The value to set for the PublicIp property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithPublicIp(string publicIp) { this.publicIp = publicIp; return this; } // Check to see if PublicIp property is set internal bool IsSetPublicIp() { return this.publicIp != null; } /// <summary> /// The instance private IP address. /// /// </summary> public string PrivateIp { get { return this.privateIp; } set { this.privateIp = value; } } /// <summary> /// Sets the PrivateIp property /// </summary> /// <param name="privateIp">The value to set for the PrivateIp property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithPrivateIp(string privateIp) { this.privateIp = privateIp; return this; } // Check to see if PrivateIp property is set internal bool IsSetPrivateIp() { return this.privateIp != null; } /// <summary> /// The instance <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html">Elastic IP address </a>. /// /// </summary> public string ElasticIp { get { return this.elasticIp; } set { this.elasticIp = value; } } /// <summary> /// Sets the ElasticIp property /// </summary> /// <param name="elasticIp">The value to set for the ElasticIp property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithElasticIp(string elasticIp) { this.elasticIp = elasticIp; return this; } // Check to see if ElasticIp property is set internal bool IsSetElasticIp() { return this.elasticIp != null; } /// <summary> /// The instance's auto scaling type, which has three possible values: <ul> <li><b>AlwaysRunning</b>: A 24/7 instance, which is not affected by /// auto scaling.</li> <li><b>TimeBasedAutoScaling</b>: A time-based auto scaling instance, which is started and stopped based on a specified /// schedule.</li> <li><b>LoadBasedAutoScaling</b>: A load-based auto scaling instance, which is started and stopped based on load metrics.</li> /// </ul> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>load, timer</description> /// </item> /// </list> /// </para> /// </summary> public string AutoScalingType { get { return this.autoScalingType; } set { this.autoScalingType = value; } } /// <summary> /// Sets the AutoScalingType property /// </summary> /// <param name="autoScalingType">The value to set for the AutoScalingType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithAutoScalingType(string autoScalingType) { this.autoScalingType = autoScalingType; return this; } // Check to see if AutoScalingType property is set internal bool IsSetAutoScalingType() { return this.autoScalingType != null; } /// <summary> /// The instance SSH key name. /// /// </summary> public string SshKeyName { get { return this.sshKeyName; } set { this.sshKeyName = value; } } /// <summary> /// Sets the SshKeyName property /// </summary> /// <param name="sshKeyName">The value to set for the SshKeyName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSshKeyName(string sshKeyName) { this.sshKeyName = sshKeyName; return this; } // Check to see if SshKeyName property is set internal bool IsSetSshKeyName() { return this.sshKeyName != null; } /// <summary> /// The SSH key's RSA fingerprint. /// /// </summary> public string SshHostRsaKeyFingerprint { get { return this.sshHostRsaKeyFingerprint; } set { this.sshHostRsaKeyFingerprint = value; } } /// <summary> /// Sets the SshHostRsaKeyFingerprint property /// </summary> /// <param name="sshHostRsaKeyFingerprint">The value to set for the SshHostRsaKeyFingerprint property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSshHostRsaKeyFingerprint(string sshHostRsaKeyFingerprint) { this.sshHostRsaKeyFingerprint = sshHostRsaKeyFingerprint; return this; } // Check to see if SshHostRsaKeyFingerprint property is set internal bool IsSetSshHostRsaKeyFingerprint() { return this.sshHostRsaKeyFingerprint != null; } /// <summary> /// The SSH key's DSA fingerprint. /// /// </summary> public string SshHostDsaKeyFingerprint { get { return this.sshHostDsaKeyFingerprint; } set { this.sshHostDsaKeyFingerprint = value; } } /// <summary> /// Sets the SshHostDsaKeyFingerprint property /// </summary> /// <param name="sshHostDsaKeyFingerprint">The value to set for the SshHostDsaKeyFingerprint property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithSshHostDsaKeyFingerprint(string sshHostDsaKeyFingerprint) { this.sshHostDsaKeyFingerprint = sshHostDsaKeyFingerprint; return this; } // Check to see if SshHostDsaKeyFingerprint property is set internal bool IsSetSshHostDsaKeyFingerprint() { return this.sshHostDsaKeyFingerprint != null; } /// <summary> /// The time that the instance was created. /// /// </summary> public string CreatedAt { get { return this.createdAt; } set { this.createdAt = value; } } /// <summary> /// Sets the CreatedAt property /// </summary> /// <param name="createdAt">The value to set for the CreatedAt property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithCreatedAt(string createdAt) { this.createdAt = createdAt; return this; } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this.createdAt != null; } /// <summary> /// The ID of the last service error. For more information, call <a>DescribeServiceErrors</a>. /// /// </summary> public string LastServiceErrorId { get { return this.lastServiceErrorId; } set { this.lastServiceErrorId = value; } } /// <summary> /// Sets the LastServiceErrorId property /// </summary> /// <param name="lastServiceErrorId">The value to set for the LastServiceErrorId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithLastServiceErrorId(string lastServiceErrorId) { this.lastServiceErrorId = lastServiceErrorId; return this; } // Check to see if LastServiceErrorId property is set internal bool IsSetLastServiceErrorId() { return this.lastServiceErrorId != null; } /// <summary> /// The instance architecture, "i386" or "x86_64". /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>x86_64, i386</description> /// </item> /// </list> /// </para> /// </summary> public string Architecture { get { return this.architecture; } set { this.architecture = value; } } /// <summary> /// Sets the Architecture property /// </summary> /// <param name="architecture">The value to set for the Architecture property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithArchitecture(string architecture) { this.architecture = architecture; return this; } // Check to see if Architecture property is set internal bool IsSetArchitecture() { return this.architecture != null; } /// <summary> /// The instance root device type. For more information, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device">Storage for the Root Device</a>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>ebs, instance-store</description> /// </item> /// </list> /// </para> /// </summary> public string RootDeviceType { get { return this.rootDeviceType; } set { this.rootDeviceType = value; } } /// <summary> /// Sets the RootDeviceType property /// </summary> /// <param name="rootDeviceType">The value to set for the RootDeviceType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithRootDeviceType(string rootDeviceType) { this.rootDeviceType = rootDeviceType; return this; } // Check to see if RootDeviceType property is set internal bool IsSetRootDeviceType() { return this.rootDeviceType != null; } /// <summary> /// The root device volume ID. /// /// </summary> public string RootDeviceVolumeId { get { return this.rootDeviceVolumeId; } set { this.rootDeviceVolumeId = value; } } /// <summary> /// Sets the RootDeviceVolumeId property /// </summary> /// <param name="rootDeviceVolumeId">The value to set for the RootDeviceVolumeId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithRootDeviceVolumeId(string rootDeviceVolumeId) { this.rootDeviceVolumeId = rootDeviceVolumeId; return this; } // Check to see if RootDeviceVolumeId property is set internal bool IsSetRootDeviceVolumeId() { return this.rootDeviceVolumeId != null; } /// <summary> /// Whether to install operating system and package updates when the instance boots. The default value is <c>true</c>. If this value is set to /// <c>false</c>, you must then update your instances manually by using <a>CreateDeployment</a> to run the <c>update_dependencies</c> stack /// command or manually running <c>yum</c> (Amazon Linux) or <c>apt-get</c> (Ubuntu) on the instances. <note>We strongly recommend using the /// default value of <c>true</c>, to ensure that your instances have the latest security updates.</note> /// /// </summary> public bool InstallUpdatesOnBoot { get { return this.installUpdatesOnBoot ?? default(bool); } set { this.installUpdatesOnBoot = value; } } /// <summary> /// Sets the InstallUpdatesOnBoot property /// </summary> /// <param name="installUpdatesOnBoot">The value to set for the InstallUpdatesOnBoot property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Instance WithInstallUpdatesOnBoot(bool installUpdatesOnBoot) { this.installUpdatesOnBoot = installUpdatesOnBoot; return this; } // Check to see if InstallUpdatesOnBoot property is set internal bool IsSetInstallUpdatesOnBoot() { return this.installUpdatesOnBoot.HasValue; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// A Scheme category does not reference individual members or indices, but simply describes a symbolic representation that /// can be used by an actual category. /// </summary> [TypeConverter(typeof(ExpandableObjectConverter))] [Serializable] public class FeatureCategory : Category, IFeatureCategory { #region Fields private IFeatureSymbolizer _featureSymbolizer; private string _filterExpression; private SymbologyMenuItem _mnuDeselectFeatures; private SymbologyMenuItem _mnuRemoveMe; private SymbologyMenuItem _mnuSelectFeatures; private IFeatureSymbolizer _selectionSymbolizer; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="FeatureCategory"/> class. /// </summary> public FeatureCategory() { LegendSymbolMode = SymbolMode.Symbol; LegendType = LegendType.Symbol; CreateContextMenuItems(); } #endregion #region Events /// <summary> /// Occurs when the deselect features context menu is clicked. /// </summary> public event EventHandler<ExpressionEventArgs> DeselectFeatures; /// <summary> /// Occurs when the select features context menu is clicked. /// </summary> public event EventHandler<ExpressionEventArgs> SelectFeatures; #endregion #region Properties /// <summary> /// Gets or sets the filter expression that is used to add members to generate a category based on this scheme. /// </summary> /// <remarks>[Editor(typeof(ExpressionEditor), typeof(UITypeEditor))]</remarks> [Description("Gets or set the filter expression that is used to add members to generate a category based on this scheme.")] [Serialize("FilterExpression")] public string FilterExpression { get { return _filterExpression; } set { _filterExpression = value; } } /// <summary> /// Gets or sets the symbolizer used for this category /// </summary> [Serialize("SelectionSymbolizer")] public IFeatureSymbolizer SelectionSymbolizer { get { return _selectionSymbolizer; } set { if (_selectionSymbolizer != null) _selectionSymbolizer.ItemChanged -= SymbolizerItemChanged; if (_selectionSymbolizer != value && value != null) { value.ItemChanged += SymbolizerItemChanged; value.SetParentItem(this); } _selectionSymbolizer = value; OnItemChanged(); } } /// <summary> /// Gets or sets the symbolizer used for this category. /// </summary> [Serialize("Symbolizer")] public IFeatureSymbolizer Symbolizer { get { return _featureSymbolizer; } set { if (_featureSymbolizer != null) _featureSymbolizer.ItemChanged -= SymbolizerItemChanged; if (_featureSymbolizer != value && value != null) { value.ItemChanged += SymbolizerItemChanged; value.SetParentItem(this); } _featureSymbolizer = value; OnItemChanged(); } } #endregion #region Methods /// <summary> /// Applies the minimum and maximum in order to create the filter expression. This will also /// count the members that match the specified criteria. /// </summary> /// <param name="settings">Settings that are used to apply the minimum and maximum.</param> public override void ApplyMinMax(EditorSettings settings) { base.ApplyMinMax(settings); FeatureEditorSettings fs = settings as FeatureEditorSettings; if (fs == null) return; string field = "[" + fs.FieldName.ToUpper() + "]"; if (!string.IsNullOrEmpty(fs.NormField)) field += "/[" + fs.NormField.ToUpper() + "]"; IntervalSnapMethod method = settings.IntervalSnapMethod; int digits = settings.IntervalRoundingDigits; LegendText = Range.ToString(method, digits); _filterExpression = Range.ToExpression(field); } /// <summary> /// Forces the creation of an entirely new context menu list. That way, we are not /// pointing to an event handler in the previous parent. /// </summary> public void CreateContextMenuItems() { ContextMenuItems = new List<SymbologyMenuItem>(); _mnuRemoveMe = new SymbologyMenuItem("Remove Category", RemoveCategoryClicked); _mnuSelectFeatures = new SymbologyMenuItem("Select Features", SelectFeaturesClicked); _mnuDeselectFeatures = new SymbologyMenuItem("Deselect Features", DeselectFeaturesClicked); ContextMenuItems.Add(_mnuRemoveMe); ContextMenuItems.Add(_mnuSelectFeatures); ContextMenuItems.Add(_mnuDeselectFeatures); } /// <summary> /// In some cases, it is useful to simply be able to show an approximation of the actual expression. /// This also removes brackets from the field names to make it slightly cleaner. /// </summary> public void DisplayExpression() { string exp = _filterExpression; if (exp != null) { exp = exp.Replace("[", string.Empty); exp = exp.Replace("]", string.Empty); } LegendText = exp; } /// <summary> /// This gets a single color that attempts to represent the specified /// category. For polygons, for example, this is the fill color (or central fill color) /// of the top pattern. If an image is being used, the color will be gray. /// </summary> /// <returns>The System.Color that can be used as an approximation to represent this category.</returns> public virtual Color GetColor() { return Color.Gray; } /// <summary> /// Queries this layer and the entire parental tree up to the map frame to determine if /// this layer is within the selected layers. /// </summary> /// <returns>True, if the item is selected in legend.</returns> public bool IsWithinLegendSelection() { if (IsSelected) return true; ILayer lyr = GetParentItem() as ILayer; while (lyr != null) { if (lyr.IsSelected) return true; lyr = lyr.GetParentItem() as ILayer; } return false; } /// <summary> /// Controls what happens in the legend when this item is instructed to draw a symbol. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="box">Rectangle used for drawing.</param> public override void LegendSymbolPainted(Graphics g, Rectangle box) { _featureSymbolizer.Draw(g, box); } /// <summary> /// Triggers the DeselectFeatures event. /// </summary> public virtual void OnDeselectFeatures() { DeselectFeatures?.Invoke(this, new ExpressionEventArgs(_filterExpression)); } /// <summary> /// This applies the color to the top symbol stroke or pattern. /// </summary> /// <param name="color">The Color to apply</param> public virtual void SetColor(Color color) { } /// <summary> /// Makes it so that if there are any pre-existing listeners to the SelectFeatuers /// event when creating a clone of this object, those listeners are removed. /// They should be added correctly when the cloned item is added to the collection, /// after being cloned. /// </summary> /// <param name="copy">The copy descriptor.</param> protected override void OnCopy(Descriptor copy) { // todo: do the same for DeselectFeatures event... FeatureCategory cat = copy as FeatureCategory; if (cat?.SelectFeatures != null) { foreach (var handler in cat.SelectFeatures.GetInvocationList()) { cat.SelectFeatures -= (EventHandler<ExpressionEventArgs>)handler; } } cat?.CreateContextMenuItems(); base.OnCopy(copy); } /// <summary> /// Fires the SelectFeatures event /// </summary> protected virtual void OnSelectFeatures() { SelectFeatures?.Invoke(this, new ExpressionEventArgs(_filterExpression)); } private void DeselectFeaturesClicked(object sender, EventArgs e) { OnDeselectFeatures(); } private void RemoveCategoryClicked(object sender, EventArgs e) { OnRemoveItem(); } private void SelectFeaturesClicked(object sender, EventArgs e) { OnSelectFeatures(); } private void SymbolizerItemChanged(object sender, EventArgs e) { OnItemChanged(); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; namespace RefactoringEssentials { #if NR6 public #endif static partial class EnumerableExtensions { public static IEnumerable<T> Do<T>(this IEnumerable<T> source, Action<T> action) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } // perf optimization. try to not use enumerator if possible var list = source as IList<T>; if (list != null) { for (int i = 0, count = list.Count; i < count; i++) { action(list[i]); } } else { foreach (var value in source) { action(value); } } return source; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new ReadOnlyCollection<T>(source.ToList()); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> source, T value) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.ConcatWorker(value); } private static IEnumerable<T> ConcatWorker<T>(this IEnumerable<T> source, T value) { foreach (var v in source) { yield return v; } yield return value; } public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2, IEqualityComparer<T> comparer) { if (source1 == null) { throw new ArgumentNullException(nameof(source1)); } if (source2 == null) { throw new ArgumentNullException(nameof(source2)); } return source1.ToSet(comparer).SetEquals(source2); } public static bool SetEquals<T>(this IEnumerable<T> source1, IEnumerable<T> source2) { if (source1 == null) { throw new ArgumentNullException(nameof(source1)); } if (source2 == null) { throw new ArgumentNullException(nameof(source2)); } return source1.ToSet().SetEquals(source2); } public static ISet<T> ToSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new HashSet<T>(source, comparer); } public static ISet<T> ToSet<T>(this IEnumerable<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source as ISet<T> ?? new HashSet<T>(source); } public static T? FirstOrNullable<T>(this IEnumerable<T> source) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().FirstOrDefault(); } public static T? FirstOrNullable<T>(this IEnumerable<T> source, Func<T, bool> predicate) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().FirstOrDefault(v => predicate(v.Value)); } public static T? LastOrNullable<T>(this IEnumerable<T> source) where T : struct { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Cast<T?>().LastOrDefault(); } public static bool IsSingle<T>(this IEnumerable<T> list) { using (var enumerator = list.GetEnumerator()) { return enumerator.MoveNext() && !enumerator.MoveNext(); } } public static bool IsEmpty<T>(this IEnumerable<T> source) { var readOnlyCollection = source as IReadOnlyCollection<T>; if (readOnlyCollection != null) { return readOnlyCollection.Count == 0; } var genericCollection = source as ICollection<T>; if (genericCollection != null) { return genericCollection.Count == 0; } var collection = source as ICollection; if (collection != null) { return collection.Count == 0; } var str = source as string; if (str != null) { return str.Length == 0; } foreach (var t in source) { return false; } return true; } public static bool IsEmpty<T>(this IReadOnlyCollection<T> source) { return source.Count == 0; } public static bool IsEmpty<T>(this ICollection<T> source) { return source.Count == 0; } public static bool IsEmpty(this string source) { return source.Length == 0; } /// <remarks> /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>. /// </remarks> public static bool IsEmpty<T>(this T[] source) { return source.Length == 0; } /// <remarks> /// This method is necessary to avoid an ambiguity between <see cref="IsEmpty{T}(IReadOnlyCollection{T})"/> and <see cref="IsEmpty{T}(ICollection{T})"/>. /// </remarks> public static bool IsEmpty<T>(this List<T> source) { return source.Count == 0; } private static readonly Func<object, bool> s_notNullTest = x => x != null; public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source) where T : class { if (source == null) { return SpecializedCollections.EmptyEnumerable<T>(); } return source.Where((Func<T, bool>)s_notNullTest); } public static bool All(this IEnumerable<bool> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } foreach (var b in source) { if (!b) { return false; } } return true; } public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence) { if (sequence == null) { throw new ArgumentNullException(nameof(sequence)); } return sequence.SelectMany(s => s); } public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer) { return source.OrderBy(t => t, comparer); } // public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare) // { // return source.OrderBy(new ComparisonComparer<T>(compare)); // } // public static IEnumerable<T> Order<T>(this IEnumerable<T> source) where T : IComparable<T> // { // return source.OrderBy((t1, t2) => t1.CompareTo(t2)); // } public static bool IsSorted<T>(this IEnumerable<T> enumerable, IComparer<T> comparer) { using (var e = enumerable.GetEnumerator()) { if (!e.MoveNext()) { return true; } var previous = e.Current; while (e.MoveNext()) { if (comparer.Compare(previous, e.Current) > 0) { return false; } previous = e.Current; } return true; } } public static bool SequenceEqual<T>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, T, bool> comparer) { Debug.Assert(comparer != null); if (first == second) { return true; } if (first == null || second == null) { return false; } using (var enumerator = first.GetEnumerator()) using (var enumerator2 = second.GetEnumerator()) { while (enumerator.MoveNext()) { if (!enumerator2.MoveNext() || !comparer(enumerator.Current, enumerator2.Current)) { return false; } } if (enumerator2.MoveNext()) { return false; } } return true; } public static bool Contains<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) { return sequence.Any(predicate); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections; using System.Collections.Generic; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.Xml; static class ReliableSessionPolicyStrings { public const string AcknowledgementInterval = "AcknowledgementInterval"; public const string AtLeastOnce = "AtLeastOnce"; public const string AtMostOnce = "AtMostOnce"; public const string BaseRetransmissionInterval = "BaseRetransmissionInterval"; public const string DeliveryAssurance = "DeliveryAssurance"; public const string ExactlyOnce = "ExactlyOnce"; public const string ExponentialBackoff = "ExponentialBackoff"; public const string InactivityTimeout = "InactivityTimeout"; public const string InOrder = "InOrder"; public const string Milliseconds = "Milliseconds"; public const string NET11Namespace = "http://schemas.microsoft.com/ws-rx/wsrmp/200702"; public const string NET11Prefix = "netrmp"; public const string ReliableSessionName = "RMAssertion"; public const string ReliableSessionFebruary2005Namespace = "http://schemas.xmlsoap.org/ws/2005/02/rm/policy"; public const string ReliableSessionFebruary2005Prefix = "wsrm"; public const string ReliableSession11Namespace = "http://docs.oasis-open.org/ws-rx/wsrmp/200702"; public const string ReliableSession11Prefix = "wsrmp"; public const string SequenceSTR = "SequenceSTR"; public const string SequenceTransportSecurity = "SequenceTransportSecurity"; } public sealed class ReliableSessionBindingElementImporter : IPolicyImportExtension { void IPolicyImportExtension.ImportPolicy(MetadataImporter importer, PolicyConversionContext context) { if (importer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("importer"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } bool gotAssertion = false; XmlElement reliableSessionAssertion = PolicyConversionContext.FindAssertion(context.GetBindingAssertions(), ReliableSessionPolicyStrings.ReliableSessionName, ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace, true); if (reliableSessionAssertion != null) { ProcessReliableSessionFeb2005Assertion(reliableSessionAssertion, GetReliableSessionBindingElement(context)); gotAssertion = true; } reliableSessionAssertion = PolicyConversionContext.FindAssertion(context.GetBindingAssertions(), ReliableSessionPolicyStrings.ReliableSessionName, ReliableSessionPolicyStrings.ReliableSession11Namespace, true); if (reliableSessionAssertion != null) { if (gotAssertion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException( SR.GetString(SR.MultipleVersionsFoundInPolicy, ReliableSessionPolicyStrings.ReliableSessionName))); } ProcessReliableSession11Assertion(importer, reliableSessionAssertion, GetReliableSessionBindingElement(context)); } } static ReliableSessionBindingElement GetReliableSessionBindingElement(PolicyConversionContext context) { ReliableSessionBindingElement settings = context.BindingElements.Find<ReliableSessionBindingElement>(); if (settings == null) { settings = new ReliableSessionBindingElement(); context.BindingElements.Add(settings); } return settings; } static bool Is11Assertion(XmlNode node, string assertion) { return IsElement(node, ReliableSessionPolicyStrings.NET11Namespace, assertion); } static bool IsElement(XmlNode node, string ns, string assertion) { if (assertion == null) { throw Fx.AssertAndThrow("Argument assertion cannot be null."); } return ((node != null) && (node.NodeType == XmlNodeType.Element) && (node.NamespaceURI == ns) && (node.LocalName == assertion)); } static bool IsFeb2005Assertion(XmlNode node, string assertion) { return IsElement(node, ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace, assertion); } static void ProcessReliableSession11Assertion(MetadataImporter importer, XmlElement element, ReliableSessionBindingElement settings) { // Version settings.ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessaging11; IEnumerator assertionChildren = element.ChildNodes.GetEnumerator(); XmlNode currentNode = SkipToNode(assertionChildren); // Policy ProcessWsrm11Policy(importer, currentNode, settings); currentNode = SkipToNode(assertionChildren); // Looking for: // InactivityTimeout, AcknowledgementInterval // InactivityTimeout // AcknowledgementInterval // or nothing at all. State state = State.InactivityTimeout; while (currentNode != null) { if (state == State.InactivityTimeout) { // InactivityTimeout assertion if (Is11Assertion(currentNode, ReliableSessionPolicyStrings.InactivityTimeout)) { SetInactivityTimeout(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName); state = State.AcknowledgementInterval; currentNode = SkipToNode(assertionChildren); continue; } } // AcknowledgementInterval assertion if (Is11Assertion(currentNode, ReliableSessionPolicyStrings.AcknowledgementInterval)) { SetAcknowledgementInterval(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName); // ignore the rest break; } if (state == State.AcknowledgementInterval) { // ignore the rest break; } currentNode = SkipToNode(assertionChildren); } // Schema allows arbitrary elements from now on, ignore everything else } static void ProcessReliableSessionFeb2005Assertion(XmlElement element, ReliableSessionBindingElement settings) { // Version settings.ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessagingFebruary2005; IEnumerator nodes = element.ChildNodes.GetEnumerator(); XmlNode currentNode = SkipToNode(nodes); // InactivityTimeout assertion if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.InactivityTimeout)) { SetInactivityTimeout(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName); currentNode = SkipToNode(nodes); } // BaseRetransmissionInterval assertion is read but ignored if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.BaseRetransmissionInterval)) { ReadMillisecondsAttribute(currentNode, false); currentNode = SkipToNode(nodes); } // ExponentialBackoff assertion is read but ignored if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.ExponentialBackoff)) { currentNode = SkipToNode(nodes); } // AcknowledgementInterval assertion if (IsFeb2005Assertion(currentNode, ReliableSessionPolicyStrings.AcknowledgementInterval)) { SetAcknowledgementInterval(settings, ReadMillisecondsAttribute(currentNode, true), currentNode.LocalName); } // Schema allows arbitrary elements from now on, ignore everything else } static void ProcessWsrm11Policy(MetadataImporter importer, XmlNode node, ReliableSessionBindingElement settings) { XmlElement element = ThrowIfNotPolicyElement(node, ReliableMessagingVersion.WSReliableMessaging11); IEnumerable<IEnumerable<XmlElement>> alternatives = importer.NormalizePolicy(new XmlElement[] { element }); List<Wsrm11PolicyAlternative> wsrmAlternatives = new List<Wsrm11PolicyAlternative>(); foreach (IEnumerable<XmlElement> alternative in alternatives) { Wsrm11PolicyAlternative wsrm11Policy = Wsrm11PolicyAlternative.ImportAlternative(importer, alternative); wsrmAlternatives.Add(wsrm11Policy); } if (wsrmAlternatives.Count == 0) { // No specific policy other than turn on WS-RM. return; } foreach (Wsrm11PolicyAlternative wsrmAlternative in wsrmAlternatives) { // The only policy setting that affects the binding is the InOrder assurance. // Even that setting does not affect the binding since InOrder is a server delivery assurance. // Transfer any that is valid. if (wsrmAlternative.HasValidPolicy) { wsrmAlternative.TransferSettings(settings); return; } } // Found only invalid policy. // This throws an exception about security since that is the only invalid policy we have. Wsrm11PolicyAlternative.ThrowInvalidBindingException(); } static TimeSpan ReadMillisecondsAttribute(XmlNode wsrmNode, bool convertToTimeSpan) { XmlAttribute millisecondsAttribute = wsrmNode.Attributes[ReliableSessionPolicyStrings.Milliseconds]; if (millisecondsAttribute == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString(SR.RequiredAttributeIsMissing, ReliableSessionPolicyStrings.Milliseconds, wsrmNode.LocalName, ReliableSessionPolicyStrings.ReliableSessionName))); UInt64 milliseconds = 0; Exception innerException = null; try { milliseconds = XmlConvert.ToUInt64(millisecondsAttribute.Value); } catch (FormatException exception) { innerException = exception; } catch (OverflowException exception) { innerException = exception; } if (innerException != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString(SR.RequiredMillisecondsAttributeIncorrect, wsrmNode.LocalName), innerException)); if (convertToTimeSpan) { TimeSpan interval; try { interval = TimeSpan.FromMilliseconds(Convert.ToDouble(milliseconds)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString(SR.MillisecondsNotConvertibleToBindingRange, wsrmNode.LocalName), exception)); } return interval; } else { return default(TimeSpan); } } static void SetInactivityTimeout(ReliableSessionBindingElement settings, TimeSpan inactivityTimeout, string localName) { try { settings.InactivityTimeout = inactivityTimeout; } catch (ArgumentOutOfRangeException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException( SR.GetString(SR.MillisecondsNotConvertibleToBindingRange, localName), exception)); } } static void SetAcknowledgementInterval(ReliableSessionBindingElement settings, TimeSpan acknowledgementInterval, string localName) { try { settings.AcknowledgementInterval = acknowledgementInterval; } catch (ArgumentOutOfRangeException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString(SR.MillisecondsNotConvertibleToBindingRange, localName), exception)); } } static bool ShouldSkipNodeType(XmlNodeType type) { return (type == XmlNodeType.Comment || type == XmlNodeType.SignificantWhitespace || type == XmlNodeType.Whitespace || type == XmlNodeType.Notation); } static XmlNode SkipToNode(IEnumerator nodes) { while (nodes.MoveNext()) { XmlNode currentNode = (XmlNode)nodes.Current; if (ShouldSkipNodeType(currentNode.NodeType)) continue; return currentNode; } return null; } static XmlElement ThrowIfNotPolicyElement(XmlNode node, ReliableMessagingVersion reliableMessagingVersion) { string policyLocalName = MetadataStrings.WSPolicy.Elements.Policy; if (!IsElement(node, MetadataStrings.WSPolicy.NamespaceUri, policyLocalName) && !IsElement(node, MetadataStrings.WSPolicy.NamespaceUri15, policyLocalName)) { string wsrmPrefix = (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) ? ReliableSessionPolicyStrings.ReliableSessionFebruary2005Prefix : ReliableSessionPolicyStrings.ReliableSession11Prefix; string exceptionString = (node == null) ? SR.GetString(SR.ElementRequired, wsrmPrefix, ReliableSessionPolicyStrings.ReliableSessionName, MetadataStrings.WSPolicy.Prefix, MetadataStrings.WSPolicy.Elements.Policy) : SR.GetString(SR.ElementFound, wsrmPrefix, ReliableSessionPolicyStrings.ReliableSessionName, MetadataStrings.WSPolicy.Prefix, MetadataStrings.WSPolicy.Elements.Policy, node.LocalName, node.NamespaceURI); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString)); } return (XmlElement)node; } class Wsrm11PolicyAlternative { bool hasValidPolicy = true; bool isOrdered = false; public bool HasValidPolicy { get { return this.hasValidPolicy; } } public static Wsrm11PolicyAlternative ImportAlternative(MetadataImporter importer, IEnumerable<XmlElement> alternative) { State state = State.Security; Wsrm11PolicyAlternative wsrmPolicy = new Wsrm11PolicyAlternative(); foreach (XmlElement node in alternative) { if (state == State.Security) { state = State.DeliveryAssurance; if (wsrmPolicy.TryImportSequenceSTR(node)) { continue; } } if (state == State.DeliveryAssurance) { state = State.Done; if (wsrmPolicy.TryImportDeliveryAssurance(importer, node)) { continue; } } string exceptionString = SR.GetString(SR.UnexpectedXmlChildNode, node.LocalName, node.NodeType, ReliableSessionPolicyStrings.ReliableSessionName); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString)); } return wsrmPolicy; } public static void ThrowInvalidBindingException() { string exceptionString = SR.GetString(SR.AssertionNotSupported, ReliableSessionPolicyStrings.ReliableSession11Prefix, ReliableSessionPolicyStrings.SequenceTransportSecurity); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString)); } public void TransferSettings(ReliableSessionBindingElement settings) { settings.Ordered = this.isOrdered; } bool TryImportSequenceSTR(XmlElement node) { string wsrmNs = ReliableSessionPolicyStrings.ReliableSession11Namespace; if (IsElement(node, wsrmNs, ReliableSessionPolicyStrings.SequenceSTR)) { return true; } if (IsElement(node, wsrmNs, ReliableSessionPolicyStrings.SequenceTransportSecurity)) { this.hasValidPolicy = false; return true; } return false; } bool TryImportDeliveryAssurance(MetadataImporter importer, XmlElement node) { string wsrmNs = ReliableSessionPolicyStrings.ReliableSession11Namespace; if (!IsElement(node, wsrmNs, ReliableSessionPolicyStrings.DeliveryAssurance)) { return false; } // Policy IEnumerator policyNodes = node.ChildNodes.GetEnumerator(); XmlNode policyNode = SkipToNode(policyNodes); XmlElement policyElement = ThrowIfNotPolicyElement(policyNode, ReliableMessagingVersion.WSReliableMessaging11); IEnumerable<IEnumerable<XmlElement>> alternatives = importer.NormalizePolicy(new XmlElement[] { policyElement }); foreach (IEnumerable<XmlElement> alternative in alternatives) { State state = State.Assurance; foreach (XmlElement element in alternative) { if (state == State.Assurance) { state = State.Order; if (!IsElement(element, wsrmNs, ReliableSessionPolicyStrings.ExactlyOnce) && !IsElement(element, wsrmNs, ReliableSessionPolicyStrings.AtMostOnce) && !IsElement(element, wsrmNs, ReliableSessionPolicyStrings.AtMostOnce)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString( SR.DeliveryAssuranceRequired, wsrmNs, element.LocalName, element.NamespaceURI))); } // Found required DeliveryAssurance, ignore the value and skip to InOrder continue; } if (state == State.Order) { state = State.Done; // InOrder if (IsElement(element, wsrmNs, ReliableSessionPolicyStrings.InOrder)) { // set ordered if (!this.isOrdered) { this.isOrdered = true; } continue; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString( SR.UnexpectedXmlChildNode, element.LocalName, element.NodeType, ReliableSessionPolicyStrings.DeliveryAssurance))); } if (state == State.Assurance) { string exceptionString = SR.GetString(SR.DeliveryAssuranceRequiredNothingFound, wsrmNs); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(exceptionString)); } } policyNode = SkipToNode(policyNodes); if (policyNode != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidChannelBindingException(SR.GetString( SR.UnexpectedXmlChildNode, policyNode.LocalName, policyNode.NodeType, node.LocalName))); } return true; } } enum State { Security, DeliveryAssurance, Assurance, Order, InactivityTimeout, AcknowledgementInterval, Done, } } }
// CommandLineParser.cs using System; using System.Collections; namespace SevenZip.CommandLineParser { public enum SwitchType { Simple, PostMinus, LimitedPostString, UnLimitedPostString, PostChar } public class SwitchForm { public string IDString; public SwitchType Type; public bool Multi; public int MinLen; public int MaxLen; public string PostCharSet; public SwitchForm(string idString, SwitchType type, bool multi, int minLen, int maxLen, string postCharSet) { IDString = idString; Type = type; Multi = multi; MinLen = minLen; MaxLen = maxLen; PostCharSet = postCharSet; } public SwitchForm(string idString, SwitchType type, bool multi, int minLen) : this(idString, type, multi, minLen, 0, "") { } public SwitchForm(string idString, SwitchType type, bool multi) : this(idString, type, multi, 0) { } } public class SwitchResult { public bool ThereIs; public bool WithMinus; public ArrayList PostStrings = new ArrayList(); public int PostCharIndex; public SwitchResult() { ThereIs = false; } } public class Parser { public ArrayList NonSwitchStrings = new ArrayList(); SwitchResult[] _switches; public Parser(int numSwitches) { _switches = new SwitchResult[numSwitches]; for (int i = 0; i < numSwitches; i++) _switches[i] = new SwitchResult(); } bool ParseString(string srcString, SwitchForm[] switchForms) { int len = srcString.Length; if (len == 0) return false; int pos = 0; if (!IsItSwitchChar(srcString[pos])) return false; while (pos < len) { if (IsItSwitchChar(srcString[pos])) pos++; const int kNoLen = -1; int matchedSwitchIndex = 0; int maxLen = kNoLen; for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) { int switchLen = switchForms[switchIndex].IDString.Length; if (switchLen <= maxLen || pos + switchLen > len) continue; if (String.Compare(switchForms[switchIndex].IDString, 0, srcString, pos, switchLen, true) == 0) { matchedSwitchIndex = switchIndex; maxLen = switchLen; } } if (maxLen == kNoLen) throw new Exception("maxLen == kNoLen"); SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; SwitchForm switchForm = switchForms[matchedSwitchIndex]; if ((!switchForm.Multi) && matchedSwitch.ThereIs) throw new Exception("switch must be single"); matchedSwitch.ThereIs = true; pos += maxLen; int tailSize = len - pos; SwitchType type = switchForm.Type; switch (type) { case SwitchType.PostMinus: { if (tailSize == 0) matchedSwitch.WithMinus = false; else { matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); if (matchedSwitch.WithMinus) pos++; } break; } case SwitchType.PostChar: { if (tailSize < switchForm.MinLen) throw new Exception("switch is not full"); string charSet = switchForm.PostCharSet; const int kEmptyCharValue = -1; if (tailSize == 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { int index = charSet.IndexOf(srcString[pos]); if (index < 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { matchedSwitch.PostCharIndex = index; pos++; } } break; } case SwitchType.LimitedPostString: case SwitchType.UnLimitedPostString: { int minLen = switchForm.MinLen; if (tailSize < minLen) throw new Exception("switch is not full"); if (type == SwitchType.UnLimitedPostString) { matchedSwitch.PostStrings.Add(srcString.Substring(pos)); return true; } String stringSwitch = srcString.Substring(pos, minLen); pos += minLen; for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) { char c = srcString[pos]; if (IsItSwitchChar(c)) break; stringSwitch += c; } matchedSwitch.PostStrings.Add(stringSwitch); break; } } } return true; } public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) { int numCommandStrings = commandStrings.Length; bool stopSwitch = false; for (int i = 0; i < numCommandStrings; i++) { string s = commandStrings[i]; if (stopSwitch) NonSwitchStrings.Add(s); else if (s == kStopSwitchParsing) stopSwitch = true; else if (!ParseString(s, switchForms)) NonSwitchStrings.Add(s); } } public SwitchResult this[int index] { get { return _switches[index]; } } public static int ParseCommand(CommandForm[] commandForms, string commandString, out string postString) { for (int i = 0; i < commandForms.Length; i++) { string id = commandForms[i].IDString; if (commandForms[i].PostStringMode) { if (commandString.IndexOf(id) == 0) { postString = commandString.Substring(id.Length); return i; } } else if (commandString == id) { postString = ""; return i; } } postString = ""; return -1; } static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, string commandString, ArrayList indices) { indices.Clear(); int numUsedChars = 0; for (int i = 0; i < numForms; i++) { CommandSubCharsSet charsSet = forms[i]; int currentIndex = -1; int len = charsSet.Chars.Length; for (int j = 0; j < len; j++) { char c = charsSet.Chars[j]; int newIndex = commandString.IndexOf(c); if (newIndex >= 0) { if (currentIndex >= 0) return false; if (commandString.IndexOf(c, newIndex + 1) >= 0) return false; currentIndex = j; numUsedChars++; } } if (currentIndex == -1 && !charsSet.EmptyAllowed) return false; indices.Add(currentIndex); } return (numUsedChars == commandString.Length); } const char kSwitchID1 = '-'; const char kSwitchID2 = '/'; const char kSwitchMinus = '-'; const string kStopSwitchParsing = "--"; static bool IsItSwitchChar(char c) { return (c == kSwitchID1 || c == kSwitchID2); } } public class CommandForm { public string IDString = ""; public bool PostStringMode = false; public CommandForm(string idString, bool postStringMode) { IDString = idString; PostStringMode = postStringMode; } } class CommandSubCharsSet { public string Chars = ""; public bool EmptyAllowed = false; } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace LumiSoft.Net { #region enum AuthType /// <summary> /// Authentication type. /// </summary> public enum AuthType { /// <summary> /// Plain username/password authentication. /// </summary> Plain = 0, /// <summary> /// APOP /// </summary> APOP = 1, /// <summary> /// Not implemented. /// </summary> LOGIN = 2, /// <summary> /// Cram-md5 authentication. /// </summary> CRAM_MD5 = 3, /// <summary> /// DIGEST-md5 authentication. /// </summary> DIGEST_MD5 = 4, } #endregion /// <summary> /// Provides net core utility methods. /// </summary> public class Core { #region method DoPeriodHandling /// <summary> /// Does period handling. /// </summary> /// <param name="data"></param> /// <param name="add_Remove">If true add periods, else removes periods.</param> /// <returns></returns> public static MemoryStream DoPeriodHandling(byte[] data,bool add_Remove) { using(MemoryStream strm = new MemoryStream(data)){ return DoPeriodHandling(strm,add_Remove); } } /// <summary> /// Does period handling. /// </summary> /// <param name="strm">Input stream.</param> /// <param name="add_Remove">If true add periods, else removes periods.</param> /// <returns></returns> public static MemoryStream DoPeriodHandling(Stream strm,bool add_Remove) { return DoPeriodHandling(strm,add_Remove,true); } /// <summary> /// Does period handling. /// </summary> /// <param name="strm">Input stream.</param> /// <param name="add_Remove">If true add periods, else removes periods.</param> /// <param name="setStrmPosTo0">If true sets stream position to 0.</param> /// <returns></returns> public static MemoryStream DoPeriodHandling(Stream strm,bool add_Remove,bool setStrmPosTo0) { MemoryStream replyData = new MemoryStream(); byte[] crlf = new byte[]{(byte)'\r',(byte)'\n'}; if(setStrmPosTo0){ strm.Position = 0; } StreamLineReader r = new StreamLineReader(strm); byte[] line = r.ReadLine(); // Loop through all lines while(line != null){ if(line.Length > 0){ if(line[0] == (byte)'.'){ /* Add period Rfc 2821 4.5.2 - Before sending a line of mail text, the SMTP client checks the first character of the line. If it is a period, one additional period is inserted at the beginning of the line. */ if(add_Remove){ replyData.WriteByte((byte)'.'); replyData.Write(line,0,line.Length); } /* Remove period Rfc 2821 4.5.2 If the first character is a period , the first characteris deleted. */ else{ replyData.Write(line,1,line.Length-1); } } else{ replyData.Write(line,0,line.Length); } } replyData.Write(crlf,0,crlf.Length); // Read next line line = r.ReadLine(); } replyData.Position = 0; return replyData; } #endregion #region method ScanInvalid_CR_or_LF /// <summary> /// Scans invalid CR or LF combination in stream. Returns true if contains invalid CR or LF combination. /// </summary> /// <param name="strm">Stream which to check.</param> /// <returns>Returns true if contains invalid CR or LF combination.</returns> public static bool ScanInvalid_CR_or_LF(Stream strm) { StreamLineReader lineReader = new StreamLineReader(strm); byte[] line = lineReader.ReadLine(); while(line != null){ foreach(byte b in line){ // Contains CR or LF. It cannot conatian such sumbols, because CR must be paired with LF // and we currently reading lines with CRLF combination. if(b == 10 || b == 13){ return true; } } line = lineReader.ReadLine(); } return false; } #endregion #region method GetHostName /// <summary> /// Gets host name. If fails returns 'UnkownHost'. /// </summary> /// <param name="IP"></param> /// <returns></returns> public static string GetHostName(IPAddress IP) { // ToDo: use LS dns client instead, ms is slow try{ return System.Net.Dns.GetHostByAddress(IP).HostName; } catch{ return "UnknownHost"; } } #endregion #region method GetArgsText /// <summary> /// Gets argument part of command text. /// </summary> /// <param name="input">Input srting from where to remove value.</param> /// <param name="cmdTxtToRemove">Command text which to remove.</param> /// <returns></returns> public static string GetArgsText(string input,string cmdTxtToRemove) { string buff = input.Trim(); if(buff.Length >= cmdTxtToRemove.Length){ buff = buff.Substring(cmdTxtToRemove.Length); } buff = buff.Trim(); return buff; } #endregion #region method IsNumber /// <summary> /// Checks if specified string is number(long). /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumber(string str) { try{ Convert.ToInt64(str); return true; } catch{ return false; } } #endregion #region method Base64Encode /// <summary> /// Encodes data with base64 encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <returns></returns> public static byte[] Base64Encode(byte[] data) { MemoryStream base64Data = new MemoryStream(System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(data))); // System encode won't split base64 data to lines, we need to do it manually MemoryStream retVal = new MemoryStream(); while(true){ byte[] dataLine = new byte[76]; int readedCount = base64Data.Read(dataLine,0,dataLine.Length); // End of stream reached, end reading if(readedCount == 0){ break; } retVal.Write(dataLine,0,readedCount); retVal.Write(new byte[]{(byte)'\r',(byte)'\n'},0,2); } return retVal.ToArray(); } #endregion #region method Base64Decode /// <summary> /// Decodes base64 data. /// </summary> /// <param name="base64Data">Base64 decoded data.</param> /// <returns></returns> public static byte[] Base64Decode(byte[] base64Data) { string dataStr = System.Text.Encoding.Default.GetString(base64Data); if(dataStr.Trim().Length > 0){ return Convert.FromBase64String(dataStr); } else{ return new byte[]{}; } } #endregion #region method QuotedPrintableEncode /// <summary> /// Encodes data with quoted-printable encoding. /// </summary> /// <param name="data">Data to encode.</param> /// <returns></returns> public static byte[] QuotedPrintableEncode(byte[] data) { /* Rfc 2045 6.7. Quoted-Printable Content-Transfer-Encoding (2) (Literal representation) Octets with decimal values of 33 through 60 inclusive, and 62 through 126, inclusive, MAY be represented as the US-ASCII characters which correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN through TILDE, respectively). (3) (White Space) Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line. You must encode it =XX. (5) Encoded lines must not be longer than 76 characters, not counting the trailing CRLF. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks must be used. An equal sign as the last character on a encoded line indicates such a non-significant ("soft") line break in the encoded text. *) If binary data is encoded in quoted-printable, care must be taken to encode CR and LF characters as "=0D" and "=0A", respectively. */ int lineLength = 0; // Encode bytes <= 33 , >= 126 and 61 (=) MemoryStream retVal = new MemoryStream(); foreach(byte b in data){ // Suggested line length is exceeded, add soft line break if(lineLength > 75){ retVal.Write(new byte[]{(byte)'=',(byte)'\r',(byte)'\n'},0,3); lineLength = 0; } // We need to encode that byte if(b <= 33 || b >= 126 || b == 61){ retVal.Write(new byte[]{(byte)'='},0,1); retVal.Write(Core.ToHex(b),0,2); lineLength += 3; } // We don't need to encode that byte, just write it to stream else{ retVal.WriteByte(b); lineLength++; } } return retVal.ToArray(); } #endregion #region method QuotedPrintableDecode /// <summary> /// quoted-printable decoder. /// </summary> /// <param name="encoding">Input string encoding.</param> /// <param name="data">Data which to encode.</param> /// <param name="includeCRLF">Specified if line breaks are included or skipped.</param> /// <returns>Returns decoded data with specified encoding.</returns> public static string QuotedPrintableDecode(System.Text.Encoding encoding,byte[] data,bool includeCRLF) { return encoding.GetString(QuotedPrintableDecodeB(data,includeCRLF)); } /// <summary> /// quoted-printable decoder. /// </summary> /// <param name="data">Data which to encode.</param> /// <param name="includeCRLF">Specified if line breaks are included or skipped. For text data CRLF is usually included and for binary data excluded.</param> /// <returns>Returns decoded data.</returns> public static byte[] QuotedPrintableDecodeB(byte[] data,bool includeCRLF) { MemoryStream strm = new MemoryStream(data); MemoryStream dStrm = new MemoryStream(); int b = strm.ReadByte(); while(b > -1){ // Hex eg. =E4 if(b == '='){ byte[] buf = new byte[2]; strm.Read(buf,0,2); // <CRLF> followed by =, it's splitted line if(!(buf[0] == '\r' && buf[1] == '\n')){ try{ byte[] convertedByte = FromHex(buf); dStrm.Write(convertedByte,0,convertedByte.Length); } catch{ // If worng hex value, just skip this chars } } } else{ // For text line breaks are included, for binary data they are excluded if(includeCRLF){ dStrm.WriteByte((byte)b); } else{ // Skip \r\n they must be escaped if(b != '\r' && b != '\n'){ dStrm.WriteByte((byte)b); } } } b = strm.ReadByte(); } return dStrm.ToArray(); } #endregion #region method QDecode /// <summary> /// "Q" decoder. This is same as quoted-printable, except '_' is converted to ' '. /// </summary> /// <param name="encoding">Input string encoding.</param> /// <param name="data">String which to encode.</param> /// <returns>Returns decoded string.</returns> public static string QDecode(System.Text.Encoding encoding,string data) { return QuotedPrintableDecode(encoding,System.Text.Encoding.ASCII.GetBytes(data.Replace("_"," ")),true); // REMOVEME: // 15.09.2004 - replace must be done before encoding // return QuotedPrintableDecode(encoding,System.Text.Encoding.ASCII.GetBytes(data)).Replace("_"," "); } #endregion #region method CanonicalDecode /// <summary> /// Canonical decoding. Decodes all canonical encoding occurences in specified text. /// Usually mime message header unicode/8bit values are encoded as Canonical. /// Format: =?charSet?type[Q or B]?encoded_string?= . /// Defined in RFC 2047. /// </summary> /// <param name="text">Text to decode.</param> /// <returns></returns> public static string CanonicalDecode(string text) { /* RFC 2047 Generally, an "encoded-word" is a sequence of printable ASCII characters that begins with "=?", ends with "?=", and has two "?"s in between. Syntax: =?charSet?type[Q or B]?encoded_string?= Examples: =?utf-8?q?Buy a Rolex?= =?iso-8859-1?B?bORs5D8=?= */ StringBuilder retVal = new StringBuilder(); int offset = 0; while(offset < text.Length){ // Search start and end of canonical entry int iStart = text.IndexOf("=?",offset); int iEnd = -1; if(iStart > -1){ // End index must be over start index position iEnd = text.IndexOf("?=",iStart + 2); } if(iStart > -1 && iEnd > -1){ // Add left side non encoded text of encoded text, if there is any if((iStart - offset) > 0){ retVal.Append(text.Substring(offset,iStart - offset)); } while(true){ // Check if it is encoded entry string[] charset_type_text = text.Substring(iStart + 2,iEnd - iStart - 2).Split('?'); if(charset_type_text.Length == 3){ // Try to parse encoded text try{ Encoding enc = Encoding.GetEncoding(charset_type_text[0]); // QEecoded text if(charset_type_text[1].ToLower() == "q"){ retVal.Append(Core.QDecode(enc,charset_type_text[2])); } // Base64 encoded text else{ retVal.Append(enc.GetString(Core.Base64Decode(Encoding.Default.GetBytes(charset_type_text[2])))); } } catch{ // Parsing failed, just leave text as is. retVal.Append(text.Substring(iStart,iEnd - iStart + 2)); } // Move current offset in string offset = iEnd + 2; break; } // This isn't right end tag, try next else if(charset_type_text.Length < 3){ // Try next end tag iEnd = text.IndexOf("?=",iEnd + 2); // No suitable end tag for active start tag, move offset over start tag. if(iEnd == -1){ retVal.Append("=?"); offset = iStart + 2; break; } } // Illegal start tag or start tag is just in side some text, move offset over start tag. else{ retVal.Append("=?"); offset = iStart + 2; break; } } } // There are no more entries else{ // Add remaining non encoded text, if there is any. if(text.Length > offset){ retVal.Append(text.Substring(offset)); offset = text.Length; } } } return retVal.ToString(); } /* /// <summary> /// Canonical decoding. Decodes all canonical encoding occurences in specified text. /// Usually mime message header unicode/8bit values are encoded as Canonical. /// Format: =?charSet?type[Q or B]?encoded string?= . /// Defined in RFC 2047. /// </summary> /// <param name="text">Text to decode.</param> /// <returns>Returns decoded text.</returns> public static string CanonicalDecode(string text) { // =?charSet?type[Q or B]?encoded string?= // // Examples: // =?utf-8?q?Buy a Rolex?= // =?ISO-8859-1?Q?Asb=F8rn_Miken?= Regex regex = new Regex(@"\=\?(?<charSet>[\w\-]*)\?(?<type>[qQbB])\?(?<text>[\w\s_\-=*+;:,./]*)\?\="); MatchCollection m = regex.Matches(text); foreach(Match match in m){ try{ System.Text.Encoding enc = System.Text.Encoding.GetEncoding(match.Groups["charSet"].Value); // QDecode if(match.Groups["type"].Value.ToLower() == "q"){ text = text.Replace(match.Value,Core.QDecode(enc,match.Groups["text"].Value)); } // Base64 else{ text = text.Replace(match.Value,enc.GetString(Convert.FromBase64String(match.Groups["text"].Value))); } } catch{ // If parsing fails, just leave this string as is } } return text; } */ #endregion #region method CanonicalEncode /// <summary> /// Canonical encoding. /// </summary> /// <param name="str">String to encode.</param> /// <param name="charSet">With what charset to encode string. If you aren't sure about it, utf-8 is suggested.</param> /// <returns>Returns encoded text.</returns> public static string CanonicalEncode(string str,string charSet) { // Contains non ascii chars, need to encode if(!IsAscii(str)){ string retVal = "=?" + charSet + "?" + "B?"; retVal += Convert.ToBase64String(System.Text.Encoding.GetEncoding(charSet).GetBytes(str)); retVal += "?="; return retVal; } return str; } #endregion #region method IsAscii /// <summary> /// Checks if specified string data is acii data. /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsAscii(string data) { foreach(char c in data){ if((int)c > 127){ return false; } } return true; } #endregion #region method ToHex /// <summary> /// Convert byte to hex data. /// </summary> /// <param name="byteValue">Byte to convert.</param> /// <returns></returns> public static byte[] ToHex(byte byteValue) { return ToHex(new byte[]{byteValue}); } /// <summary> /// Converts data to hex data. /// </summary> /// <param name="data">Data to convert.</param> /// <returns></returns> public static byte[] ToHex(byte[] data) { char[] hexChars = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; MemoryStream retVal = new MemoryStream(data.Length * 2); foreach(byte b in data){ byte[] hexByte = new byte[2]; // left 4 bit of byte hexByte[0] = (byte)hexChars[(b & 0xF0) >> 4]; // right 4 bit of byte hexByte[1] = (byte)hexChars[b & 0x0F]; retVal.Write(hexByte,0,2); } return retVal.ToArray(); } #endregion #region method FromHex /// <summary> /// Converts hex byte data to normal byte data. Hex data must be in two bytes pairs, for example: 0F,FF,A3,... . /// </summary> /// <param name="hexData">Hex data.</param> /// <returns></returns> public static byte[] FromHex(byte[] hexData) { if(hexData.Length < 2 || (hexData.Length / (double)2 != Math.Floor(hexData.Length / (double)2))){ throw new Exception("Illegal hex data, hex data must be in two bytes pairs, for example: 0F,FF,A3,... ."); } MemoryStream retVal = new MemoryStream(hexData.Length / 2); // Loop hex value pairs for(int i=0;i<hexData.Length;i+=2){ byte[] hexPairInDecimal = new byte[2]; // We need to convert hex char to decimal number, for example F = 15 for(int h=0;h<2;h++){ if(((char)hexData[i + h]) == '0'){ hexPairInDecimal[h] = 0; } else if(((char)hexData[i + h]) == '1'){ hexPairInDecimal[h] = 1; } else if(((char)hexData[i + h]) == '2'){ hexPairInDecimal[h] = 2; } else if(((char)hexData[i + h]) == '3'){ hexPairInDecimal[h] = 3; } else if(((char)hexData[i + h]) == '4'){ hexPairInDecimal[h] = 4; } else if(((char)hexData[i + h]) == '5'){ hexPairInDecimal[h] = 5; } else if(((char)hexData[i + h]) == '6'){ hexPairInDecimal[h] = 6; } else if(((char)hexData[i + h]) == '7'){ hexPairInDecimal[h] = 7; } else if(((char)hexData[i + h]) == '8'){ hexPairInDecimal[h] = 8; } else if(((char)hexData[i + h]) == '9'){ hexPairInDecimal[h] = 9; } else if(((char)hexData[i + h]) == 'A' || ((char)hexData[i + h]) == 'a'){ hexPairInDecimal[h] = 10; } else if(((char)hexData[i + h]) == 'B' || ((char)hexData[i + h]) == 'b'){ hexPairInDecimal[h] = 11; } else if(((char)hexData[i + h]) == 'C' || ((char)hexData[i + h]) == 'c'){ hexPairInDecimal[h] = 12; } else if(((char)hexData[i + h]) == 'D' || ((char)hexData[i + h]) == 'd'){ hexPairInDecimal[h] = 13; } else if(((char)hexData[i + h]) == 'E' || ((char)hexData[i + h]) == 'e'){ hexPairInDecimal[h] = 14; } else if(((char)hexData[i + h]) == 'F' || ((char)hexData[i + h]) == 'f'){ hexPairInDecimal[h] = 15; } } // Join hex 4 bit(left hex cahr) + 4bit(right hex char) in bytes 8 it retVal.WriteByte((byte)((hexPairInDecimal[0] << 4) | hexPairInDecimal[1])); } return retVal.ToArray(); } #endregion } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using ESRI.ArcGIS.Geometry; namespace MultiPatchExamples { public static class RingGroupExamples { private static object _missing = Type.Missing; public static IGeometry GetExample1() { //RingGroup: Multiple Rings IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); //Ring 1 IPointCollection ring1PointCollection = new RingClass(); ring1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 1, 0), ref _missing, ref _missing); ring1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 4, 0), ref _missing, ref _missing); ring1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 4, 0), ref _missing, ref _missing); ring1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 1, 0), ref _missing, ref _missing); IRing ring1 = ring1PointCollection as IRing; ring1.Close(); multiPatchGeometryCollection.AddGeometry(ring1 as IGeometry, ref _missing, ref _missing); //Ring 2 IPointCollection ring2PointCollection = new RingClass(); ring2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -1, 0), ref _missing, ref _missing); ring2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, -1, 0), ref _missing, ref _missing); ring2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, -4, 0), ref _missing, ref _missing); ring2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -4, 0), ref _missing, ref _missing); IRing ring2 = ring2PointCollection as IRing; ring2.Close(); multiPatchGeometryCollection.AddGeometry(ring2 as IGeometry, ref _missing, ref _missing); //Ring 3 IPointCollection ring3PointCollection = new RingClass(); ring3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 1, 0), ref _missing, ref _missing); ring3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 1, 0), ref _missing, ref _missing); ring3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 4, 0), ref _missing, ref _missing); ring3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 4, 0), ref _missing, ref _missing); IRing ring3 = ring3PointCollection as IRing; ring3.Close(); multiPatchGeometryCollection.AddGeometry(ring3 as IGeometry, ref _missing, ref _missing); //Ring 4 IPointCollection ring4PointCollection = new RingClass(); ring4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -1, 0), ref _missing, ref _missing); ring4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -4, 0), ref _missing, ref _missing); ring4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, -4, 0), ref _missing, ref _missing); ring4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, -1, 0), ref _missing, ref _missing); IRing ring4 = ring4PointCollection as IRing; ring4.Close(); multiPatchGeometryCollection.AddGeometry(ring4 as IGeometry, ref _missing, ref _missing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample2() { //RingGroup: Multiple Exterior Rings With Corresponding Interior Rings IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Exterior Ring 1 IPointCollection exteriorRing1PointCollection = new RingClass(); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 1, 0), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 4, 0), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 4, 0), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 1, 0), ref _missing, ref _missing); IRing exteriorRing1 = exteriorRing1PointCollection as IRing; exteriorRing1.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing1, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 1 IPointCollection interiorRing1PointCollection = new RingClass(); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3.5, 1.5, 0), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3.5, 3.5, 0), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1.5, 3.5, 0), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1.5, 1.5, 0), ref _missing, ref _missing); IRing interiorRing1 = interiorRing1PointCollection as IRing; interiorRing1.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing1, esriMultiPatchRingType.esriMultiPatchInnerRing); //Exterior Ring 2 IPointCollection exteriorRing2PointCollection = new RingClass(); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -1, 0), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, -1, 0), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, -4, 0), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -4, 0), ref _missing, ref _missing); IRing exteriorRing2 = exteriorRing2PointCollection as IRing; exteriorRing2.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing2 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing2, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 2 IPointCollection interiorRing2PointCollection = new RingClass(); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1.5, -1.5, 0), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3.5, -1.5, 0), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3.5, -3.5, 0), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1.5, -3.5, 0), ref _missing, ref _missing); IRing interiorRing2 = interiorRing2PointCollection as IRing; interiorRing2.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing2 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing2, esriMultiPatchRingType.esriMultiPatchInnerRing); //Exterior Ring 3 IPointCollection exteriorRing3PointCollection = new RingClass(); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 1, 0), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 1, 0), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 4, 0), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 4, 0), ref _missing, ref _missing); IRing exteriorRing3 = exteriorRing3PointCollection as IRing; exteriorRing3.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing3 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing3, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 3 IPointCollection interiorRing3PointCollection = new RingClass(); interiorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1.5, 1.5, 0), ref _missing, ref _missing); interiorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3.5, 1.5, 0), ref _missing, ref _missing); interiorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3.5, 3.5, 0), ref _missing, ref _missing); interiorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1.5, 3.5, 0), ref _missing, ref _missing); IRing interiorRing3 = interiorRing3PointCollection as IRing; interiorRing3.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing3 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing3, esriMultiPatchRingType.esriMultiPatchInnerRing); //Exterior Ring 4 IPointCollection exteriorRing4PointCollection = new RingClass(); exteriorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -1, 0), ref _missing, ref _missing); exteriorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -4, 0), ref _missing, ref _missing); exteriorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, -4, 0), ref _missing, ref _missing); exteriorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, -1, 0), ref _missing, ref _missing); IRing exteriorRing4 = exteriorRing4PointCollection as IRing; exteriorRing4.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing4 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing4, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 4 IPointCollection interiorRing4PointCollection = new RingClass(); interiorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1.5, -1.5, 0), ref _missing, ref _missing); interiorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1.5, -3.5, 0), ref _missing, ref _missing); interiorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3.5, -3.5, 0), ref _missing, ref _missing); interiorRing4PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3.5, -1.5, 0), ref _missing, ref _missing); IRing interiorRing4 = interiorRing4PointCollection as IRing; interiorRing4.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing4 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing4, esriMultiPatchRingType.esriMultiPatchInnerRing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample3() { //RingGroup: Upright Square With Hole IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Exterior Ring 1 IPointCollection exteriorRing1PointCollection = new RingClass(); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, -5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, -5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, 5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 5), ref _missing, ref _missing); IRing exteriorRing1 = exteriorRing1PointCollection as IRing; exteriorRing1.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing1, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 1 IPointCollection interiorRing1PointCollection = new RingClass(); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 0, -4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 0, -4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 0, 4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 0, 4), ref _missing, ref _missing); IRing interiorRing1 = interiorRing1PointCollection as IRing; interiorRing1.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing1, esriMultiPatchRingType.esriMultiPatchInnerRing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample4() { //RingGroup: Upright Square Composed Of Multiple Exterior Rings And Multiple Interior Rings IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Exterior Ring 1 IPointCollection exteriorRing1PointCollection = new RingClass(); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, -5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, -5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, 5), ref _missing, ref _missing); exteriorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 5), ref _missing, ref _missing); IRing exteriorRing1 = exteriorRing1PointCollection as IRing; exteriorRing1.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing1, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 1 IPointCollection interiorRing1PointCollection = new RingClass(); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 0, -4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 0, -4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(4, 0, 4), ref _missing, ref _missing); interiorRing1PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-4, 0, 4), ref _missing, ref _missing); IRing interiorRing1 = interiorRing1PointCollection as IRing; interiorRing1.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing1 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing1, esriMultiPatchRingType.esriMultiPatchInnerRing); //Exterior Ring 2 IPointCollection exteriorRing2PointCollection = new RingClass(); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 0, -3), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 0, -3), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 0, 3), ref _missing, ref _missing); exteriorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 0, 3), ref _missing, ref _missing); IRing exteriorRing2 = exteriorRing2PointCollection as IRing; exteriorRing2.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing2 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing2, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring 2 IPointCollection interiorRing2PointCollection = new RingClass(); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2, 0, -2), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2, 0, -2), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(2, 0, 2), ref _missing, ref _missing); interiorRing2PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-2, 0, 2), ref _missing, ref _missing); IRing interiorRing2 = interiorRing2PointCollection as IRing; interiorRing2.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing2 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing2, esriMultiPatchRingType.esriMultiPatchInnerRing); //Exterior Ring 3 IPointCollection exteriorRing3PointCollection = new RingClass(); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 0, -1), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 0, -1), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 0, 1), ref _missing, ref _missing); exteriorRing3PointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 0, 1), ref _missing, ref _missing); IRing exteriorRing3 = exteriorRing3PointCollection as IRing; exteriorRing3.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing3 as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing3, esriMultiPatchRingType.esriMultiPatchOuterRing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample5() { const int XRange = 16; const int YRange = 16; const int InteriorRingCount = 25; const double HoleRange = 0.5; //RingGroup: Square Lying In XY Plane With Single Exterior Ring And Multiple Interior Rings IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Exterior Ring IPointCollection exteriorRingPointCollection = new RingClass(); exteriorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0.5 * (XRange + 2), -0.5 * (YRange + 2), 0), ref _missing, ref _missing); exteriorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-0.5 * (XRange + 2), -0.5 * (YRange + 2), 0), ref _missing, ref _missing); exteriorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-0.5 * (XRange + 2), 0.5 * (YRange + 2), 0), ref _missing, ref _missing); exteriorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(0.5 * (XRange + 2), 0.5 * (YRange + 2), 0), ref _missing, ref _missing); IRing exteriorRing = exteriorRingPointCollection as IRing; exteriorRing.Close(); multiPatchGeometryCollection.AddGeometry(exteriorRing as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(exteriorRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Rings Random random = new Random(); for (int i = 0; i < InteriorRingCount; i++) { double interiorRingOriginX = XRange * (random.NextDouble() - 0.5); double interiorRingOriginY = YRange * (random.NextDouble() - 0.5); IPointCollection interiorRingPointCollection = new RingClass(); interiorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(interiorRingOriginX - 0.5 * HoleRange, interiorRingOriginY - 0.5 * HoleRange, 0), ref _missing, ref _missing); interiorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(interiorRingOriginX + 0.5 * HoleRange, interiorRingOriginY - 0.5 * HoleRange, 0), ref _missing, ref _missing); interiorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(interiorRingOriginX + 0.5 * HoleRange, interiorRingOriginY + 0.5 * HoleRange, 0), ref _missing, ref _missing); interiorRingPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(interiorRingOriginX - 0.5 * HoleRange, interiorRingOriginY + 0.5 * HoleRange, 0), ref _missing, ref _missing); IRing interiorRing = interiorRingPointCollection as IRing; interiorRing.Close(); multiPatchGeometryCollection.AddGeometry(interiorRing as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(interiorRing, esriMultiPatchRingType.esriMultiPatchInnerRing); } return multiPatchGeometryCollection as IGeometry; } } }
using System; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for * Computer Science and RSA Data Security, Inc. * <p> * <b>NOTE</b>: This algorithm is only included for backwards compatibility * with legacy applications, it's not secure, don't use it for anything new!</p> */ public class MD4Digest : GeneralDigest { private const int DigestLength = 16; private int H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public MD4Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public MD4Digest(MD4Digest t) : base(t) { CopyIn(t); } private void CopyIn(MD4Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "MD4"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong) bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint) word >> 8); outBytes[outOff + 2] = (byte)((uint) word >> 16); outBytes[outOff + 3] = (byte)((uint) word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H1, output, outOff); UnpackWord(H2, output, outOff + 4); UnpackWord(H3, output, outOff + 8); UnpackWord(H4, output, outOff + 12); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H1 = unchecked((int) 0x67452301); H2 = unchecked((int) 0xefcdab89); H3 = unchecked((int) 0x98badcfe); H4 = unchecked((int) 0x10325476); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } // // round 1 left rotates // private const int S11 = 3; private const int S12 = 7; private const int S13 = 11; private const int S14 = 19; // // round 2 left rotates // private const int S21 = 3; private const int S22 = 5; private const int S23 = 9; private const int S24 = 13; // // round 3 left rotates // private const int S31 = 3; private const int S32 = 9; private const int S33 = 11; private const int S34 = 15; /* * rotate int x left n bits. */ private int RotateLeft( int x, int n) { return (x << n) | (int) ((uint) x >> (32 - n)); } /* * F, G, H and I are the basic MD4 functions. */ private int F( int u, int v, int w) { return (u & v) | (~u & w); } private int G( int u, int v, int w) { return (u & v) | (u & w) | (v & w); } private int H( int u, int v, int w) { return u ^ v ^ w; } internal override void ProcessBlock() { int a = H1; int b = H2; int c = H3; int d = H4; // // Round 1 - F cycle, 16 times. // a = RotateLeft((a + F(b, c, d) + X[ 0]), S11); d = RotateLeft((d + F(a, b, c) + X[ 1]), S12); c = RotateLeft((c + F(d, a, b) + X[ 2]), S13); b = RotateLeft((b + F(c, d, a) + X[ 3]), S14); a = RotateLeft((a + F(b, c, d) + X[ 4]), S11); d = RotateLeft((d + F(a, b, c) + X[ 5]), S12); c = RotateLeft((c + F(d, a, b) + X[ 6]), S13); b = RotateLeft((b + F(c, d, a) + X[ 7]), S14); a = RotateLeft((a + F(b, c, d) + X[ 8]), S11); d = RotateLeft((d + F(a, b, c) + X[ 9]), S12); c = RotateLeft((c + F(d, a, b) + X[10]), S13); b = RotateLeft((b + F(c, d, a) + X[11]), S14); a = RotateLeft((a + F(b, c, d) + X[12]), S11); d = RotateLeft((d + F(a, b, c) + X[13]), S12); c = RotateLeft((c + F(d, a, b) + X[14]), S13); b = RotateLeft((b + F(c, d, a) + X[15]), S14); // // Round 2 - G cycle, 16 times. // a = RotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24); a = RotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21); d = RotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22); c = RotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23); b = RotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24); // // Round 3 - H cycle, 16 times. // a = RotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34); a = RotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31); d = RotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32); c = RotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33); b = RotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34); H1 += a; H2 += b; H3 += c; H4 += d; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new MD4Digest(this); } public override void Reset(IMemoable other) { MD4Digest d = (MD4Digest)other; CopyIn(d); } } }
namespace AngleSharp.Core.Tests { using System; using AngleSharp.Core.Tests.Mocks; using AngleSharp.Dom; using NUnit.Framework; /// <summary> /// Tests from https://github.com/html5lib/html5lib-tests: /// tree-construction/tests5.dat /// </summary> [TestFixture] public class RawtextTests { static IDocument Html(String code) { return code.ToHtmlDocument(); } static IDocument HtmlWithScripting(String code) { var scripting = new EnableScripting(); var config = Configuration.Default.With(scripting); return code.ToHtmlDocument(config); } [Test] public void IllegalCommentStartInStyleElement() { var doc = Html(@"<style> <!-- </style>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0style0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0style0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0style0).Attributes.Length); Assert.AreEqual("style", dochtml0head0style0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0style0.NodeType); var dochtml0head0style0Text0 = dochtml0head0style0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0style0Text0.NodeType); Assert.AreEqual(" <!-- ", dochtml0head0style0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("x", dochtml0body1Text0.TextContent); } [Test] public void StartOfCommentInStyleElement() { var doc = Html(@"<style> <!-- </style> --> </style>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(2, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0style0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0style0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0style0).Attributes.Length); Assert.AreEqual("style", dochtml0head0style0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0style0.NodeType); var dochtml0head0style0Text0 = dochtml0head0style0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0style0Text0.NodeType); Assert.AreEqual(" <!-- ", dochtml0head0style0Text0.TextContent); var dochtml0head0Text1 = dochtml0head0.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0head0Text1.NodeType); Assert.AreEqual(" ", dochtml0head0Text1.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("--> x", dochtml0body1Text0.TextContent); } [Test] public void IllegalCommentInStyleTag() { var doc = Html(@"<style> <!--> </style>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0style0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0style0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0style0).Attributes.Length); Assert.AreEqual("style", dochtml0head0style0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0style0.NodeType); var dochtml0head0style0Text0 = dochtml0head0style0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0style0Text0.NodeType); Assert.AreEqual(" <!--> ", dochtml0head0style0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("x", dochtml0body1Text0.TextContent); } [Test] public void CommentInStyleElement() { var doc = Html(@"<style> <!---> </style>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0style0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0style0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0style0).Attributes.Length); Assert.AreEqual("style", dochtml0head0style0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0style0.NodeType); var dochtml0head0style0Text0 = dochtml0head0style0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0style0Text0.NodeType); Assert.AreEqual(" <!---> ", dochtml0head0style0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("x", dochtml0body1Text0.TextContent); } [Test] public void CommentInIframeElement() { var doc = Html(@"<iframe> <!---> </iframe>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(2, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1iframe0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1iframe0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1iframe0).Attributes.Length); Assert.AreEqual("iframe", dochtml0body1iframe0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1iframe0.NodeType); var dochtml0body1iframe0Text0 = dochtml0body1iframe0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1iframe0Text0.NodeType); Assert.AreEqual(" <!---> ", dochtml0body1iframe0Text0.TextContent); var dochtml0body1Text1 = dochtml0body1.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0body1Text1.NodeType); Assert.AreEqual("x", dochtml0body1Text1.TextContent); } [Test] public void StartOfCommentInIframeElement() { var doc = Html(@"<iframe> <!--- </iframe>->x</iframe> --> </iframe>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(2, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1iframe0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1iframe0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1iframe0).Attributes.Length); Assert.AreEqual("iframe", dochtml0body1iframe0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1iframe0.NodeType); var dochtml0body1iframe0Text0 = dochtml0body1iframe0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1iframe0Text0.NodeType); Assert.AreEqual(" <!--- ", dochtml0body1iframe0Text0.TextContent); var dochtml0body1Text1 = dochtml0body1.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0body1Text1.NodeType); Assert.AreEqual("->x --> x", dochtml0body1Text1.TextContent); } [Test] public void StartOfCommentInScriptElement() { var doc = Html(@"<script> <!-- </script> --> </script>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(2, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0script0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0script0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0script0).Attributes.Length); Assert.AreEqual("script", dochtml0head0script0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0script0.NodeType); var dochtml0head0script0Text0 = dochtml0head0script0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0script0Text0.NodeType); Assert.AreEqual(" <!-- ", dochtml0head0script0Text0.TextContent); var dochtml0head0Text1 = dochtml0head0.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0head0Text1.NodeType); Assert.AreEqual(" ", dochtml0head0Text1.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("--> x", dochtml0body1Text0.TextContent); } [Test] public void StartOfCommentInTitleElement() { var doc = Html(@"<title> <!-- </title> --> </title>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(2, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0title0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0title0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0title0).Attributes.Length); Assert.AreEqual("title", dochtml0head0title0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0title0.NodeType); var dochtml0head0title0Text0 = dochtml0head0title0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0title0Text0.NodeType); Assert.AreEqual(" <!-- ", dochtml0head0title0Text0.TextContent); var dochtml0head0Text1 = dochtml0head0.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0head0Text1.NodeType); Assert.AreEqual(" ", dochtml0head0Text1.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("--> x", dochtml0body1Text0.TextContent); } [Test] public void StartOfCommentInTextareaElement() { var doc = Html(@"<textarea> <!--- </textarea>->x</textarea> --> </textarea>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(2, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1textarea0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1textarea0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1textarea0).Attributes.Length); Assert.AreEqual("textarea", dochtml0body1textarea0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1textarea0.NodeType); var dochtml0body1textarea0Text0 = dochtml0body1textarea0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1textarea0Text0.NodeType); Assert.AreEqual(" <!--- ", dochtml0body1textarea0Text0.TextContent); var dochtml0body1Text1 = dochtml0body1.ChildNodes[1]; Assert.AreEqual(NodeType.Text, dochtml0body1Text1.NodeType); Assert.AreEqual("->x --> x", dochtml0body1Text1.TextContent); } [Test] public void RawtextHalfCommentInStyleElement() { var doc = Html(@"<style> <!</-- </style>x"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0style0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0style0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0style0).Attributes.Length); Assert.AreEqual("style", dochtml0head0style0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0style0.NodeType); var dochtml0head0style0Text0 = dochtml0head0style0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0style0Text0.NodeType); Assert.AreEqual(" <!</-- ", dochtml0head0style0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("x", dochtml0body1Text0.TextContent); } [Test] public void XmpInParagraphElement() { var doc = Html(@"<p><xmp></xmp>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(2, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1p0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(0, dochtml0body1p0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1p0).Attributes.Length); Assert.AreEqual("p", dochtml0body1p0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1p0.NodeType); var dochtml0body1xmp1 = dochtml0body1.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1xmp1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1xmp1).Attributes.Length); Assert.AreEqual("xmp", dochtml0body1xmp1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1xmp1.NodeType); } [Test] public void RawtextInXmpTag() { var doc = Html(@"<xmp> <!-- > --> </xmp>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1xmp0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1xmp0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1xmp0).Attributes.Length); Assert.AreEqual("xmp", dochtml0body1xmp0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1xmp0.NodeType); var dochtml0body1xmp0Text0 = dochtml0body1xmp0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1xmp0Text0.NodeType); Assert.AreEqual(" <!-- > --> ", dochtml0body1xmp0Text0.TextContent); } [Test] public void EntityInTitleTag() { var doc = Html(@"<title>&amp;</title>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0title0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0title0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0title0).Attributes.Length); Assert.AreEqual("title", dochtml0head0title0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0title0.NodeType); var dochtml0head0title0Text0 = dochtml0head0title0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0title0Text0.NodeType); Assert.AreEqual("&", dochtml0head0title0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); } [Test] public void CommentAndEntityInTitleText() { var doc = Html(@"<title><!--&amp;--></title>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0title0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0title0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0title0).Attributes.Length); Assert.AreEqual("title", dochtml0head0title0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0title0.NodeType); var dochtml0head0title0Text0 = dochtml0head0title0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0title0Text0.NodeType); Assert.AreEqual("<!--&-->", dochtml0head0title0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); } [Test] public void TitleTriggersRawtextMode() { var doc = Html(@"<title><!--</title>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0title0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0title0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0title0).Attributes.Length); Assert.AreEqual("title", dochtml0head0title0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0title0.NodeType); var dochtml0head0title0Text0 = dochtml0head0title0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0title0Text0.NodeType); Assert.AreEqual("<!--", dochtml0head0title0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); } [Test] public void NoScriptTriggersRawtextMode() { var doc = HtmlWithScripting(@"<noscript><!--</noscript>--></noscript>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0noscript0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0noscript0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0noscript0).Attributes.Length); Assert.AreEqual("noscript", dochtml0head0noscript0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0noscript0.NodeType); var dochtml0head0noscript0Text0 = dochtml0head0noscript0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0head0noscript0Text0.NodeType); Assert.AreEqual("<!--", dochtml0head0noscript0Text0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1Text0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1Text0.NodeType); Assert.AreEqual("-->", dochtml0body1Text0.TextContent); } [Test] public void NoScriptElementWithComment() { var doc = Html(@"<noscript><!--</noscript>--></noscript>"); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0head0noscript0 = dochtml0head0.ChildNodes[0]; Assert.AreEqual(1, dochtml0head0noscript0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0noscript0).Attributes.Length); Assert.AreEqual("noscript", dochtml0head0noscript0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0noscript0.NodeType); var dochtml0head0noscript0Comment0 = dochtml0head0noscript0.ChildNodes[0]; Assert.AreEqual(NodeType.Comment, dochtml0head0noscript0Comment0.NodeType); Assert.AreEqual(@"</noscript>", dochtml0head0noscript0Comment0.TextContent); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); } } }
namespace System.Workflow.ComponentModel.Design { #region Imports using System; using System.Drawing.Design; using System.ComponentModel; using System.ComponentModel.Design; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.CodeDom; using System.Workflow.ComponentModel.Compiler; using System.Collections.Specialized; using System.Diagnostics; using System.Text; #endregion #region Class ConditionDeclTypeConverter internal sealed class ConditionTypeConverter : TypeConverter { internal static readonly Type RuleConditionReferenceType = null; internal static readonly Type RuleDefinitionsType = null; internal static readonly Type CodeConditionType = null; internal static DependencyProperty DeclarativeConditionDynamicProp = null; private Hashtable conditionDecls = new Hashtable(); static ConditionTypeConverter() { RuleConditionReferenceType = Type.GetType("System.Workflow.Activities.Rules.RuleDefinitions, " + AssemblyRef.ActivitiesAssemblyRef); RuleDefinitionsType = Type.GetType("System.Workflow.Activities.Rules.RuleConditionReference, " + AssemblyRef.ActivitiesAssemblyRef); CodeConditionType = Type.GetType("System.Workflow.Activities.CodeCondition, " + AssemblyRef.ActivitiesAssemblyRef); DeclarativeConditionDynamicProp = (DependencyProperty)RuleConditionReferenceType.GetField("RuleDefinitionsProperty").GetValue(null); } public ConditionTypeConverter() { string key = CodeConditionType.FullName; object[] attributes = CodeConditionType.GetCustomAttributes(typeof(DisplayNameAttribute), false); if (attributes != null && attributes.Length > 0 && attributes[0] is DisplayNameAttribute) key = ((DisplayNameAttribute)attributes[0]).DisplayName; this.conditionDecls.Add(key, CodeConditionType); key = RuleDefinitionsType.FullName; attributes = RuleDefinitionsType.GetCustomAttributes(typeof(DisplayNameAttribute), false); if (attributes != null && attributes.Length > 0 && attributes[0] is DisplayNameAttribute) key = ((DisplayNameAttribute)attributes[0]).DisplayName; this.conditionDecls.Add(key, RuleDefinitionsType); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { if (((string)value).Length == 0 || ((string)value) == SR.GetString(SR.NullConditionExpression)) return null; else return Activator.CreateInstance(this.conditionDecls[value] as Type); } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; else return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value == null) return SR.GetString(SR.NullConditionExpression); object convertedValue = null; if (destinationType == typeof(string) && value is ActivityCondition) { foreach (DictionaryEntry conditionTypeEntry in this.conditionDecls) { if ((object)value.GetType() == conditionTypeEntry.Value) { convertedValue = conditionTypeEntry.Key; break; } } } if (convertedValue == null) convertedValue = base.ConvertTo(context, culture, value, destinationType); return convertedValue; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { ArrayList conditionDeclList = new ArrayList(); conditionDeclList.Add(null); foreach (object key in this.conditionDecls.Keys) { Type declType = this.conditionDecls[key] as Type; conditionDeclList.Add(Activator.CreateInstance(declType)); } return new StandardValuesCollection((ActivityCondition[])conditionDeclList.ToArray(typeof(ActivityCondition))); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = new PropertyDescriptorCollection(new PropertyDescriptor[] { }); TypeConverter typeConverter = TypeDescriptor.GetConverter(value.GetType()); if (typeConverter != null && typeConverter.GetType() != GetType() && typeConverter.GetPropertiesSupported()) { return typeConverter.GetProperties(context, value, attributes); } else { IComponent component = PropertyDescriptorUtils.GetComponent(context); if (component != null) props = PropertyDescriptorFilter.FilterProperties(component.Site, value, TypeDescriptor.GetProperties(value, new Attribute[] { BrowsableAttribute.Yes })); } return props; } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } #endregion #region ActivityBindTypeConverter [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ActivityBindTypeConverter : TypeConverter { public ActivityBindTypeConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) return actualConverter.CanConvertFrom(actualContext, sourceType); else if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string) && context != null && context.PropertyDescriptor != null) { ActivityBind activityBind = context.PropertyDescriptor.GetValue(context.Instance) as ActivityBind; if (activityBind != null) return true; } ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) return actualConverter.CanConvertTo(actualContext, destinationType); else if (destinationType == typeof(string)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object valueToConvert) { string value = valueToConvert as string; if (value == null) return base.ConvertFrom(context, culture, valueToConvert); //Trim the value value = value.Trim(); //Check if format is "Activity=, Path=" string[] splitParts = Parse(value); object convertedValue = (splitParts.Length == 2) ? new ActivityBind(splitParts[0], splitParts[1]) : null; if (convertedValue == null && (context == null || context.PropertyDescriptor == null)) return base.ConvertFrom(context, culture, valueToConvert); //For string's only if they begin and end with " we will use the type converter if (convertedValue == null) { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter) && actualConverter.CanConvertFrom(actualContext, typeof(string))) convertedValue = actualConverter.ConvertFrom(actualContext, culture, value); else convertedValue = valueToConvert; } return convertedValue; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); string convertedValue = null; ActivityBind activityBind = value as ActivityBind; if (activityBind != null) { Activity activity = PropertyDescriptorUtils.GetComponent(context) as Activity; activity = (activity != null) ? Helpers.ParseActivityForBind(activity, activityBind.Name) : null; convertedValue = String.Format(CultureInfo.InvariantCulture, ("Activity={0}, Path={1}"), (activity != null) ? activity.QualifiedName : activityBind.Name, activityBind.Path); } else { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter) && actualConverter.CanConvertTo(actualContext, destinationType)) convertedValue = actualConverter.ConvertTo(actualContext, culture, value, destinationType) as string; else convertedValue = base.ConvertTo(context, culture, value, destinationType) as string; } return convertedValue; } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { bool propertiesSupported = false; if (context != null && context.PropertyDescriptor != null) { ActivityBind activityBind = context.PropertyDescriptor.GetValue(context.Instance) as ActivityBind; if (activityBind != null) { propertiesSupported = true; } else { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) propertiesSupported = actualConverter.GetPropertiesSupported(actualContext); } } return propertiesSupported; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { ArrayList properties = new ArrayList(); ActivityBind activityBind = value as ActivityBind; if (activityBind != null && context != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value, new Attribute[] { BrowsableAttribute.Yes }); PropertyDescriptor activityDescriptor = props["Name"]; if (activityDescriptor != null) properties.Add(new ActivityBindNamePropertyDescriptor(context, activityDescriptor)); PropertyDescriptor pathDescriptor = props["Path"]; if (pathDescriptor != null) properties.Add(new ActivityBindPathPropertyDescriptor(context, pathDescriptor)); } else if (context != null && context.PropertyDescriptor != null) { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) properties.AddRange(actualConverter.GetProperties(actualContext, value, attributes)); } return new PropertyDescriptorCollection((PropertyDescriptor[])properties.ToArray(typeof(PropertyDescriptor))); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { ArrayList valuesList = new ArrayList(); if (context == null || context.PropertyDescriptor == null) return new StandardValuesCollection(new ArrayList()); //If the property type supports exclusive values then we need to add them to list ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetStandardValuesSupported(actualContext) && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) valuesList.AddRange(actualConverter.GetStandardValues(actualContext)); return new StandardValuesCollection(valuesList.ToArray()); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { //We do not support standard values through the bool standardValuesSupported = false; if (context != null && context.PropertyDescriptor != null) { object existingPropertyValue = (context.Instance != null) ? context.PropertyDescriptor.GetValue(context.Instance) : null; if (!(existingPropertyValue is ActivityBind)) { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) standardValuesSupported = actualConverter.GetStandardValuesSupported(actualContext); } } return standardValuesSupported; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { bool exclusiveValuesSupported = false; if (context != null && context.PropertyDescriptor != null) { object existingPropertyValue = (context.Instance != null) ? context.PropertyDescriptor.GetValue(context.Instance) : null; if (!(existingPropertyValue is ActivityBind)) { ITypeDescriptorContext actualContext = null; TypeConverter actualConverter = null; GetActualTypeConverterAndContext(context, out actualConverter, out actualContext); if (actualConverter != null && actualConverter.GetType() != typeof(ActivityBindTypeConverter)) exclusiveValuesSupported = actualConverter.GetStandardValuesExclusive(actualContext); } } return exclusiveValuesSupported; } #region Helper Methods private void GetActualTypeConverterAndContext(ITypeDescriptorContext currentContext, out TypeConverter realTypeConverter, out ITypeDescriptorContext realContext) { //The following case covers the scenario where we have users writting custom property descriptors in which they have returned custom type converters //In such cases we should honor the type converter returned by property descriptor only if it is not a ActivityBindTypeConverter //If it is ActivityBindTypeConveter then we should lookup the converter based on Property type //Please be care ful when you change this code as it will break ParameterInfoBasedPropertyDescriptor realContext = currentContext; realTypeConverter = null; if (currentContext != null && currentContext.PropertyDescriptor != null) { realTypeConverter = TypeDescriptor.GetConverter(currentContext.PropertyDescriptor.PropertyType); ActivityBindPropertyDescriptor activityBindPropertyDescriptor = currentContext.PropertyDescriptor as ActivityBindPropertyDescriptor; if (activityBindPropertyDescriptor != null && activityBindPropertyDescriptor.RealPropertyDescriptor != null && activityBindPropertyDescriptor.RealPropertyDescriptor.Converter != null && activityBindPropertyDescriptor.RealPropertyDescriptor.Converter.GetType() != typeof(ActivityBindTypeConverter)) { realTypeConverter = activityBindPropertyDescriptor.RealPropertyDescriptor.Converter; realContext = new TypeDescriptorContext(currentContext, activityBindPropertyDescriptor.RealPropertyDescriptor, currentContext.Instance); } } } private string[] Parse(string value) { string[] splitValues = value.Split(new char[] { ',' }, 2); //array could be multi-dimentional if (splitValues.Length == 2) { string activityIDMatch = "Activity="; string pathMatch = "Path="; string activityID = splitValues[0].Trim(); string path = splitValues[1].Trim(); if (activityID.StartsWith(activityIDMatch, StringComparison.OrdinalIgnoreCase) && path.StartsWith(pathMatch, StringComparison.OrdinalIgnoreCase)) { activityID = activityID.Substring(activityIDMatch.Length); path = path.Substring(pathMatch.Length); return new String[] { activityID, path }; } } return new string[] { }; } #endregion } #endregion #region ActivityBindPathTypeConverter internal sealed class ActivityBindPathTypeConverter : PropertyValueProviderTypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return new StringConverter().CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return new StringConverter().CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return new StringConverter().ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { return new StringConverter().ConvertTo(context, culture, value, destinationType); } } #endregion }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <[email protected]> using UnityEngine; using UnityEditor; using System; namespace AmplifyShaderEditor { public enum TexReferenceType { Object = 0, Instance } public enum MipType { Auto, MipLevel, MipBias, Derivative } [Serializable] [NodeAttributes( "Texture Sample", "Textures", "Samples a choosen texture a returns its color", KeyCode.T, true,0,typeof( Texture ), typeof( Texture2D ), typeof( Texture3D ), typeof( Cubemap ), typeof( ProceduralTexture ) )] public sealed class SamplerNode : TexturePropertyNode { private const string MipModeStr = "Mip Mode"; private const string DefaultTextureUseSematicsStr = "Use Semantics"; private const string DefaultTextureIsNormalMapsStr = "Is Normal Map"; private const string NormalScaleStr = "Scale"; private float InstanceIconWidth = 19; private float InstanceIconHeight = 19; private readonly Color ReferenceHeaderColor = new Color( 2.67f, 1.0f, 0.5f, 1.0f ); [SerializeField] private int m_textureCoordSet = 0; [SerializeField] private string m_normalMapUnpackMode; [SerializeField] private bool m_autoUnpackNormals = false; [SerializeField] private bool m_useSemantics; [SerializeField] private string m_samplerType; [SerializeField] private MipType m_mipMode = MipType.Auto; [SerializeField] private TexReferenceType m_referenceType = TexReferenceType.Object; [SerializeField] private int m_referenceArrayId = -1; [SerializeField] private int m_referenceNodeId = -1; private SamplerNode m_referenceSampler = null; [SerializeField] private GUIStyle m_referenceStyle = null; [SerializeField] private GUIStyle m_referenceIconStyle = null; [SerializeField] private GUIContent m_referenceContent = null; [SerializeField] private float m_referenceWidth = -1; private bool m_forceSamplerUpdate = false; private bool m_forceInputTypeCheck = false; private int m_cachedUvsId = -1; private int m_cachedUnpackId = -1; private int m_cachedLodId = -1; private InputPort m_texPort; private InputPort m_uvPort; private InputPort m_lodPort; private InputPort m_ddxPort; private InputPort m_ddyPort; private InputPort m_normalPort; private OutputPort m_colorPort; public SamplerNode() : base() { } public SamplerNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { } protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); m_defaultTextureValue = TexturePropertyValues.white; //m_extraSize.Set( 10, 0 ); AddInputPort( WirePortDataType.SAMPLER2D, false, "Tex" ); m_inputPorts[ 0 ].CreatePortRestrictions( WirePortDataType.SAMPLER1D, WirePortDataType.SAMPLER2D, WirePortDataType.SAMPLER3D, WirePortDataType.SAMPLERCUBE, WirePortDataType.OBJECT ); AddInputPort( WirePortDataType.FLOAT2, false, "UV" ); AddInputPort( WirePortDataType.FLOAT, false, "Level" ); AddInputPort( WirePortDataType.FLOAT2, false, "DDX" ); AddInputPort( WirePortDataType.FLOAT2, false, "DDY" ); AddInputPort( WirePortDataType.FLOAT, false, NormalScaleStr ); m_texPort = m_inputPorts[ 0 ]; m_uvPort = m_inputPorts[ 1 ]; m_lodPort = m_inputPorts[ 2 ]; m_ddxPort = m_inputPorts[ 3 ]; m_ddyPort = m_inputPorts[ 4 ]; m_normalPort = m_inputPorts[ 5 ]; m_lodPort.Visible = false; m_lodPort.FloatInternalData = 1.0f; m_ddxPort.Visible = false; m_ddyPort.Visible = false; m_normalPort.Visible = m_autoUnpackNormals; m_normalPort.FloatInternalData = 1.0f; //Remove output port (sampler) m_outputPortsDict.Remove( m_outputPorts[ 0 ].PortId ); m_outputPorts.RemoveAt( 0 ); AddOutputColorPorts( "RGBA" ); m_colorPort = m_outputPorts[ 0 ]; m_currentParameterType = PropertyType.Property; // m_useCustomPrefix = true; m_customPrefix = "Texture Sample "; m_referenceContent = new GUIContent( string.Empty ); m_freeType = false; m_useSemantics = true; m_drawPicker = false; ConfigTextureData( TextureType.Texture2D ); m_selectedLocation = PreviewLocation.TopCenter; m_previewShaderGUID = "7b4e86a89b70ae64993bf422eb406422"; } public override void SetPreviewInputs() { base.SetPreviewInputs(); if ( m_cachedUvsId == -1 ) m_cachedUvsId = Shader.PropertyToID( "_CustomUVs" ); if ( m_cachedSamplerId == -1 ) m_cachedSamplerId = Shader.PropertyToID( "_Sampler" ); if ( m_cachedUnpackId == -1 ) m_cachedUnpackId = Shader.PropertyToID( "_Unpack" ); if ( m_cachedLodId == -1 ) m_cachedLodId = Shader.PropertyToID( "_LodType" ); PreviewMaterial.SetFloat( m_cachedLodId, ( m_mipMode == MipType.MipLevel ? 1 : ( m_mipMode == MipType.MipBias ? 2 : 0 ) )); PreviewMaterial.SetFloat( m_cachedUnpackId, m_autoUnpackNormals ? 1 : 0 ); if ( SoftValidReference ) { PreviewMaterial.SetTexture( m_cachedSamplerId, m_referenceSampler.TextureProperty.Value ); } else { PreviewMaterial.SetTexture( m_cachedSamplerId, TextureProperty.Value ); } PreviewMaterial.SetFloat( m_cachedUvsId, (m_uvPort.IsConnected ? 1 : 0) ); } protected override void OnUniqueIDAssigned() { base.OnUniqueIDAssigned(); if ( m_referenceType == TexReferenceType.Object ) { UIUtils.RegisterSamplerNode( this ); UIUtils.RegisterPropertyNode( this ); } m_textureProperty = this; } public void ConfigSampler() { switch ( m_currentType ) { case TextureType.Texture1D: m_samplerType = "tex1D"; break; case TextureType.Texture2D: m_samplerType = "tex2D"; break; case TextureType.Texture3D: m_samplerType = "tex3D"; break; case TextureType.Cube: m_samplerType = "texCUBE"; break; } } public override void DrawSubProperties() { ShowDefaults(); DrawSamplerOptions(); EditorGUI.BeginChangeCheck(); m_defaultValue = EditorGUILayoutObjectField( Constants.DefaultValueLabel, m_defaultValue, m_textureType, false ) as Texture; if ( EditorGUI.EndChangeCheck() ) { CheckTextureImporter( true ); SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) ); ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } } public override void DrawMaterialProperties() { ShowDefaults(); DrawSamplerOptions(); EditorGUI.BeginChangeCheck(); m_materialValue = EditorGUILayoutObjectField( Constants.MaterialValueLabel, m_materialValue, m_textureType, false ) as Texture; if ( EditorGUI.EndChangeCheck() ) { CheckTextureImporter( true ); SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) ); ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } } new void ShowDefaults() { m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets ); m_defaultTextureValue = ( TexturePropertyValues ) EditorGUILayoutEnumPopup( DefaultTextureStr, m_defaultTextureValue ); AutoCastType newAutoCast = ( AutoCastType ) EditorGUILayoutEnumPopup( AutoCastModeStr, m_autocastMode ); if ( newAutoCast != m_autocastMode ) { m_autocastMode = newAutoCast; if ( m_autocastMode != AutoCastType.Auto ) { ConfigTextureData( m_currentType ); ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } } } public override void AdditionalCheck() { m_autoUnpackNormals = m_isNormalMap; ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true ) { base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode ); if ( portId == m_texPort.PortId ) { m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode; if ( m_textureProperty == null ) { m_textureProperty = this; } else { if ( m_autocastMode == AutoCastType.Auto ) { m_currentType = m_textureProperty.CurrentType; } AutoUnpackNormals = m_textureProperty.IsNormalMap; if ( m_textureProperty is VirtualTexturePropertyNode ) { AutoUnpackNormals = ( m_textureProperty as VirtualTexturePropertyNode ).Channel == VirtualChannel.Normal; } UIUtils.UnregisterPropertyNode( this ); UIUtils.UnregisterTexturePropertyNode( this ); } ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } } public override void OnInputPortDisconnected( int portId ) { base.OnInputPortDisconnected( portId ); if ( portId == m_texPort.PortId ) { m_textureProperty = this; if ( m_referenceType == TexReferenceType.Object ) { UIUtils.RegisterPropertyNode( this ); UIUtils.RegisterTexturePropertyNode( this ); } ConfigureOutputPorts(); ResizeNodeToPreview(); } } private void ForceInputPortsChange() { m_texPort.ChangeType( WirePortDataType.SAMPLER2D, false ); m_normalPort.ChangeType( WirePortDataType.FLOAT, false ); switch ( m_currentType ) { case TextureType.Texture2D: m_uvPort.ChangeType( WirePortDataType.FLOAT2, false ); m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false ); m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false ); break; case TextureType.Texture3D: case TextureType.Cube: m_uvPort.ChangeType( WirePortDataType.FLOAT3, false ); m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false ); m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false ); break; } } public override void ConfigureInputPorts() { m_normalPort.Visible = AutoUnpackNormals; switch ( m_mipMode ) { case MipType.Auto: m_lodPort.Visible = false; m_ddxPort.Visible = false; m_ddyPort.Visible = false; break; case MipType.MipLevel: m_lodPort.Name = "Level"; m_lodPort.Visible = true; m_ddxPort.Visible = false; m_ddyPort.Visible = false; break; case MipType.MipBias: m_lodPort.Name = "Bias"; m_lodPort.Visible = true; m_ddxPort.Visible = false; m_ddyPort.Visible = false; break; case MipType.Derivative: m_lodPort.Visible = false; m_ddxPort.Visible = true; m_ddyPort.Visible = true; break; } switch ( m_currentType ) { case TextureType.Texture2D: m_uvPort.ChangeType( WirePortDataType.FLOAT2, false ); m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false ); m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false ); break; case TextureType.Texture3D: case TextureType.Cube: m_uvPort.ChangeType( WirePortDataType.FLOAT3, false ); m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false ); m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false ); break; } m_sizeIsDirty = true; } public override void ConfigureOutputPorts() { m_outputPorts[ m_colorPort.PortId + 4 ].Visible = !AutoUnpackNormals; if ( !AutoUnpackNormals ) { m_colorPort.ChangeProperties( "RGBA", WirePortDataType.FLOAT4, false ); m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "R", WirePortDataType.FLOAT, false ); m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "G", WirePortDataType.FLOAT, false ); m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "B", WirePortDataType.FLOAT, false ); m_outputPorts[ m_colorPort.PortId + 4 ].ChangeProperties( "A", WirePortDataType.FLOAT, false ); } else { m_colorPort.ChangeProperties( "XYZ", WirePortDataType.FLOAT3, false ); m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "X", WirePortDataType.FLOAT, false ); m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "Y", WirePortDataType.FLOAT, false ); m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "Z", WirePortDataType.FLOAT, false ); } m_sizeIsDirty = true; } //public override void ResizeNodeToPreview() //{ // if ( AutoUnpackNormals ) // { // PreviewSizeX = 128; // PreviewSizeY = 128; // } // else // { // PreviewSizeX = 128; // PreviewSizeY = 128; // } // m_insideSize.Set( PreviewSizeX, PreviewSizeY + 5 ); // m_sizeIsDirty = true; //} public override void OnObjectDropped( UnityEngine.Object obj ) { base.OnObjectDropped( obj ); ConfigFromObject( obj ); } public override void SetupFromCastObject( UnityEngine.Object obj ) { base.SetupFromCastObject( obj ); ConfigFromObject( obj ); } void UpdateHeaderColor() { m_headerColorModifier = ( m_referenceType == TexReferenceType.Object ) ? Color.white : ReferenceHeaderColor; } public void DrawSamplerOptions() { MipType newMipMode = ( MipType ) EditorGUILayoutEnumPopup( MipModeStr, m_mipMode ); if ( newMipMode != m_mipMode ) { m_mipMode = newMipMode; ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } EditorGUI.BeginChangeCheck(); bool autoUnpackNormals = EditorGUILayoutToggle( "Normal Map", m_autoUnpackNormals ); if ( EditorGUI.EndChangeCheck() ) { if ( m_autoUnpackNormals != autoUnpackNormals ) { AutoUnpackNormals = autoUnpackNormals; ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } } if ( m_autoUnpackNormals && !m_normalPort.IsConnected ) { m_normalPort.FloatInternalData = EditorGUILayoutFloatField( NormalScaleStr, m_normalPort.FloatInternalData ); } } public override void DrawMainPropertyBlock() { EditorGUI.BeginChangeCheck(); //m_referenceType = ( TexReferenceType ) EditorGUILayout.EnumPopup( Constants.ReferenceTypeStr, m_referenceType ); m_referenceType = ( TexReferenceType ) EditorGUILayoutPopup( Constants.ReferenceTypeStr, (int)m_referenceType , Constants.ReferenceArrayLabels ); if ( EditorGUI.EndChangeCheck() ) { if ( m_referenceType == TexReferenceType.Object ) { UIUtils.RegisterSamplerNode( this ); UIUtils.RegisterPropertyNode( this ); if ( !m_texPort.IsConnected ) UIUtils.RegisterTexturePropertyNode( this ); SetTitleText( m_propertyInspectorName ); SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) ); m_referenceArrayId = -1; m_referenceNodeId = -1; m_referenceSampler = null; } else { UIUtils.UnregisterSamplerNode( this ); UIUtils.UnregisterPropertyNode( this ); if ( !m_texPort.IsConnected ) UIUtils.UnregisterTexturePropertyNode( this ); } UpdateHeaderColor(); } if ( m_referenceType == TexReferenceType.Object ) { EditorGUI.BeginChangeCheck(); base.DrawMainPropertyBlock(); if ( EditorGUI.EndChangeCheck() ) { OnPropertyNameChanged(); } } else { string[] arr = UIUtils.SamplerNodeArr(); bool guiEnabledBuffer = GUI.enabled; if ( arr != null && arr.Length > 0 ) { GUI.enabled = true; } else { m_referenceArrayId = -1; GUI.enabled = false; } m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId, arr ); GUI.enabled = guiEnabledBuffer; DrawSamplerOptions(); } } public override void OnPropertyNameChanged() { base.OnPropertyNameChanged(); UIUtils.UpdateSamplerDataNode( m_uniqueId, PropertyInspectorName ); } public override void Draw( DrawInfo drawInfo ) { base.Draw( drawInfo ); if ( m_forceInputTypeCheck ) { m_forceInputTypeCheck = false; ForceInputPortsChange(); } EditorGUI.BeginChangeCheck(); if ( m_forceSamplerUpdate ) { m_forceSamplerUpdate = false; if ( UIUtils.CurrentShaderVersion() > 22 ) { m_referenceSampler = UIUtils.GetNode( m_referenceNodeId ) as SamplerNode; //m_referenceArrayId = UIUtils.GetTexturePropertyNodeRegisterId( m_referenceNodeId ); m_referenceArrayId = UIUtils.GetSamplerNodeRegisterId( m_referenceNodeId ); } else { m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId ); if ( m_referenceSampler != null ) { m_referenceNodeId = m_referenceSampler.UniqueId; } } } if ( EditorGUI.EndChangeCheck() ) { OnPropertyNameChanged(); } if ( m_isVisible ) { if ( SoftValidReference ) { m_drawPicker = false; DrawTexturePropertyPreview( drawInfo, true ); } else if ( m_texPort.IsConnected ) { m_drawPicker = false; DrawTexturePropertyPreview( drawInfo, false ); } else { SetTitleText( m_propertyInspectorName ); SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) ); m_drawPicker = true; } } } public void SetTitleTextDelay( string newText ) { if ( !newText.Equals( m_content.text ) ) { m_content.text = newText; BeginDelayedDirtyProperty(); } } public void SetAdditonalTitleTextDelay( string newText ) { if ( !newText.Equals( m_additionalContent.text ) ) { m_additionalContent.text = newText; BeginDelayedDirtyProperty(); } } private void DrawTexturePropertyPreview( DrawInfo drawInfo, bool instance ) { Rect newPos = m_previewRect; TexturePropertyNode texProp = null; if ( instance ) texProp = m_referenceSampler.TextureProperty; else texProp = TextureProperty; if ( texProp == null ) texProp = this; float previewSizeX = PreviewSizeX; float previewSizeY = PreviewSizeY; newPos.width = previewSizeX * drawInfo.InvertedZoom; newPos.height = previewSizeY * drawInfo.InvertedZoom; SetTitleText( texProp.PropertyInspectorName + ( instance ? Constants.InstancePostfixStr : " (Input)" ) ); SetAdditonalTitleText( texProp.AdditonalTitleContent.text ); if ( m_referenceStyle == null ) { m_referenceStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef ); } if ( m_referenceIconStyle == null || m_referenceIconStyle.normal == null ) { m_referenceIconStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureIcon ); if ( m_referenceIconStyle != null && m_referenceIconStyle.normal != null && m_referenceIconStyle.normal.background != null) { InstanceIconWidth = m_referenceIconStyle.normal.background.width; InstanceIconHeight = m_referenceIconStyle.normal.background.height; } } Rect iconPos = m_globalPosition; iconPos.width = InstanceIconWidth * drawInfo.InvertedZoom; iconPos.height = InstanceIconHeight * drawInfo.InvertedZoom; iconPos.y += 10 * drawInfo.InvertedZoom; iconPos.x += m_globalPosition.width - iconPos.width - 5 * drawInfo.InvertedZoom; if ( GUI.Button( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef )/* m_referenceStyle */) || GUI.Button( iconPos, string.Empty, m_referenceIconStyle ) ) { UIUtils.FocusOnNode( texProp, 1, true ); } if ( texProp.Value != null ) { DrawPreview( drawInfo, m_previewRect ); //Rect butRect = m_previewRect; //butRect.y -= drawInfo.InvertedZoom; //DrawPreviewMaskButtons( drawInfo, butRect ); GUI.Box( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerFrame ) ); UIUtils.GetCustomStyle( CustomStyle.SamplerButton ).fontSize = ( int )Mathf.Round( 9 * drawInfo.InvertedZoom ); //EditorGUI.DrawPreviewTexture( newPos, texProp.Value ); } } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { if ( dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) { UIUtils.ShowMessage( m_nodeAttribs.Name + " cannot be used on Master Node Tessellation port" ); return "(-1)"; } OnPropertyNameChanged(); ConfigSampler(); if ( m_texPort.IsConnected ) m_texPort.GenerateShaderForOutput( ref dataCollector, m_texPort.DataType, ignoreLocalVar ); if ( m_autoUnpackNormals ) { bool isScaledNormal = false; if ( m_normalPort.IsConnected ) { isScaledNormal = true; } else { if ( m_normalPort.FloatInternalData != 1 ) { isScaledNormal = true; } } if ( isScaledNormal ) { string scaleValue = m_normalPort.GenerateShaderForOutput( ref dataCollector, m_normalPort.DataType, ignoreLocalVar ); dataCollector.AddToIncludes( m_uniqueId, Constants.UnityStandardUtilsLibFuncs ); m_normalMapUnpackMode = "UnpackScaleNormal( {0} ," + scaleValue + " )"; } else { m_normalMapUnpackMode = "UnpackNormal( {0} )"; } } base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar ); if ( !m_uvPort.IsConnected ) { SetUVChannelDeclaration( ref dataCollector ); } string valueName = SetFetchedData( ref dataCollector, ignoreLocalVar ); return GetOutputColorItem( 0, outputId, valueName ); } public string SetUVChannelDeclaration( ref MasterNodeDataCollector dataCollector, int customCoordSet = -1 ) { string propertyName = CurrentPropertyReference; int coordSet = ( ( customCoordSet < 0 ) ? m_textureCoordSet : customCoordSet ); //string uvChannelDeclaration = IOUtils.GetUVChannelDeclaration( propertyName, -1, coordSet ); //dataCollector.AddToInput( m_uniqueId, uvChannelDeclaration, true ); return IOUtils.GetUVChannelName( propertyName, coordSet ); } public string SampleVirtualTexture( VirtualTexturePropertyNode node, string coord ) { string sampler = string.Empty; switch ( node.Channel ) { default: case VirtualChannel.Albedo: case VirtualChannel.Base: sampler = "VTSampleAlbedo( " + coord + " )"; break; case VirtualChannel.Normal: case VirtualChannel.Height: case VirtualChannel.Occlusion: case VirtualChannel.Displacement: sampler = "VTSampleNormal( " + coord + " )"; break; case VirtualChannel.Specular: case VirtualChannel.SpecMet: case VirtualChannel.Material: sampler = "VTSampleSpecular( " + coord + " )"; break; } return sampler; } public string SetFetchedData( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { m_precisionString = UIUtils.PrecisionWirePortToCgType( UIUtils.GetFinalPrecision( m_currentPrecisionType ), m_colorPort.DataType ); string propertyName = CurrentPropertyReference; string mipType = ""; if ( m_lodPort.IsConnected ) { switch ( m_mipMode ) { case MipType.Auto: break; case MipType.MipLevel: mipType = "lod"; break; case MipType.MipBias: mipType = "bias"; break; case MipType.Derivative: break; } } if ( ignoreLocalVar ) { if ( TextureProperty is VirtualTexturePropertyNode ) Debug.Log( "TODO" ); if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) { mipType = "lod"; } string samplerValue = m_samplerType + mipType + "( " + propertyName + "," + GetUVCoords( ref dataCollector, ignoreLocalVar ) + ")"; AddNormalMapTag( ref samplerValue ); return samplerValue; } VirtualTexturePropertyNode vtex = ( TextureProperty as VirtualTexturePropertyNode ); if ( vtex != null ) { string atPathname = AssetDatabase.GUIDToAssetPath( Constants.ATSharedLibGUID ); if ( string.IsNullOrEmpty( atPathname ) ) { UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error ); } else { //Need to see if the asset really exists because AssetDatabase.GUIDToAssetPath() can return a valid path if // the asset was previously imported and deleted after that UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>( atPathname ); if ( obj == null ) { UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error ); } else { if ( m_isTextureFetched ) return m_textureFetchedValue; string remapPortR = ".r"; string remapPortG = ".g"; string remapPortB = ".b"; string remapPortA = ".a"; if ( vtex.Channel == VirtualChannel.Occlusion ) { remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r"; remapPortA = ".r"; } else if ( vtex.Channel == VirtualChannel.SpecMet && ( UIUtils.CurrentWindow.CurrentGraph.CurrentStandardSurface != null && UIUtils.CurrentWindow.CurrentGraph.CurrentStandardSurface.CurrentLightingModel == StandardShaderLightModel.Standard ) ) { remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r"; } else if ( vtex.Channel == VirtualChannel.Height || vtex.Channel == VirtualChannel.Displacement ) { remapPortR = ".b"; remapPortG = ".b"; remapPortB = ".b"; remapPortA = ".b"; } dataCollector.AddToPragmas( m_uniqueId, IOUtils.VirtualTexturePragmaHeader ); dataCollector.AddToIncludes( m_uniqueId, atPathname ); string lodBias = m_mipMode == MipType.MipLevel ? "Lod" : m_mipMode == MipType.MipBias ? "Bias" : ""; int virtualCoordId = dataCollector.GetVirtualCoordinatesId( m_uniqueId, GetVirtualUVCoords( ref dataCollector, ignoreLocalVar ), lodBias ); string virtualSampler = SampleVirtualTexture( vtex, Constants.VirtualCoordNameStr + virtualCoordId ); AddNormalMapTag( ref virtualSampler ); for ( int i = 0; i < m_outputPorts.Count; i++ ) { if ( m_outputPorts[ i ].IsConnected ) { //TODO: make the sampler not generate local variables at all times m_textureFetchedValue = "virtualNode" + m_uniqueId; m_isTextureFetched = true; //dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" ); if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) dataCollector.AddToVertexLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" ); else dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" ); m_colorPort.SetLocalValue( m_textureFetchedValue ); m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + remapPortR ); m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + remapPortG ); m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + remapPortB ); m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + remapPortA ); return m_textureFetchedValue; } } return virtualSampler; } } } if ( m_isTextureFetched ) return m_textureFetchedValue; if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) { mipType = "lod"; } string samplerOp = m_samplerType + mipType + "( " + propertyName + "," + GetUVCoords( ref dataCollector, ignoreLocalVar ) + ")"; AddNormalMapTag( ref samplerOp ); int connectedPorts = 0; for ( int i = 0; i < m_outputPorts.Count; i++ ) { if ( m_outputPorts[ i ].IsConnected ) { connectedPorts += 1; if ( connectedPorts > 1 || m_outputPorts[ i ].ConnectionCount > 1 ) { // Create common local var and mark as fetched m_textureFetchedValue = m_samplerType + "Node" + m_uniqueId; m_isTextureFetched = true; //dataCollector.AddToLocalVariables( m_uniqueId, ( ( /*m_isNormalMap && */m_autoUnpackNormals ) ? "float3 " : "float4 " ) + m_textureFetchedValue + " = " + samplerOp + ";" ); //dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" ); if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) dataCollector.AddToVertexLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" ); else dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" ); m_colorPort.SetLocalValue( m_textureFetchedValue ); m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + ".r" ); m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + ".g" ); m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + ".b" ); m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + ".a" ); return m_textureFetchedValue; } } } return samplerOp; } private void AddNormalMapTag( ref string value ) { if ( /*m_isNormalMap && */m_autoUnpackNormals ) { value = string.Format( m_normalMapUnpackMode, value ); } } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); string textureName = GetCurrentParam( ref nodeParams ); m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName ); m_useSemantics = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); m_textureCoordSet = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); m_isNormalMap = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); m_defaultTextureValue = ( TexturePropertyValues ) Enum.Parse( typeof( TexturePropertyValues ), GetCurrentParam( ref nodeParams ) ); m_autocastMode = ( AutoCastType ) Enum.Parse( typeof( AutoCastType ), GetCurrentParam( ref nodeParams ) ); m_autoUnpackNormals = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); if ( UIUtils.CurrentShaderVersion() > 12 ) { m_referenceType = ( TexReferenceType ) Enum.Parse( typeof( TexReferenceType ), GetCurrentParam( ref nodeParams ) ); if ( UIUtils.CurrentShaderVersion() > 22 ) { m_referenceNodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); } else { m_referenceArrayId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); } if ( m_referenceType == TexReferenceType.Instance ) { UIUtils.UnregisterSamplerNode( this ); UIUtils.UnregisterPropertyNode( this ); m_forceSamplerUpdate = true; } UpdateHeaderColor(); } if ( UIUtils.CurrentShaderVersion() > 2406 ) m_mipMode = ( MipType ) Enum.Parse( typeof( MipType ), GetCurrentParam( ref nodeParams ) ); if ( UIUtils.CurrentShaderVersion() > 3201 ) m_currentType = ( TextureType ) Enum.Parse( typeof( TextureType ), GetCurrentParam( ref nodeParams ) ); if ( m_defaultValue == null ) { ConfigureInputPorts(); ConfigureOutputPorts(); ResizeNodeToPreview(); } else { ConfigFromObject( m_defaultValue ); } m_forceInputTypeCheck = true; } public override void ReadAdditionalData( ref string[] nodeParams ) { } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, ( m_defaultValue != null ) ? AssetDatabase.GetAssetPath( m_defaultValue ) : Constants.NoStringValue ); IOUtils.AddFieldValueToString( ref nodeInfo, m_useSemantics.ToString() ); IOUtils.AddFieldValueToString( ref nodeInfo, m_textureCoordSet.ToString() ); IOUtils.AddFieldValueToString( ref nodeInfo, m_isNormalMap.ToString() ); IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultTextureValue ); IOUtils.AddFieldValueToString( ref nodeInfo, m_autocastMode ); IOUtils.AddFieldValueToString( ref nodeInfo, m_autoUnpackNormals ); IOUtils.AddFieldValueToString( ref nodeInfo, m_referenceType ); IOUtils.AddFieldValueToString( ref nodeInfo, ( ( m_referenceSampler != null ) ? m_referenceSampler.UniqueId : -1 ) ); IOUtils.AddFieldValueToString( ref nodeInfo, m_mipMode ); IOUtils.AddFieldValueToString( ref nodeInfo, m_currentType ); } public override void WriteAdditionalToString( ref string nodeInfo, ref string connectionsInfo ) { } public string GetVirtualUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { string bias = ""; if ( m_mipMode == MipType.MipBias || m_mipMode == MipType.MipLevel ) { string lodLevel = m_lodPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar ); bias += ", " + lodLevel; } if ( m_uvPort.IsConnected ) { string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); return uvs + bias; } else { string uvCoord = string.Empty; if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ) { uvCoord = Constants.VertexShaderInputStr + ".texcoord"; if ( m_textureCoordSet > 0 ) { uvCoord += m_textureCoordSet.ToString(); } //uvCoord = UIUtils.FinalPrecisionWirePortToCgType( PrecisionType.Fixed, WirePortDataType.FLOAT4 ) + "( " + uvCoord + ",0,0 )"; } else { string propertyName = CurrentPropertyReference; string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet ); string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ); string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV; dataCollector.AddToUniforms( m_uniqueId, "uniform float4 " + propertyName + "_ST;" ); dataCollector.AddToProperties( m_uniqueId, "[HideInInspector] " + dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 ); dataCollector.AddToInput( m_uniqueId, "float2 " + dummyUV, true ); dataCollector.AddToLocalVariables( m_uniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" ); uvCoord = /*Constants.InputVarStr + "." + */uvChannelName; } return uvCoord + bias; } } public string GetUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar ) { bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ); if ( m_uvPort.IsConnected ) { if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected ) { string lodLevel = m_lodPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar ); if ( m_currentType != TextureType.Texture2D ) { string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")"; } else { string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")"; } } else if ( m_mipMode == MipType.Derivative ) { if ( m_currentType != TextureType.Texture2D ) { string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); return uvs + ", " + ddx + ", " + ddy; } else { string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); return uvs + ", " + ddx + ", " + ddy; } } else { if ( m_currentType != TextureType.Texture2D ) return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT3, ignoreLocalVar, true ); else return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT2, ignoreLocalVar, true ); } } else { string vertexCoords = Constants.VertexShaderInputStr + ".texcoord"; if ( m_textureCoordSet > 0 ) { vertexCoords += m_textureCoordSet.ToString(); } string propertyName = CurrentPropertyReference; string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet ); string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? (m_textureCoordSet + 1).ToString() : "" ); string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV; dataCollector.AddToUniforms( m_uniqueId, "uniform float4 " + propertyName + "_ST;"); dataCollector.AddToProperties( m_uniqueId, "[HideInInspector] "+ dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 ); dataCollector.AddToInput( m_uniqueId, "float2 " + dummyUV, true ); if ( isVertex ) { string lodLevel = "0"; if( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) lodLevel = m_lodPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar ); dataCollector.AddToVertexLocalVariables( m_uniqueId, "float4 " + uvChannelName + " = float4(" + vertexCoords + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw, 0 ," + lodLevel + ");" ); return uvChannelName; } else dataCollector.AddToLocalVariables( m_uniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr+"."+dummyUV + " * "+ propertyName + "_ST.xy + "+ propertyName + "_ST.zw" ); string uvCoord = uvChannelName; if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected ) { string lodLevel = m_lodPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT, ignoreLocalVar ); if ( m_currentType != TextureType.Texture2D ) { string uvs = string.Format( "float3({0},0.0)", uvCoord ); ; return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")"; } else { string uvs = uvCoord; return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")"; } } else if ( m_mipMode == MipType.Derivative ) { if ( m_currentType != TextureType.Texture2D ) { string uvs = string.Format( "float3({0},0.0)", uvCoord ); string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true ); return uvs + ", " + ddx + ", " + ddy; } else { string uvs = uvCoord; string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true ); return uvs + ", " + ddx + ", " + ddy; } } else { if ( m_currentType != TextureType.Texture2D ) { return string.Format( "float3({0},0.0)", uvCoord ); } else { return uvCoord; } } } } public override int VersionConvertInputPortId( int portId ) { int newPort = portId; //change normal scale port to last if ( UIUtils.CurrentShaderVersion() < 2407 ) { if ( portId == 1 ) newPort = 4; } if ( UIUtils.CurrentShaderVersion() < 2408 ) { newPort = newPort + 1; } return newPort; } public override void Destroy() { base.Destroy(); m_defaultValue = null; m_materialValue = null; m_referenceSampler = null; m_referenceStyle = null; m_referenceContent = null; m_texPort = null; m_uvPort = null; m_lodPort = null; m_ddxPort = null; m_ddyPort = null; m_normalPort = null; m_colorPort = null; if ( m_referenceType == TexReferenceType.Object ) { UIUtils.UnregisterSamplerNode( this ); UIUtils.UnregisterPropertyNode( this ); } } public override string GetPropertyValStr() { return m_materialMode ? ( m_materialValue != null ? m_materialValue.name : IOUtils.NO_TEXTURES ) : ( m_defaultValue != null ? m_defaultValue.name : IOUtils.NO_TEXTURES ); } public TexturePropertyNode TextureProperty { get { if ( m_referenceSampler != null ) { m_textureProperty = m_referenceSampler as TexturePropertyNode; } else if ( m_texPort.IsConnected ) { m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode; } //if ( m_textureProperty != null ) return m_textureProperty; //return this; } } public override string GetPropertyValue() { if ( SoftValidReference ) { //if ( m_referenceSampler.IsConnected ) // return string.Empty; return m_referenceSampler.TextureProperty.GetPropertyValue(); } else if ( m_texPort.IsConnected && TextureProperty != null ) { return TextureProperty.GetPropertyValue(); } switch ( m_currentType ) { case TextureType.Texture2D: { return PropertyAttributes + GetTexture2DPropertyValue(); } case TextureType.Texture3D: { return PropertyAttributes + GetTexture3DPropertyValue(); } case TextureType.Cube: { return PropertyAttributes + GetCubePropertyValue(); } } return string.Empty; } public override string GetUniformValue() { if ( SoftValidReference ) { //if ( m_referenceSampler.IsConnected ) // return string.Empty; return m_referenceSampler.TextureProperty.GetUniformValue(); } else if ( m_texPort.IsConnected && TextureProperty != null ) { return TextureProperty.GetUniformValue(); } return base.GetUniformValue(); } public override void GetUniformData( out string dataType, out string dataName ) { if ( SoftValidReference ) { //if ( m_referenceSampler.IsConnected ) //{ // dataType = string.Empty; // dataName = string.Empty; // return; //} m_referenceSampler.TextureProperty.GetUniformData( out dataType, out dataName); return; } else if ( m_texPort.IsConnected && TextureProperty != null ) { TextureProperty.GetUniformData( out dataType, out dataName ); return; } base.GetUniformData( out dataType, out dataName ); } public string UVCoordsName { get { return Constants.InputVarStr + "." + IOUtils.GetUVChannelName( CurrentPropertyReference, m_textureCoordSet ); } } public override string CurrentPropertyReference { get { string propertyName = string.Empty; if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 ) { SamplerNode node = UIUtils.GetSamplerNode( m_referenceArrayId ); propertyName = ( node != null ) ? node.TextureProperty.PropertyName : PropertyName; } else if ( m_texPort.IsConnected && TextureProperty != null ) { propertyName = TextureProperty.PropertyName; } else { propertyName = PropertyName; } return propertyName; } } public bool SoftValidReference { get { if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 ) { m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId ); m_texPort.Locked = true; if ( m_referenceContent == null ) m_referenceContent = new GUIContent(); if ( m_referenceSampler != null ) { m_referenceContent.image = m_referenceSampler.Value; if ( m_referenceWidth != m_referenceSampler.Position.width ) { m_referenceWidth = m_referenceSampler.Position.width; m_sizeIsDirty = true; } } else { m_referenceArrayId = -1; m_referenceWidth = -1; } return m_referenceSampler != null; } m_texPort.Locked = false; return false; } } //public override string DataToArray { get { return PropertyName; } } public bool AutoUnpackNormals { get { return m_autoUnpackNormals; } set { m_autoUnpackNormals = value; m_defaultTextureValue = value ? TexturePropertyValues.bump : TexturePropertyValues.white; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.AspNetCore.Testing; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Certificates.Generation.Tests { public class CertificateManagerTests : IClassFixture<CertFixture> { private readonly CertFixture _fixture; private CertificateManager _manager => _fixture.Manager; public CertificateManagerTests(ITestOutputHelper output, CertFixture fixture) { _fixture = fixture; Output = output; } public const string TestCertificateSubject = "CN=aspnet.test"; public ITestOutputHelper Output { get; } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CreatesACertificate_WhenThereAreNoHttpsCertificates() { try { // Arrange _fixture.CleanupCertificates(); const string CertificateName = nameof(EnsureCreateHttpsCertificate_CreatesACertificate_WhenThereAreNoHttpsCertificates) + ".cer"; // Act var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var result = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, isInteractive: false); // Assert Assert.Equal(EnsureCertificateResult.Succeeded, result); Assert.True(File.Exists(CertificateName)); var exportedCertificate = new X509Certificate2(File.ReadAllBytes(CertificateName)); Assert.NotNull(exportedCertificate); Assert.False(exportedCertificate.HasPrivateKey); var httpsCertificates = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false); var httpsCertificate = Assert.Single(httpsCertificates, c => c.Subject == TestCertificateSubject); Assert.True(httpsCertificate.HasPrivateKey); Assert.Equal(TestCertificateSubject, httpsCertificate.Subject); Assert.Equal(TestCertificateSubject, httpsCertificate.Issuer); Assert.Equal("sha256RSA", httpsCertificate.SignatureAlgorithm.FriendlyName); Assert.Equal("1.2.840.113549.1.1.11", httpsCertificate.SignatureAlgorithm.Value); Assert.Equal(now.LocalDateTime, httpsCertificate.NotBefore); Assert.Equal(now.AddYears(1).LocalDateTime, httpsCertificate.NotAfter); Assert.Contains( httpsCertificate.Extensions.OfType<X509Extension>(), e => e is X509BasicConstraintsExtension basicConstraints && basicConstraints.Critical == true && basicConstraints.CertificateAuthority == false && basicConstraints.HasPathLengthConstraint == false && basicConstraints.PathLengthConstraint == 0); Assert.Contains( httpsCertificate.Extensions.OfType<X509Extension>(), e => e is X509KeyUsageExtension keyUsage && keyUsage.Critical == true && keyUsage.KeyUsages == (X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature)); Assert.Contains( httpsCertificate.Extensions.OfType<X509Extension>(), e => e is X509EnhancedKeyUsageExtension enhancedKeyUsage && enhancedKeyUsage.Critical == true && enhancedKeyUsage.EnhancedKeyUsages.OfType<Oid>().Single() is Oid keyUsage && keyUsage.Value == "1.3.6.1.5.5.7.3.1"); // Subject alternative name Assert.Contains( httpsCertificate.Extensions.OfType<X509Extension>(), e => e.Critical == true && e.Oid.Value == "2.5.29.17"); // ASP.NET HTTPS Development certificate extension Assert.Contains( httpsCertificate.Extensions.OfType<X509Extension>(), e => e.Critical == false && e.Oid.Value == "1.3.6.1.4.1.311.84.1.1" && e.RawData[0] == _manager.AspNetHttpsCertificateVersion); Assert.Equal(httpsCertificate.GetCertHashString(), exportedCertificate.GetCertHashString()); } catch (Exception e) { Output.WriteLine(e.Message); ListCertificates(); throw; } } private void ListCertificates() { using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates; foreach (var certificate in certificates) { Output.WriteLine($"Certificate: '{Convert.ToBase64String(certificate.Export(X509ContentType.Cert))}'."); certificate.Dispose(); } store.Close(); } } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates() { // Arrange const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pfx"; var certificatePassword = Guid.NewGuid().ToString(); _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); // Act var result = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: true, password: certificatePassword, isInteractive: false); // Assert Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); var exportedCertificate = new X509Certificate2(File.ReadAllBytes(CertificateName), certificatePassword); Assert.NotNull(exportedCertificate); Assert.True(exportedCertificate.HasPrivateKey); Assert.Equal(httpsCertificate.GetCertHashString(), exportedCertificate.GetCertHashString()); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CanExportTheCertInPemFormat() { // Arrange var message = "plaintext"; const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pem"; var certificatePassword = Guid.NewGuid().ToString(); _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); // Act var result = _manager .EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: true, password: certificatePassword, keyExportFormat: CertificateKeyExportFormat.Pem, isInteractive: false); // Assert Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); var exportedCertificate = X509Certificate2.CreateFromEncryptedPemFile(CertificateName, certificatePassword, Path.ChangeExtension(CertificateName, "key")); Assert.NotNull(exportedCertificate); Assert.True(exportedCertificate.HasPrivateKey); Assert.Equal("plaintext", Encoding.ASCII.GetString(exportedCertificate.GetRSAPrivateKey().Decrypt(exportedCertificate.GetRSAPrivateKey().Encrypt(Encoding.ASCII.GetBytes(message), RSAEncryptionPadding.OaepSHA256), RSAEncryptionPadding.OaepSHA256))); Assert.Equal(httpsCertificate.GetCertHashString(), exportedCertificate.GetCertHashString()); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CanExportTheCertInPemFormat_WithoutKey() { // Arrange const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pem"; _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); // Act var result = _manager .EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: false, password: null, keyExportFormat: CertificateKeyExportFormat.Pem, isInteractive: false); // Assert Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); var exportedCertificate = new X509Certificate2(CertificateName); Assert.NotNull(exportedCertificate); Assert.False(exportedCertificate.HasPrivateKey); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CanImport_ExportedPfx() { // Arrange const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pfx"; var certificatePassword = Guid.NewGuid().ToString(); _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); _manager .EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: true, password: certificatePassword, isInteractive: false); _manager.CleanupHttpsCertificates(); // Act var result = _manager.ImportCertificate(CertificateName, certificatePassword); // Assert Assert.Equal(ImportCertificateResult.Succeeded, result); var importedCertificate = Assert.Single(_manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false)); Assert.Equal(httpsCertificate.GetCertHashString(), importedCertificate.GetCertHashString()); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CanImport_ExportedPfx_FailsIfThereAreCertificatesPresent() { // Arrange const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pfx"; var certificatePassword = Guid.NewGuid().ToString(); _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: true, password: certificatePassword, isInteractive: false); // Act var result = _manager.ImportCertificate(CertificateName, certificatePassword); // Assert Assert.Equal(ImportCertificateResult.ExistingCertificatesPresent, result); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_CanExportTheCertInPemFormat_WithoutPassword() { // Arrange var message = "plaintext"; const string CertificateName = nameof(EnsureCreateHttpsCertificate_DoesNotCreateACertificate_WhenThereIsAnExistingHttpsCertificates) + ".pem"; _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificate = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: false).Single(c => c.Subject == TestCertificateSubject); // Act var result = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), CertificateName, trust: false, includePrivateKey: true, password: null, keyExportFormat: CertificateKeyExportFormat.Pem, isInteractive: false); // Assert Assert.Equal(EnsureCertificateResult.ValidCertificatePresent, result); Assert.True(File.Exists(CertificateName)); var exportedCertificate = X509Certificate2.CreateFromPemFile(CertificateName, Path.ChangeExtension(CertificateName, "key")); Assert.NotNull(exportedCertificate); Assert.True(exportedCertificate.HasPrivateKey); Assert.Equal("plaintext", Encoding.ASCII.GetString(exportedCertificate.GetRSAPrivateKey().Decrypt(exportedCertificate.GetRSAPrivateKey().Encrypt(Encoding.ASCII.GetBytes(message), RSAEncryptionPadding.OaepSHA256), RSAEncryptionPadding.OaepSHA256))); Assert.Equal(httpsCertificate.GetCertHashString(), exportedCertificate.GetCertHashString()); } [Fact] public void EnsureCreateHttpsCertificate_ReturnsExpiredCertificateIfVersionIsIncorrect() { _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); _manager.AspNetHttpsCertificateVersion = 2; var httpsCertificateList = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true); Assert.Empty(httpsCertificateList); } [Fact] public void EnsureCreateHttpsCertificate_ReturnsExpiredCertificateForEmptyVersionField() { _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); _manager.AspNetHttpsCertificateVersion = 0; var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); _manager.AspNetHttpsCertificateVersion = 1; var httpsCertificateList = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true); Assert.Empty(httpsCertificateList); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_ReturnsValidIfVersionIsZero() { _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); _manager.AspNetHttpsCertificateVersion = 0; var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); var httpsCertificateList = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true); Assert.NotEmpty(httpsCertificateList); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void EnsureCreateHttpsCertificate_ReturnValidIfCertIsNewer() { _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); _manager.AspNetHttpsCertificateVersion = 2; var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); _manager.AspNetHttpsCertificateVersion = 1; var httpsCertificateList = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true); Assert.NotEmpty(httpsCertificateList); } [ConditionalFact] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/6720", Queues = "All.OSX")] public void ListCertificates_AlwaysReturnsTheCertificate_WithHighestVersion() { _fixture.CleanupCertificates(); var now = DateTimeOffset.UtcNow; now = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Offset); _manager.AspNetHttpsCertificateVersion = 1; var creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); _manager.AspNetHttpsCertificateVersion = 2; creation = _manager.EnsureAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1), path: null, trust: false, isInteractive: false); Output.WriteLine(creation.ToString()); ListCertificates(); _manager.AspNetHttpsCertificateVersion = 1; var httpsCertificateList = _manager.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true); Assert.Equal(2, httpsCertificateList.Count); var firstCertificate = httpsCertificateList[0]; var secondCertificate = httpsCertificateList[1]; Assert.Contains( firstCertificate.Extensions.OfType<X509Extension>(), e => e.Critical == false && e.Oid.Value == "1.3.6.1.4.1.311.84.1.1" && e.RawData[0] == 2); Assert.Contains( secondCertificate.Extensions.OfType<X509Extension>(), e => e.Critical == false && e.Oid.Value == "1.3.6.1.4.1.311.84.1.1" && e.RawData[0] == 1); } } public class CertFixture : IDisposable { public const string TestCertificateSubject = "CN=aspnet.test"; public CertFixture() { Manager = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new WindowsCertificateManager(TestCertificateSubject, 1) : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? new MacOSCertificateManager(TestCertificateSubject, 1) as CertificateManager : new UnixCertificateManager(TestCertificateSubject, 1); CleanupCertificates(); } internal CertificateManager Manager { get; set; } public void Dispose() => CleanupCertificates(); internal void CleanupCertificates() { Manager.RemoveAllCertificates(StoreName.My, StoreLocation.CurrentUser); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Manager.RemoveAllCertificates(StoreName.Root, StoreLocation.CurrentUser); } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Export.Algo File: XmlExporter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Export { using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Ecng.Common; using StockSharp.BusinessEntities; using StockSharp.Messages; /// <summary> /// The export into xml. /// </summary> public class XmlExporter : BaseExporter { private const string _timeFormat = "yyyy-MM-dd HH:mm:ss.fff zzz"; /// <summary> /// Initializes a new instance of the <see cref="XmlExporter"/>. /// </summary> /// <param name="security">Security.</param> /// <param name="arg">The data parameter.</param> /// <param name="isCancelled">The processor, returning export interruption sign.</param> /// <param name="fileName">The path to file.</param> public XmlExporter(Security security, object arg, Func<int, bool> isCancelled, string fileName) : base(security, arg, isCancelled, fileName) { } /// <summary> /// To export <see cref="ExecutionMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<ExecutionMessage> messages) { switch ((ExecutionTypes)Arg) { case ExecutionTypes.Tick: { Do(messages, "ticks", (writer, trade) => { writer.WriteStartElement("trade"); writer.WriteAttribute("id", trade.TradeId == null ? trade.TradeStringId : trade.TradeId.To<string>()); writer.WriteAttribute("serverTime", trade.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", trade.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("price", trade.TradePrice); writer.WriteAttribute("volume", trade.TradeVolume); if (trade.OriginSide != null) writer.WriteAttribute("originSide", trade.OriginSide.Value); if (trade.OpenInterest != null) writer.WriteAttribute("openInterest", trade.OpenInterest.Value); if (trade.IsUpTick != null) writer.WriteAttribute("isUpTick", trade.IsUpTick.Value); writer.WriteEndElement(); }); break; } case ExecutionTypes.OrderLog: { Do(messages, "orderLog", (writer, item) => { writer.WriteStartElement("item"); writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>()); writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("price", item.OrderPrice); writer.WriteAttribute("volume", item.OrderVolume); writer.WriteAttribute("side", item.Side); writer.WriteAttribute("state", item.OrderState); writer.WriteAttribute("timeInForce", item.TimeInForce); writer.WriteAttribute("isSystem", item.IsSystem); if (item.TradePrice != null) { writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>()); writer.WriteAttribute("tradePrice", item.TradePrice); if (item.OpenInterest != null) writer.WriteAttribute("openInterest", item.OpenInterest.Value); } writer.WriteEndElement(); }); break; } case ExecutionTypes.Transaction: { Do(messages, "transactions", (writer, item) => { writer.WriteStartElement("item"); writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("portfolio", item.PortfolioName); writer.WriteAttribute("clientCode", item.ClientCode); writer.WriteAttribute("brokerCode", item.BrokerCode); writer.WriteAttribute("depoName", item.DepoName); writer.WriteAttribute("transactionId", item.TransactionId); writer.WriteAttribute("originalTransactionId", item.OriginalTransactionId); writer.WriteAttribute("orderId", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>()); writer.WriteAttribute("derivedOrderId", item.DerivedOrderId == null ? item.DerivedOrderStringId : item.DerivedOrderId.To<string>()); writer.WriteAttribute("orderPrice", item.OrderPrice); writer.WriteAttribute("orderVolume", item.OrderVolume); writer.WriteAttribute("orderType", item.OrderType); writer.WriteAttribute("orderState", item.OrderState); writer.WriteAttribute("orderStatus", item.OrderStatus); writer.WriteAttribute("visibleVolume", item.VisibleVolume); writer.WriteAttribute("balance", item.Balance); writer.WriteAttribute("side", item.Side); writer.WriteAttribute("originSide", item.OriginSide); writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>()); writer.WriteAttribute("tradePrice", item.TradePrice); writer.WriteAttribute("tradeVolume", item.TradeVolume); writer.WriteAttribute("tradeStatus", item.TradeStatus); writer.WriteAttribute("isOrder", item.HasOrderInfo); writer.WriteAttribute("isTrade", item.HasTradeInfo); writer.WriteAttribute("commission", item.Commission); writer.WriteAttribute("pnl", item.PnL); writer.WriteAttribute("position", item.Position); writer.WriteAttribute("latency", item.Latency); writer.WriteAttribute("slippage", item.Slippage); writer.WriteAttribute("error", item.Error?.Message); writer.WriteAttribute("currency", item.Currency); writer.WriteAttribute("openInterest", item.OpenInterest); writer.WriteAttribute("isCancelled", item.IsCancelled); writer.WriteAttribute("isSystem", item.IsSystem); writer.WriteAttribute("isUpTick", item.IsUpTick); writer.WriteEndElement(); }); break; } default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// To export <see cref="QuoteChangeMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<QuoteChangeMessage> messages) { Do(messages, "depths", (writer, depth) => { writer.WriteStartElement("depth"); writer.WriteAttribute("serverTime", depth.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", depth.LocalTime.ToString(_timeFormat)); foreach (var quote in depth.Bids.Concat(depth.Asks).OrderByDescending(q => q.Price)) { writer.WriteStartElement("quote"); writer.WriteAttribute("price", quote.Price); writer.WriteAttribute("volume", quote.Volume); writer.WriteAttribute("side", quote.Side); writer.WriteEndElement(); } writer.WriteEndElement(); }); } /// <summary> /// To export <see cref="Level1ChangeMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<Level1ChangeMessage> messages) { Do(messages, "messages", (writer, message) => { writer.WriteStartElement("message"); writer.WriteAttribute("serverTime", message.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", message.LocalTime.ToString(_timeFormat)); foreach (var pair in message.Changes) writer.WriteAttribute(pair.Key.ToString(), (pair.Value as DateTime?)?.ToString(_timeFormat) ?? pair.Value); writer.WriteEndElement(); }); } /// <summary> /// To export <see cref="CandleMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<CandleMessage> messages) { Do(messages, "candles", (writer, candle) => { writer.WriteStartElement("candle"); writer.WriteAttribute("openTime", candle.OpenTime.ToString(_timeFormat)); writer.WriteAttribute("closeTime", candle.CloseTime.ToString(_timeFormat)); writer.WriteAttribute("O", candle.OpenPrice); writer.WriteAttribute("H", candle.HighPrice); writer.WriteAttribute("L", candle.LowPrice); writer.WriteAttribute("C", candle.ClosePrice); writer.WriteAttribute("V", candle.TotalVolume); if (candle.OpenInterest != null) writer.WriteAttribute("openInterest", candle.OpenInterest.Value); writer.WriteEndElement(); }); } /// <summary> /// To export <see cref="NewsMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<NewsMessage> messages) { Do(messages, "news", (writer, n) => { writer.WriteStartElement("item"); if (!n.Id.IsEmpty()) writer.WriteAttribute("id", n.Id); writer.WriteAttribute("serverTime", n.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", n.LocalTime.ToString(_timeFormat)); if (n.SecurityId != null) writer.WriteAttribute("securityCode", n.SecurityId.Value.SecurityCode); if (!n.BoardCode.IsEmpty()) writer.WriteAttribute("boardCode", n.BoardCode); writer.WriteAttribute("headline", n.Headline); if (!n.Source.IsEmpty()) writer.WriteAttribute("source", n.Source); if (n.Url != null) writer.WriteAttribute("board", n.Url); if (!n.Story.IsEmpty()) writer.WriteCData(n.Story); writer.WriteEndElement(); }); } /// <summary> /// To export <see cref="SecurityMessage"/>. /// </summary> /// <param name="messages">Messages.</param> protected override void Export(IEnumerable<SecurityMessage> messages) { Do(messages, "securities", (writer, security) => { writer.WriteStartElement("security"); writer.WriteAttribute("code", security.SecurityId.SecurityCode); writer.WriteAttribute("board", security.SecurityId.BoardCode); if (!security.Name.IsEmpty()) writer.WriteAttribute("name", security.Name); if (!security.ShortName.IsEmpty()) writer.WriteAttribute("shortName", security.ShortName); if (security.PriceStep != null) writer.WriteAttribute("priceStep", security.PriceStep.Value); if (security.VolumeStep != null) writer.WriteAttribute("volumeStep", security.VolumeStep.Value); if (security.Multiplier != null) writer.WriteAttribute("multiplier", security.Multiplier.Value); if (security.Decimals != null) writer.WriteAttribute("decimals", security.Decimals.Value); if (security.Currency != null) writer.WriteAttribute("currency", security.Currency.Value); if (security.SecurityType != null) writer.WriteAttribute("type", security.SecurityType.Value); if (security.OptionType != null) writer.WriteAttribute("optionType", security.OptionType.Value); if (security.Strike != null) writer.WriteAttribute("strike", security.Strike.Value); if (!security.BinaryOptionType.IsEmpty()) writer.WriteAttribute("binaryOptionType", security.BinaryOptionType); if (!security.UnderlyingSecurityCode.IsEmpty()) writer.WriteAttribute("underlyingSecurityCode", security.UnderlyingSecurityCode); if (security.ExpiryDate != null) writer.WriteAttribute("expiryDate", security.ExpiryDate.Value.ToString("yyyy-MM-dd")); if (security.SettlementDate != null) writer.WriteAttribute("settlementDate", security.SettlementDate.Value.ToString("yyyy-MM-dd")); if (!security.SecurityId.Bloomberg.IsEmpty()) writer.WriteAttribute("bloomberg", security.SecurityId.Bloomberg); if (!security.SecurityId.Cusip.IsEmpty()) writer.WriteAttribute("cusip", security.SecurityId.Cusip); if (!security.SecurityId.IQFeed.IsEmpty()) writer.WriteAttribute("iqfeed", security.SecurityId.IQFeed); if (security.SecurityId.InteractiveBrokers != null) writer.WriteAttribute("ib", security.SecurityId.InteractiveBrokers); if (!security.SecurityId.Isin.IsEmpty()) writer.WriteAttribute("isin", security.SecurityId.Isin); if (!security.SecurityId.Plaza.IsEmpty()) writer.WriteAttribute("plaza", security.SecurityId.Plaza); if (!security.SecurityId.Ric.IsEmpty()) writer.WriteAttribute("ric", security.SecurityId.Ric); if (!security.SecurityId.Sedol.IsEmpty()) writer.WriteAttribute("sedol", security.SecurityId.Sedol); writer.WriteEndElement(); }); } private void Do<TValue>(IEnumerable<TValue> values, string rootElem, Action<XmlWriter, TValue> action) { using (var writer = XmlWriter.Create(Path, new XmlWriterSettings { Indent = true })) { writer.WriteStartElement(rootElem); foreach (var value in values) { if (!CanProcess()) break; action(writer, value); } writer.WriteEndElement(); } } } }
/* --------------------------------------------------------------------------- * * Copyright (c) Routrek Networks, Inc. All Rights Reserved.. * * This file is a part of the Granados SSH Client Library that is subject to * the license included in the distributed package. * You may not use this file except in compliance with the license. * * --------------------------------------------------------------------------- */ using System; using System.Collections; using System.IO; using System.Net.Sockets; using System.Text; using Routrek.Crypto; using Routrek.PKI; using Routrek.SSHCV1; using Routrek.SSHCV2; namespace Routrek.SSHC { public abstract class SSHConnection { internal AbstractSocket _stream; internal ISSHConnectionEventReceiver _eventReceiver; protected byte[] _sessionID; internal Cipher _tCipher; //transmission //internal Cipher _rCipher; //reception protected SSHConnectionParameter _param; protected object _tLockObject = new Object(); protected bool _closed; protected bool _autoDisconnect; protected AuthenticationResult _authenticationResult; protected SSHConnection(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver) { _param = (SSHConnectionParameter)param.Clone(); _eventReceiver = receiver; _channel_entries = new ArrayList(16); _autoDisconnect = true; } public abstract SSHConnectionInfo ConnectionInfo { get; } /** * returns true if any data from server is available */ public bool Available { get { if(_closed) return false; else return _stream.DataAvailable; } } public SSHConnectionParameter Param { get { return _param; } } public AuthenticationResult AuthenticationResult { get { return _authenticationResult; } } internal abstract IByteArrayHandler PacketBuilder { get ; } public ISSHConnectionEventReceiver EventReceiver { get { return _eventReceiver; } } public bool IsClosed { get { return _closed; } } public bool AutoDisconnect { get { return _autoDisconnect; } set { _autoDisconnect = value; } } internal abstract AuthenticationResult Connect(AbstractSocket target); /** * terminates this connection */ public abstract void Disconnect(string msg); /** * opens a pseudo terminal */ public abstract SSHChannel OpenShell(ISSHChannelEventReceiver receiver); /** * forwards the remote end to another host */ public abstract SSHChannel ForwardPort(ISSHChannelEventReceiver receiver, string remote_host, int remote_port, string originator_host, int originator_port); /** * listens a connection on the remote end */ public abstract void ListenForwardedPort(string allowed_host, int bind_port); /** * cancels binded port */ public abstract void CancelForwardedPort(string host, int port); /** * closes socket directly. */ public abstract void Close(); public abstract void SendIgnorableData(string msg); /** * opens another SSH connection via port-forwarded connection */ public SSHConnection OpenPortForwardedAnotherConnection(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver, string host, int port) { ProtocolNegotiationHandler pnh = new ProtocolNegotiationHandler(param); ChannelSocket s = new ChannelSocket(pnh); SSHChannel ch = ForwardPort(s, host, port, "localhost", 0); s.SSHChennal = ch; return SSHConnection.Connect(param, receiver, pnh, s); } //channel id support protected class ChannelEntry { public int _localID; public ISSHChannelEventReceiver _receiver; public SSHChannel _channel; } protected ArrayList _channel_entries; protected int _channel_sequence; protected ChannelEntry FindChannelEntry(int id) { for(int i=0; i<_channel_entries.Count; i++) { ChannelEntry e = (ChannelEntry)_channel_entries[i]; if(e._localID==id) return e; } return null; } protected ChannelEntry RegisterChannelEventReceiver(SSHChannel ch, ISSHChannelEventReceiver r) { lock(this) { ChannelEntry e = new ChannelEntry(); e._channel = ch; e._receiver = r; e._localID = _channel_sequence++; for(int i=0; i<_channel_entries.Count; i++) { if(_channel_entries[i]==null) { _channel_entries[i] = e; return e; } } _channel_entries.Add(e); return e; } } internal void RegisterChannel(int local_id, SSHChannel ch) { FindChannelEntry(local_id)._channel = ch; } internal void UnregisterChannelEventReceiver(int id) { lock(this) { foreach(ChannelEntry e in _channel_entries) { if(e._localID==id) { _channel_entries.Remove(e); break; } } if(this.ChannelCount==0 && _autoDisconnect) Disconnect(""); //auto close } } public virtual int ChannelCount { get { int r = 0; for(int i=0; i<_channel_entries.Count; i++) { if(_channel_entries[i]!=null) r++; } return r; } } //establishes a SSH connection in subject to ConnectionParameter public static SSHConnection Connect(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver, Socket underlying_socket) { if(param.UserName==null) throw new InvalidOperationException("UserName property is not set"); if(param.Password==null) throw new InvalidOperationException("Password property is not set"); ProtocolNegotiationHandler pnh = new ProtocolNegotiationHandler(param); PlainSocket s = new PlainSocket(underlying_socket, pnh); s.RepeatAsyncRead(); return ConnectMain(param, receiver, pnh, s); } internal static SSHConnection Connect(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver, ProtocolNegotiationHandler pnh, AbstractSocket s) { if(param.UserName==null) throw new InvalidOperationException("UserName property is not set"); if(param.Password==null) throw new InvalidOperationException("Password property is not set"); return ConnectMain(param, receiver, pnh, s); } private static SSHConnection ConnectMain(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver, ProtocolNegotiationHandler pnh, AbstractSocket s) { pnh.Wait(); if(pnh.State!=ReceiverState.Ready) throw new SSHException(pnh.ErrorMessage); string sv = pnh.ServerVersion; SSHConnection con = null; if(param.Protocol==SSHProtocol.SSH1) con = new SSH1Connection(param, receiver, sv, SSHUtil.ClientVersionString(param.Protocol)); else con = new SSH2Connection(param, receiver, sv, SSHUtil.ClientVersionString(param.Protocol)); s.SetHandler(con.PacketBuilder); SendMyVersion(s, param); if(con.Connect(s)!=AuthenticationResult.Failure) return con; else { s.Close(); return null; } } private static void SendMyVersion(AbstractSocket stream, SSHConnectionParameter param) { string cv = SSHUtil.ClientVersionString(param.Protocol); if(param.Protocol==SSHProtocol.SSH1) cv += param.SSH1VersionEOL; else cv += "\r\n"; byte[] data = Encoding.ASCII.GetBytes(cv); stream.Write(data, 0, data.Length); } } public enum ChannelType { Session, Shell, ForwardedLocalToRemote, ForwardedRemoteToLocal } public abstract class SSHChannel { protected ChannelType _type; protected int _localID; protected int _remoteID; protected SSHConnection _connection; protected SSHChannel(SSHConnection con, ChannelType type, int local_id) { con.RegisterChannel(local_id, this); _connection = con; _type = type; _localID = local_id; } public int LocalChannelID { get { return _localID; } } public int RemoteChannelID { get { return _remoteID; } } public SSHConnection Connection { get { return _connection; } } public ChannelType Type { get { return _type; } } /** * resizes the size of terminal */ public abstract void ResizeTerminal(int width, int height, int pixel_width, int pixel_height); /** * transmits channel data */ public abstract void Transmit(byte[] data); /** * transmits channel data */ public abstract void Transmit(byte[] data, int offset, int length); /** * sends EOF(SSH2 only) */ public abstract void SendEOF(); /** * closes this channel */ public abstract void Close(); } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:40 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.direct { #region Provider /// <inheritdocs /> /// <summary> /// <p><see cref="Ext.direct.Provider">Ext.direct.Provider</see> is an abstract class meant to be extended.</p> /// <p>For example Ext JS implements the following subclasses:</p> /// <pre><code>Provider /// | /// +---<see cref="Ext.direct.JsonProvider">JsonProvider</see> /// | /// +---<see cref="Ext.direct.PollingProvider">PollingProvider</see> /// | /// +---<see cref="Ext.direct.RemotingProvider">RemotingProvider</see> /// </code></pre> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Provider : Ext.Base, Ext.util.Observable { /// <summary> /// The unique id of the provider (defaults to an auto-assigned id). /// You should assign an id if you need to be able to access the provider later and you do /// not have an object reference available, for example: /// <code><see cref="Ext.direct.Manager.addProvider">Ext.direct.Manager.addProvider</see>({ /// type: 'polling', /// url: 'php/poll.php', /// id: 'poll-provider' /// }); /// var p = <see cref="Ext.direct.Manager">Ext.direct.Manager</see>.<see cref="Ext.direct.Manager.getProvider">getProvider</see>('poll-provider'); /// p.disconnect(); /// </code> /// </summary> public JsString id; /// <summary> /// A config object containing one or more event handlers to be added to this object during initialization. This /// should be a valid listeners config object as specified in the addListener example for attaching multiple /// handlers at once. /// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong> /// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually /// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a /// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a /// DOM listener to: /// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// width: 400, /// height: 200, /// dockedItems: [{ /// xtype: 'toolbar' /// }], /// listeners: { /// click: { /// element: 'el', //bind to the underlying el property on the panel /// fn: function(){ console.log('click el'); } /// }, /// dblclick: { /// element: 'body', //bind to the underlying body property on the panel /// fn: function(){ console.log('dblclick body'); } /// } /// } /// }); /// </code> /// </summary> public JsObject listeners; /// <summary> /// Initial suspended call count. Incremented when suspendEvents is called, decremented when resumeEvents is called. /// Defaults to: <c>0</c> /// </summary> public JsNumber eventsSuspended{get;set;} /// <summary> /// This object holds a key for any event that has a listener. The listener may be set /// directly on the instance, or on its class or a super class (via observe) or /// on the MVC EventBus. The values of this object are truthy /// (a non-zero number) and falsy (0 or undefined). They do not represent an exact count /// of listeners. The value for an event is truthy if the event must be fired and is /// falsy if there is no need to fire the event. /// The intended use of this property is to avoid the expense of fireEvent calls when /// there are no listeners. This can be particularly helpful when one would otherwise /// have to call fireEvent hundreds or thousands of times. It is used like this: /// <code> if (this.hasListeners.foo) { /// this.fireEvent('foo', this, arg1); /// } /// </code> /// </summary> public JsObject hasListeners{get;set;} /// <summary> /// true in this class to identify an object as an instantiated Observable, or subclass thereof. /// Defaults to: <c>true</c> /// </summary> public bool isObservable{get;set;} /// <summary> /// Adds the specified events to the list of events which this Observable may fire. /// </summary> /// <param name="eventNames"><p>Either an object with event names as properties with /// a value of <c>true</c>. For example:</p> /// <pre><code>this.addEvents({ /// storeloaded: true, /// storecleared: true /// }); /// </code></pre> /// <p>Or any number of event names as separate parameters. For example:</p> /// <pre><code>this.addEvents('storeloaded', 'storecleared'); /// </code></pre> /// </param> public virtual void addEvents(object eventNames){} /// <summary> /// Appends an event handler to this object. For example: /// <code>myGridPanel.on("mouseover", this.onMouseOver, this); /// </code> /// The method also allows for a single argument to be passed which is a config object /// containing properties which specify multiple events. For example: /// <code>myGridPanel.on({ /// cellClick: this.onCellClick, /// mouseover: this.onMouseOver, /// mouseout: this.onMouseOut, /// scope: this // Important. Ensure "this" is correct during handler execution /// }); /// </code> /// One can also specify options for each event handler separately: /// <code>myGridPanel.on({ /// cellClick: {fn: this.onCellClick, scope: this, single: true}, /// mouseover: {fn: panel.onMouseOver, scope: panel} /// }); /// </code> /// <em>Names</em> of methods in a specified scope may also be used. Note that /// <c>scope</c> MUST be specified to use this option: /// <code>myGridPanel.on({ /// cellClick: {fn: 'onCellClick', scope: this, single: true}, /// mouseover: {fn: 'onMouseOver', scope: panel} /// }); /// </code> /// </summary> /// <param name="eventName"><p>The name of the event to listen for. /// May also be an object who's property names are event names.</p> /// </param> /// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within /// the specified <c>scope</c>. Will be called with arguments /// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p> /// </param> /// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is /// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p> /// </param> /// <param name="options"><p>An object containing handler configuration.</p> /// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last /// argument to every event handler.</p> /// <p>This object may contain any of the following properties:</p> /// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted, /// defaults to the object which fired the event.</strong></p> /// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p> /// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p> /// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed /// by the specified number of milliseconds. If the event fires again within that time, /// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p> /// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event /// was bubbled up from a child Observable.</p> /// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong> /// The name of a Component property which references an element to add a listener to.</p> /// <p> This option is useful during Component construction to add DOM event listeners to elements of /// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered. /// For example, to add a click listener to a Panel's body:</p> /// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// title: 'The title', /// listeners: { /// click: this.handlePanelClick, /// element: 'body' /// } /// }); /// </code></pre> /// <p><strong>Combining Options</strong></p> /// <p>Using the options argument, it is possible to combine different types of listeners:</p> /// <p>A delayed, one-time listener.</p> /// <pre><code>myPanel.on('hide', this.handleClick, this, { /// single: true, /// delay: 100 /// }); /// </code></pre> /// </div></li></ul></param> public virtual void addListener(object eventName, System.Delegate fn=null, object scope=null, object options=null){} /// <summary> /// Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is /// destroyed. /// </summary> /// <param name="item"><p>The item to which to add a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> /// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the /// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p> /// </param> public virtual void addManagedListener(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){} /// <summary> /// Removes all listeners for this object including the managed listeners /// </summary> public virtual void clearListeners(){} /// <summary> /// Removes all managed listeners for this object. /// </summary> public virtual void clearManagedListeners(){} /// <summary> /// Abstract methods for subclasses to implement. /// </summary> public void connect(){} /// <summary> /// Continue to fire event. /// </summary> /// <param name="eventName"> /// </param> /// <param name="args"> /// </param> /// <param name="bubbles"> /// </param> public virtual void continueFireEvent(JsString eventName, object args=null, object bubbles=null){} /// <summary> /// Creates an event handling function which refires the event from this object as the passed event name. /// </summary> /// <param name="newName"> /// </param> /// <param name="beginEnd"><p>The caller can specify on which indices to slice</p> /// </param> /// <returns> /// <span><see cref="Function">Function</see></span><div> /// </div> /// </returns> public virtual System.Delegate createRelayer(object newName, object beginEnd=null){return null;} /// <summary> /// Abstract methods for subclasses to implement. /// </summary> public void disconnect(){} /// <summary> /// Enables events fired by this Observable to bubble up an owner hierarchy by calling this.getBubbleTarget() if /// present. There is no implementation in the Observable base class. /// This is commonly used by Ext.Components to bubble events to owner Containers. /// See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>. The default implementation in <see cref="Ext.Component">Ext.Component</see> returns the /// Component's immediate owner. But if a known target is required, this can be overridden to access the /// required target more quickly. /// Example: /// <code><see cref="Ext.ExtContext.override">Ext.override</see>(<see cref="Ext.form.field.Base">Ext.form.field.Base</see>, { /// // Add functionality to Field's initComponent to enable the change event to bubble /// initComponent : <see cref="Ext.Function.createSequence">Ext.Function.createSequence</see>(Ext.form.field.Base.prototype.initComponent, function() { /// this.enableBubble('change'); /// }), /// // We know that we want Field's events to bubble directly to the FormPanel. /// getBubbleTarget : function() { /// if (!this.formPanel) { /// this.formPanel = this.findParentByType('form'); /// } /// return this.formPanel; /// } /// }); /// var myForm = new Ext.formPanel({ /// title: 'User Details', /// items: [{ /// ... /// }], /// listeners: { /// change: function() { /// // Title goes red if form has been modified. /// myForm.header.setStyle('color', 'red'); /// } /// } /// }); /// </code> /// </summary> /// <param name="eventNames"><p>The event name to bubble, or an Array of event names.</p> /// </param> public virtual void enableBubble(object eventNames){} /// <summary> /// Fires the specified event with the passed parameters (minus the event name, plus the options object passed /// to addListener). /// An event may be set to bubble up an Observable parent hierarchy (See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>) by /// calling <see cref="Ext.util.Observable.enableBubble">enableBubble</see>. /// </summary> /// <param name="eventName"><p>The name of the event to fire.</p> /// </param> /// <param name="args"><p>Variable number of parameters are passed to handlers.</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div><p>returns false if any of the handlers return false otherwise it returns true.</p> /// </div> /// </returns> public virtual bool fireEvent(JsString eventName, params object[] args){return false;} /// <summary> /// Gets the bubbling parent for an Observable /// </summary> /// <returns> /// <span><see cref="Ext.util.Observable">Ext.util.Observable</see></span><div><p>The bubble parent. null is returned if no bubble target exists</p> /// </div> /// </returns> public virtual Ext.util.Observable getBubbleParent(){return null;} /// <summary> /// Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer /// indicates whether the event needs firing or not. /// </summary> /// <param name="eventName"><p>The name of the event to check for</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div><p><c>true</c> if the event is being listened for or bubbles, else <c>false</c></p> /// </div> /// </returns> public virtual bool hasListener(JsString eventName){return false;} /// <summary> /// Returns whether or not the server-side is currently connected. /// Abstract method for subclasses to implement. /// </summary> public void isConnected(){} /// <summary> /// Shorthand for addManagedListener. /// Adds listeners to any Observable object (or <see cref="Ext.dom.Element">Ext.Element</see>) which are automatically removed when this Component is /// destroyed. /// </summary> /// <param name="item"><p>The item to which to add a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> /// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the /// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p> /// </param> public virtual void mon(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){} /// <summary> /// Shorthand for removeManagedListener. /// Removes listeners that were added by the <see cref="Ext.util.Observable.mon">mon</see> method. /// </summary> /// <param name="item"><p>The item from which to remove a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> public virtual void mun(object item, object ename, System.Delegate fn=null, object scope=null){} /// <summary> /// Shorthand for addListener. /// Appends an event handler to this object. For example: /// <code>myGridPanel.on("mouseover", this.onMouseOver, this); /// </code> /// The method also allows for a single argument to be passed which is a config object /// containing properties which specify multiple events. For example: /// <code>myGridPanel.on({ /// cellClick: this.onCellClick, /// mouseover: this.onMouseOver, /// mouseout: this.onMouseOut, /// scope: this // Important. Ensure "this" is correct during handler execution /// }); /// </code> /// One can also specify options for each event handler separately: /// <code>myGridPanel.on({ /// cellClick: {fn: this.onCellClick, scope: this, single: true}, /// mouseover: {fn: panel.onMouseOver, scope: panel} /// }); /// </code> /// <em>Names</em> of methods in a specified scope may also be used. Note that /// <c>scope</c> MUST be specified to use this option: /// <code>myGridPanel.on({ /// cellClick: {fn: 'onCellClick', scope: this, single: true}, /// mouseover: {fn: 'onMouseOver', scope: panel} /// }); /// </code> /// </summary> /// <param name="eventName"><p>The name of the event to listen for. /// May also be an object who's property names are event names.</p> /// </param> /// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within /// the specified <c>scope</c>. Will be called with arguments /// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p> /// </param> /// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is /// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p> /// </param> /// <param name="options"><p>An object containing handler configuration.</p> /// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last /// argument to every event handler.</p> /// <p>This object may contain any of the following properties:</p> /// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted, /// defaults to the object which fired the event.</strong></p> /// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p> /// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p> /// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed /// by the specified number of milliseconds. If the event fires again within that time, /// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p> /// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event /// was bubbled up from a child Observable.</p> /// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong> /// The name of a Component property which references an element to add a listener to.</p> /// <p> This option is useful during Component construction to add DOM event listeners to elements of /// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered. /// For example, to add a click listener to a Panel's body:</p> /// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// title: 'The title', /// listeners: { /// click: this.handlePanelClick, /// element: 'body' /// } /// }); /// </code></pre> /// <p><strong>Combining Options</strong></p> /// <p>Using the options argument, it is possible to combine different types of listeners:</p> /// <p>A delayed, one-time listener.</p> /// <pre><code>myPanel.on('hide', this.handleClick, this, { /// single: true, /// delay: 100 /// }); /// </code></pre> /// </div></li></ul></param> public virtual void on(object eventName, System.Delegate fn=null, object scope=null, object options=null){} /// <summary> /// Prepares a given class for observable instances. This method is called when a /// class derives from this class or uses this class as a mixin. /// </summary> /// <param name="T"><p>The class constructor to prepare.</p> /// </param> public virtual void prepareClass(System.Delegate T){} /// <summary> /// Relays selected events from the specified Observable as if the events were fired by this. /// For example if you are extending Grid, you might decide to forward some events from store. /// So you can do this inside your initComponent: /// <code>this.relayEvents(this.getStore(), ['load']); /// </code> /// The grid instance will then have an observable 'load' event which will be passed the /// parameters of the store's load event and any function fired with the grid's load event /// would have access to the grid using the <c>this</c> keyword. /// </summary> /// <param name="origin"><p>The Observable whose events this object is to relay.</p> /// </param> /// <param name="events"><p>Array of event names to relay.</p> /// </param> /// <param name="prefix"><p>A common prefix to prepend to the event names. For example:</p> /// <pre><code>this.relayEvents(this.getStore(), ['load', 'clear'], 'store'); /// </code></pre> /// <p>Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.</p> /// </param> public virtual void relayEvents(object origin, JsArray<String> events, object prefix=null){} /// <summary> /// Removes an event handler. /// </summary> /// <param name="eventName"><p>The type of event the handler was associated with.</p> /// </param> /// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the /// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p> /// </param> /// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the /// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p> /// </param> public virtual void removeListener(JsString eventName, System.Delegate fn, object scope=null){} /// <summary> /// Removes listeners that were added by the mon method. /// </summary> /// <param name="item"><p>The item from which to remove a listener/listeners.</p> /// </param> /// <param name="ename"><p>The event name, or an object containing event name properties.</p> /// </param> /// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p> /// </param> /// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference) /// in which the handler function is executed.</p> /// </param> public virtual void removeManagedListener(object item, object ename, System.Delegate fn=null, object scope=null){} /// <summary> /// Remove a single managed listener item /// </summary> /// <param name="isClear"><p>True if this is being called during a clear</p> /// </param> /// <param name="managedListener"><p>The managed listener item /// See removeManagedListener for other args</p> /// </param> public virtual void removeManagedListenerItem(bool isClear, object managedListener){} /// <summary> /// Resumes firing events (see suspendEvents). /// If events were suspended using the <c>queueSuspended</c> parameter, then all events fired /// during event suspension will be sent to any listeners now. /// </summary> public virtual void resumeEvents(){} /// <summary> /// Suspends the firing of all events. (see resumeEvents) /// </summary> /// <param name="queueSuspended"><p>Pass as true to queue up suspended events to be fired /// after the <see cref="Ext.util.Observable.resumeEvents">resumeEvents</see> call instead of discarding all suspended events.</p> /// </param> public virtual void suspendEvents(bool queueSuspended){} /// <summary> /// Shorthand for removeListener. /// Removes an event handler. /// </summary> /// <param name="eventName"><p>The type of event the handler was associated with.</p> /// </param> /// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the /// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p> /// </param> /// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the /// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p> /// </param> public virtual void un(JsString eventName, System.Delegate fn, object scope=null){} public Provider(Ext.direct.ProviderConfig config){} public Provider(){} public Provider(params object[] args){} } #endregion #region ProviderConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ProviderConfig : Ext.BaseConfig { /// <summary> /// The unique id of the provider (defaults to an auto-assigned id). /// You should assign an id if you need to be able to access the provider later and you do /// not have an object reference available, for example: /// <code><see cref="Ext.direct.Manager.addProvider">Ext.direct.Manager.addProvider</see>({ /// type: 'polling', /// url: 'php/poll.php', /// id: 'poll-provider' /// }); /// var p = <see cref="Ext.direct.Manager">Ext.direct.Manager</see>.<see cref="Ext.direct.Manager.getProvider">getProvider</see>('poll-provider'); /// p.disconnect(); /// </code> /// </summary> public JsString id; /// <summary> /// A config object containing one or more event handlers to be added to this object during initialization. This /// should be a valid listeners config object as specified in the addListener example for attaching multiple /// handlers at once. /// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong> /// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually /// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a /// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a /// DOM listener to: /// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({ /// width: 400, /// height: 200, /// dockedItems: [{ /// xtype: 'toolbar' /// }], /// listeners: { /// click: { /// element: 'el', //bind to the underlying el property on the panel /// fn: function(){ console.log('click el'); } /// }, /// dblclick: { /// element: 'body', //bind to the underlying body property on the panel /// fn: function(){ console.log('dblclick body'); } /// } /// } /// }); /// </code> /// </summary> public JsObject listeners; public ProviderConfig(params object[] args){} } #endregion #region ProviderEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ProviderEvents : Ext.BaseEvents { /// <summary> /// Fires when the Provider connects to the server-side /// </summary> /// <param name="provider"><p>The <see cref="Ext.direct.Provider">Provider</see>.</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void connect(Ext.direct.Provider provider, object eOpts){} /// <summary> /// Fires when the Provider receives data from the server-side /// </summary> /// <param name="provider"><p>The <see cref="Ext.direct.Provider">Provider</see>.</p> /// </param> /// <param name="e"><p>The <see cref="Ext.direct.Event">Ext.direct.Event</see> type that occurred.</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void data(Ext.direct.Provider provider, Ext.direct.Event e, object eOpts){} /// <summary> /// Fires when the Provider disconnects from the server-side /// </summary> /// <param name="provider"><p>The <see cref="Ext.direct.Provider">Provider</see>.</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void disconnect(Ext.direct.Provider provider, object eOpts){} /// <summary> /// Fires when the Provider receives an exception from the server-side /// </summary> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void exception(object eOpts){} public ProviderEvents(params object[] args){} } #endregion }
using System; using System.Linq; using AutoFixture; using FluentAssertions; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Domain.Entities; using SFA.DAS.CommitmentsV2.Domain.Exceptions; using SFA.DAS.CommitmentsV2.Domain.Extensions; using SFA.DAS.CommitmentsV2.Messages.Events; using SFA.DAS.CommitmentsV2.Models; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.Testing.Builders; using SFA.DAS.UnitOfWork.Context; namespace SFA.DAS.CommitmentsV2.UnitTests.Models.Cohort { [TestFixture] [Parallelizable] public class WhenSendingCohortToOtherParty { private WhenSendingCohortToOtherPartyTestsFixture _fixture; [SetUp] public void Arrange() { _fixture = new WhenSendingCohortToOtherPartyTestsFixture(); } [TestCase(Party.Employer, EditStatus.ProviderOnly)] [TestCase(Party.Provider, EditStatus.EmployerOnly)] public void ThenShouldUpdateStatus(Party modifyingParty, EditStatus expectedEditStatus) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SendToOtherParty(); _fixture.Cohort.EditStatus.Should().Be(expectedEditStatus); _fixture.Cohort.LastAction.Should().Be(LastAction.Amend); _fixture.Cohort.CommitmentStatus.Should().Be(CommitmentStatus.Active); } [TestCase(Party.Employer, null, "", 0)] [TestCase(Party.Employer, "Hello Provider", "Hello Provider", 0)] [TestCase(Party.Provider, null, "", 1)] [TestCase(Party.Provider, "Hello Employer", "Hello Employer", 1)] public void ThenShouldAddMessage(Party modifyingParty, string message, string expectedMessage, byte expectedCreatedBy) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SetMessage(message) .SendToOtherParty(); _fixture.Cohort.Messages.Should().HaveCount(1) .And.ContainSingle(m => m.CreatedBy == expectedCreatedBy && m.Text == expectedMessage && m.Author == _fixture.UserInfo.UserDisplayName); } [TestCase(Party.Employer, "Employer", "[email protected]", "Employer", "[email protected]", null, null)] [TestCase(Party.Provider, "Provider", "[email protected]", null, null, "Provider", "[email protected]")] public void ThenShouldSetLastUpdatedBy(Party modifyingParty, string userDisplayName, string userEmail, string expectedLastUpdatedByEmployerName, string expectedLastUpdatedByEmployerEmail, string expectedLastUpdatedByProviderName, string expectedLastUpdatedByProviderEmail) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SetUserInfo(userDisplayName, userEmail) .SendToOtherParty(); _fixture.Cohort.LastUpdatedByEmployerName.Should().Be(expectedLastUpdatedByEmployerName); _fixture.Cohort.LastUpdatedByEmployerEmail.Should().Be(expectedLastUpdatedByEmployerEmail); _fixture.Cohort.LastUpdatedByProviderName.Should().Be(expectedLastUpdatedByProviderName); _fixture.Cohort.LastUpdatedByProviderEmail.Should().Be(expectedLastUpdatedByProviderEmail); } [TestCase(Party.Employer, "Employer", "[email protected]", "Employer", "[email protected]", null, null)] [TestCase(Party.Provider, "Provider", "[email protected]", null, null, "Provider", "[email protected]")] public void ThenCohortShouldNoLongerBeDraft(Party modifyingParty, string userDisplayName, string userEmail, string expectedLastUpdatedByEmployerName, string expectedLastUpdatedByEmployerEmail, string expectedLastUpdatedByProviderName, string expectedLastUpdatedByProviderEmail) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SetUserInfo(userDisplayName, userEmail) .SetIsDraft(true) .SendToOtherParty(); _fixture.Cohort.IsDraft.Should().Be(false); } [TestCase(Party.Employer, typeof(CohortAssignedToProviderEvent))] [TestCase(Party.Provider, typeof(CohortAssignedToEmployerEvent))] public void ThenShouldPublishEvent(Party modifyingParty, Type expectedEventType) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SendToOtherParty(); _fixture.UnitOfWorkContext.GetEvents().Single(e => e.GetType() == expectedEventType) .Should().BeEquivalentTo(new { CohortId = _fixture.Cohort.Id, UpdatedOn = _fixture.Now }); } [TestCase(Party.None)] [TestCase(Party.TransferSender)] public void AndModifyingPartyIsNotEmployerOrProviderThenShouldThrowException(Party modifyingParty) { _fixture.SetModifyingParty(modifyingParty); _fixture.Invoking(f => f.SendToOtherParty()).Should().Throw<DomainException>(); } [TestCase(Party.Employer, Party.Provider, LastAction.Amend)] [TestCase(Party.Provider, Party.Employer, LastAction.None)] public void AndIsNotWithModifyingPartyThenShouldThrowException(Party modifyingParty, Party withParty, LastAction lastAction) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(withParty) .SetLastAction(lastAction); _fixture.Invoking(f => f.SendToOtherParty()).Should().Throw<DomainException>(); } [Test] public void AndIsApprovedByProviderThenShouldPublishEvent() { _fixture.SetModifyingParty(Party.Employer) .SetWithParty(Party.Employer) .AddDraftApprenticeship() .SetApprovals(Party.Provider) .SendToOtherParty(); _fixture.UnitOfWorkContext.GetEvents().OfType<ApprovedCohortReturnedToProviderEvent>().Should().HaveCount(1) .And.Subject.Should().ContainSingle(e => e.CohortId == _fixture.Cohort.Id && e.UpdatedOn == _fixture.Now); } [Test] public void ThenShouldResetApprovals() { _fixture.SetModifyingParty(Party.Provider) .SetWithParty(Party.Provider) .SetApprovals(Party.Employer) .SendToOtherParty(); _fixture.Cohort.Approvals.Should().Be(Party.None); } [Test] public void ThenShouldResetTransferApprovalStatus() { _fixture.SetModifyingParty(Party.Employer) .SetWithParty(Party.Employer) .SetApprovals(Party.Employer) .SetTransferApprovalStatus(TransferApprovalStatus.Rejected) .SendToOtherParty(); _fixture.Cohort.TransferApprovalStatus.Should().BeNull(); } [TestCase(Party.Employer)] [TestCase(Party.Provider)] public void ThenShouldPublishEvent(Party modifyingParty) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SendToOtherParty(); _fixture.VerifyCohortTracking(); } [TestCase(Party.Employer)] [TestCase(Party.Provider)] public void And_IsChangeOfPartyRequest_ThenShouldPublishEvent(Party modifyingParty) { _fixture.SetModifyingParty(modifyingParty) .SetWithParty(modifyingParty) .SetChangeOfPartyRequestId() .SendToOtherParty(); _fixture.VerifyCohortWithChangeOfPartyRequestEventIsPublished(); } } public class WhenSendingCohortToOtherPartyTestsFixture { public DateTime Now { get; set; } public IFixture AutoFixture { get; set; } public Party Party { get; set; } public string Message { get; set; } public UserInfo UserInfo { get; set; } public UnitOfWorkContext UnitOfWorkContext { get; set; } public CommitmentsV2.Models.Cohort Cohort { get; set; } public WhenSendingCohortToOtherPartyTestsFixture() { Now = DateTime.UtcNow; AutoFixture = new Fixture(); Party = Party.None; Message = AutoFixture.Create<string>(); UserInfo = AutoFixture.Create<UserInfo>(); UnitOfWorkContext = new UnitOfWorkContext(); Cohort = new CommitmentsV2.Models.Cohort().Set(c => c.Id, 111).Set(x=> x.ProviderId, 1); } public void SendToOtherParty() { Cohort.SendToOtherParty(Party, Message, UserInfo, Now); } public WhenSendingCohortToOtherPartyTestsFixture AddDraftApprenticeship() { ApprenticeshipBase apprenticeship = new DraftApprenticeship(new DraftApprenticeshipDetails(), Party.None); Cohort.Add(c => c.Apprenticeships, apprenticeship); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetTransferApprovalStatus(TransferApprovalStatus status) { Cohort.Set(x => x.TransferApprovalStatus, status); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetWithParty(Party withParty) { Cohort.Set(c => c.WithParty, withParty); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetLastAction(LastAction lastAction) { Cohort.Set(c => c.LastAction, lastAction); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetApprovals(Party approvals) { Cohort.Set(c => c.Approvals, approvals); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetIsDraft(bool isDraft) { Cohort.Set(c => c.IsDraft, isDraft); return this; } public WhenSendingCohortToOtherPartyTestsFixture SetModifyingParty(Party modifyingParty) { Party = modifyingParty; return this; } public WhenSendingCohortToOtherPartyTestsFixture SetMessage(string message) { Message = message; return this; } public WhenSendingCohortToOtherPartyTestsFixture SetUserInfo(string userDisplayName, string userEmail) { UserInfo.UserDisplayName = userDisplayName; UserInfo.UserEmail = userEmail; return this; } public WhenSendingCohortToOtherPartyTestsFixture SetChangeOfPartyRequestId() { Cohort.Set(c => c.ChangeOfPartyRequestId, 123); return this; } public void VerifyCohortTracking() { Assert.IsNotNull(UnitOfWorkContext.GetEvents().SingleOrDefault(x => x is EntityStateChangedEvent @event && @event.EntityType == nameof(Cohort))); } public void VerifyCohortWithChangeOfPartyRequestEventIsPublished() { Assert.IsNotNull(UnitOfWorkContext.GetEvents().SingleOrDefault(x => x is CohortWithChangeOfPartyUpdatedEvent @event && @event.CohortId == Cohort.Id)); } } }
/* Copyright (c) 2006-2008 Google 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. */ /* Change history * Oct 13 2008 Joe Feser [email protected] * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ using System; using System.Xml; using System.Collections; using System.Text; using Google.GData.Client; using System.Globalization; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a period of time. /// </summary> public class When : IExtensionElementFactory { /// <summary> /// Event start time (required). /// </summary> private DateTime startTime; /// <summary> /// Event end time (optional). /// </summary> private DateTime endTime; /// <summary> /// String description of the event times. /// </summary> private String valueString; /// <summary> /// flag, indicating if an all day status /// </summary> private bool fAllDay; /// <summary> /// reminder object to set reminder durations /// </summary> private ExtensionCollection<Reminder> reminders; /// <summary> /// Constructs a new instance of a When object. /// </summary> public When() : base() { } /// <summary> /// Constructs a new instance of a When object with provided data. /// </summary> /// <param name="start">The beginning of the event.</param> /// <param name="end">The end of the event.</param> public When(DateTime start, DateTime end) : this() { this.StartTime = start; this.EndTime = end; } /// <summary> /// Constructs a new instance of a When object with provided data. /// </summary> /// <param name="start">The beginning of the event.</param> /// <param name="end">The end of the event.</param> /// <param name="allDay">A flag to indicate an all day event.</param> public When(DateTime start, DateTime end, bool allDay) : this(start, end) { this.AllDay = allDay; } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public DateTime StartTime</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public DateTime StartTime { get { return startTime; } set { startTime = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public DateTime EndTime</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public DateTime EndTime { get { return endTime; } set { endTime = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>reminder accessor</summary> ////////////////////////////////////////////////////////////////////// public ExtensionCollection<Reminder> Reminders { get { if (this.reminders == null) { this.reminders = new ExtensionCollection<Reminder>(null); } return this.reminders; } } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string ValueString</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public String ValueString { get { return valueString; } set { valueString = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method to the allday event flag</summary> /// <returns>true if it's an all day event</returns> ////////////////////////////////////////////////////////////////////// public bool AllDay { get { return this.fAllDay; } set { this.fAllDay = value; } } #region overloaded from IExtensionElementFactory ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); When when = null; if (node != null) { object localname = node.LocalName; if (localname.Equals(this.XmlName) == false || node.NamespaceURI.Equals(this.XmlNameSpace) == false) { return null; } } bool startTimeFlag = false, endTimeFlag = false; when = new When(); if (node != null) { if (node.Attributes != null) { String value = node.Attributes[GDataParserNameTable.XmlAttributeStartTime] != null ? node.Attributes[GDataParserNameTable.XmlAttributeStartTime].Value : null; if (value != null) { startTimeFlag = true; when.startTime = DateTime.Parse(value); when.AllDay = (value.IndexOf('T') == -1); } value = node.Attributes[GDataParserNameTable.XmlAttributeEndTime] != null ? node.Attributes[GDataParserNameTable.XmlAttributeEndTime].Value : null; if (value != null) { endTimeFlag = true; when.endTime = DateTime.Parse(value); when.AllDay = when.AllDay && (value.IndexOf('T') == -1); } if (node.Attributes[GDataParserNameTable.XmlAttributeValueString] != null) { when.valueString = node.Attributes[GDataParserNameTable.XmlAttributeValueString].Value; } } // single event, g:reminder is inside g:when if (node.HasChildNodes) { XmlNode whenChildNode = node.FirstChild; IExtensionElementFactory f = new Reminder() as IExtensionElementFactory; while (whenChildNode != null && whenChildNode is XmlElement) { if (String.Compare(whenChildNode.NamespaceURI, f.XmlNameSpace, true, CultureInfo.InvariantCulture) == 0) { if (String.Compare(whenChildNode.LocalName, f.XmlName, true, CultureInfo.InvariantCulture) == 0) { Reminder r = f.CreateInstance(whenChildNode, null) as Reminder; when.Reminders.Add(r); } } whenChildNode = whenChildNode.NextSibling; } } } if (!startTimeFlag) { throw new ClientFeedException("g:when/@startTime is required."); } if (endTimeFlag && when.startTime.CompareTo(when.endTime) > 0) { throw new ClientFeedException("g:when/@startTime must be less than or equal to g:when/@endTime."); } return when; } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element. /// </summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlWhenElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion #region overloaded for persistence /// <summary> /// Persistence method for the When object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(this.valueString) || Utilities.IsPersistable(this.startTime) || Utilities.IsPersistable(this.endTime)) { writer.WriteStartElement(BaseNameTable.gDataPrefix, XmlName, BaseNameTable.gNamespace); if (startTime != new DateTime(1, 1, 1)) { string date = this.fAllDay ? Utilities.LocalDateInUTC(this.startTime) : Utilities.LocalDateTimeInUTC(this.startTime); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeStartTime, date); } else { throw new ClientFeedException("g:when/@startTime is required."); } if (endTime != new DateTime(1, 1, 1)) { string date = this.fAllDay ? Utilities.LocalDateInUTC(this.endTime) : Utilities.LocalDateTimeInUTC(this.endTime); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeEndTime, date); } if (Utilities.IsPersistable(this.valueString)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeValueString, this.valueString); } if (this.reminders != null) { foreach (Reminder r in this.Reminders) { r.Save(writer); } } writer.WriteEndElement(); } } #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Configuration; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using QuantConnect.Lean.Engine.DataFeeds; using DateTime = System.DateTime; using Log = QuantConnect.Logging.Log; namespace QuantConnect.ToolBox.CoarseUniverseGenerator { /// <summary> /// Coarse /// </summary> public class CoarseUniverseGeneratorProgram { private readonly DirectoryInfo _dailyDataFolder; private readonly DirectoryInfo _destinationFolder; private readonly DirectoryInfo _fineFundamentalFolder; private readonly IMapFileProvider _mapFileProvider; private readonly IFactorFileProvider _factorFileProvider; private readonly string _market; private readonly FileInfo _blackListedTickersFile; /// <summary> /// Runs the Coarse universe generator with default values. /// </summary> /// <returns></returns> public static bool CoarseUniverseGenerator() { var dailyDataFolder = new DirectoryInfo(Path.Combine(Globals.DataFolder, SecurityType.Equity.SecurityTypeToLower(), Market.USA, Resolution.Daily.ResolutionToLower())); var destinationFolder = new DirectoryInfo(Path.Combine(Globals.DataFolder, SecurityType.Equity.SecurityTypeToLower(), Market.USA, "fundamental", "coarse")); var fineFundamentalFolder = new DirectoryInfo(Path.Combine(dailyDataFolder.Parent.FullName, "fundamental", "fine")); var blackListedTickersFile = new FileInfo("blacklisted-tickers.txt"); var reservedWordPrefix = Config.Get("reserved-words-prefix", "quantconnect-"); var dataProvider = new DefaultDataProvider(); var mapFileProvider = new LocalDiskMapFileProvider(); mapFileProvider.Initialize(dataProvider); var factorFileProvider = new LocalDiskFactorFileProvider(); factorFileProvider.Initialize(mapFileProvider, dataProvider); var generator = new CoarseUniverseGeneratorProgram(dailyDataFolder, destinationFolder, fineFundamentalFolder, Market.USA, blackListedTickersFile, reservedWordPrefix, mapFileProvider, factorFileProvider); return generator.Run(); } /// <summary> /// Initializes a new instance of the <see cref="CoarseUniverseGeneratorProgram"/> class. /// </summary> /// <param name="dailyDataFolder">The daily data folder.</param> /// <param name="destinationFolder">The destination folder.</param> /// <param name="market">The market.</param> /// <param name="blackListedTickersFile">The black listed tickers file.</param> /// <param name="reservedWordsPrefix">The reserved words prefix.</param> /// <param name="mapFileProvider">The map file provider.</param> /// <param name="factorFileProvider">The factor file provider.</param> /// <param name="debugEnabled">if set to <c>true</c> [debug enabled].</param> public CoarseUniverseGeneratorProgram( DirectoryInfo dailyDataFolder, DirectoryInfo destinationFolder, DirectoryInfo fineFundamentalFolder, string market, FileInfo blackListedTickersFile, string reservedWordsPrefix, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider, bool debugEnabled = false) { _blackListedTickersFile = blackListedTickersFile; _market = market; _factorFileProvider = factorFileProvider; _mapFileProvider = mapFileProvider; _destinationFolder = destinationFolder; _dailyDataFolder = dailyDataFolder; _fineFundamentalFolder = fineFundamentalFolder; Log.DebuggingEnabled = debugEnabled; } /// <summary> /// Runs this instance. /// </summary> /// <returns></returns> public bool Run() { var startTime = DateTime.UtcNow; var success = true; Log.Trace($"CoarseUniverseGeneratorProgram.ProcessDailyFolder(): Processing: {_dailyDataFolder.FullName}"); var symbolsProcessed = 0; var filesRead = 0; var dailyFilesNotFound = 0; var coarseFilesGenerated = 0; var mapFileResolver = _mapFileProvider.Get(_market); var blackListedTickers = new HashSet<string>(); if (_blackListedTickersFile.Exists) { blackListedTickers = File.ReadAllLines(_blackListedTickersFile.FullName).ToHashSet(); } if (!_fineFundamentalFolder.Exists) { Log.Error($"CoarseUniverseGenerator.Run(): FAIL, Fine Fundamental folder not found at {_fineFundamentalFolder}! "); return false; } var securityIdentifierContexts = PopulateSidContex(mapFileResolver, blackListedTickers); var dailyPricesByTicker = new ConcurrentDictionary<string, List<TradeBar>>(); var outputCoarseContent = new ConcurrentDictionary<DateTime, List<string>>(); var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2) }; try { Parallel.ForEach(securityIdentifierContexts, parallelOptions, sidContext => { var symbol = new Symbol(sidContext.SID, sidContext.LastTicker); var symbolCount = Interlocked.Increment(ref symbolsProcessed); Log.Debug($"CoarseUniverseGeneratorProgram.Run(): Processing {symbol} with tickers: '{string.Join(",", sidContext.Tickers)}'"); var factorFile = _factorFileProvider.Get(symbol); // Populate dailyPricesByTicker with all daily data by ticker for all tickers of this security. foreach (var ticker in sidContext.Tickers) { var dailyFile = new FileInfo(Path.Combine(_dailyDataFolder.FullName, $"{ticker}.zip")); if (!dailyFile.Exists) { Log.Debug($"CoarseUniverseGeneratorProgram.Run(): {dailyFile.FullName} not found, looking for daily data in data folder"); dailyFile = new FileInfo(Path.Combine(Globals.DataFolder, "equity", "usa", "daily", $"{ticker}.zip")); if (!dailyFile.Exists) { Log.Error($"CoarseUniverseGeneratorProgram.Run(): {dailyFile} not found!"); Interlocked.Increment(ref dailyFilesNotFound); continue; } } if (!dailyPricesByTicker.ContainsKey(ticker)) { dailyPricesByTicker.AddOrUpdate(ticker, ParseDailyFile(dailyFile)); Interlocked.Increment(ref filesRead); } } // Look for daily data for each ticker of the actual security for (int mapFileRowIndex = sidContext.MapFileRows.Length - 1; mapFileRowIndex >= 1; mapFileRowIndex--) { var ticker = sidContext.MapFileRows[mapFileRowIndex].Item2.ToLowerInvariant(); var endDate = sidContext.MapFileRows[mapFileRowIndex].Item1; var startDate = sidContext.MapFileRows[mapFileRowIndex - 1].Item1; List<TradeBar> tickerDailyData; if (!dailyPricesByTicker.TryGetValue(ticker, out tickerDailyData)) { Log.Error($"CoarseUniverseGeneratorProgram.Run(): Daily data for ticker {ticker.ToUpperInvariant()} not found!"); continue; } var tickerFineFundamentalFolder = Path.Combine(_fineFundamentalFolder.FullName, ticker); var fineAvailableDates = Enumerable.Empty<DateTime>(); if (Directory.Exists(tickerFineFundamentalFolder)) { fineAvailableDates = Directory.GetFiles(tickerFineFundamentalFolder, "*.zip") .Select(f => DateTime.ParseExact(Path.GetFileNameWithoutExtension(f), DateFormat.EightCharacter, CultureInfo.InvariantCulture)) .ToList(); } else { Log.Debug($"CoarseUniverseGeneratorProgram.Run(): fine folder was not found at '{tickerFineFundamentalFolder}'"); } // Get daily data only for the time the ticker was foreach (var tradeBar in tickerDailyData.Where(tb => tb.Time >= startDate && tb.Time <= endDate)) { var coarseRow = GenerateFactorFileRow(ticker, sidContext, factorFile, tradeBar, fineAvailableDates, _fineFundamentalFolder); outputCoarseContent.AddOrUpdate(tradeBar.Time, new List<string> { coarseRow }, (time, list) => { lock (list) { list.Add(coarseRow); return list; } }); } } if (symbolCount % 1000 == 0) { var elapsed = DateTime.UtcNow - startTime; Log.Trace($"CoarseUniverseGeneratorProgram.Run(): Processed {symbolCount} in {elapsed:g} at {symbolCount / elapsed.TotalMinutes:F2} symbols/minute "); } }); _destinationFolder.Create(); var startWriting = DateTime.UtcNow; Parallel.ForEach(outputCoarseContent, coarseByDate => { var filename = $"{coarseByDate.Key.ToString(DateFormat.EightCharacter, CultureInfo.InvariantCulture)}.csv"; var filePath = Path.Combine(_destinationFolder.FullName, filename); Log.Debug($"CoarseUniverseGeneratorProgram.Run(): Saving {filename} with {coarseByDate.Value.Count} entries."); File.WriteAllLines(filePath, coarseByDate.Value.OrderBy(cr => cr)); var filesCount = Interlocked.Increment(ref coarseFilesGenerated); if (filesCount % 1000 == 0) { var elapsed = DateTime.UtcNow - startWriting; Log.Trace($"CoarseUniverseGeneratorProgram.Run(): Processed {filesCount} in {elapsed:g} at {filesCount / elapsed.TotalSeconds:F2} files/second "); } }); Log.Trace($"\n\nTotal of {coarseFilesGenerated} coarse files generated in {DateTime.UtcNow - startTime:g}:\n" + $"\t => {filesRead} daily data files read.\n"); } catch (Exception e) { Log.Error(e, $"CoarseUniverseGeneratorProgram.Run(): FAILED!"); success = false; } return success; } /// <summary> /// Generates the factor file row. /// </summary> /// <param name="ticker">The ticker.</param> /// <param name="sidContext">The sid context.</param> /// <param name="factorFile">The factor file.</param> /// <param name="tradeBar">The trade bar.</param> /// <param name="fineAvailableDates">The fine available dates.</param> /// <param name="fineFundamentalFolder">The fine fundamental folder.</param> /// <returns></returns> private static string GenerateFactorFileRow(string ticker, SecurityIdentifierContext sidContext, FactorFile factorFile, TradeBar tradeBar, IEnumerable<DateTime> fineAvailableDates, DirectoryInfo fineFundamentalFolder) { var date = tradeBar.Time; var factorFileRow = factorFile?.GetScalingFactors(date); var dollarVolume = Math.Truncate(tradeBar.Close * tradeBar.Volume); var priceFactor = factorFileRow?.PriceFactor.Normalize() ?? 1m; var splitFactor = factorFileRow?.SplitFactor.Normalize() ?? 1m; bool hasFundamentalData = CheckFundamentalData(date, sidContext.MapFile, fineAvailableDates, fineFundamentalFolder); // sid,symbol,close,volume,dollar volume,has fundamental data,price factor,split factor var coarseFileLine = $"{sidContext.SID},{ticker.ToUpperInvariant()},{tradeBar.Close.Normalize()},{tradeBar.Volume.Normalize()},{Math.Truncate(dollarVolume)},{hasFundamentalData},{priceFactor},{splitFactor}"; return coarseFileLine; } /// <summary> /// Checks if there is fundamental data for /// </summary> /// <param name="ticker">The ticker.</param> /// <param name="date">The date.</param> /// <param name="mapFile">The map file.</param> /// <param name="fineAvailableDates"></param> /// <param name="fineFundamentalFolder">The fine fundamental folder.</param> /// <returns></returns> private static bool CheckFundamentalData(DateTime date, MapFile mapFile, IEnumerable<DateTime> fineAvailableDates, DirectoryInfo fineFundamentalFolder) { // Check if security has fine file within a trailing month for a date-ticker set. // There are tricky cases where a folder named by a ticker can have data for multiple securities. // e.g GOOG -> GOOGL (GOOG T1AZ164W5VTX) / GOOCV -> GOOG (GOOCV VP83T1ZUHROL) case. // The fine data in the 'fundamental/fine/goog' folder will be for 'GOOG T1AZ164W5VTX' up to the 2014-04-02 and for 'GOOCV VP83T1ZUHROL' afterward. // Therefore, date before checking if the security has fundamental data for a date, we need to filter the fine files the map's first date. var firstDate = mapFile?.FirstDate ?? DateTime.MinValue; var hasFundamentalDataForDate = fineAvailableDates.Where(d => d >= firstDate).Any(d => date.AddMonths(-1) <= d && d <= date); // The following section handles mergers and acquisitions cases. // e.g. YHOO -> AABA (YHOO R735QTJ8XC9X) // The dates right after the acquisition, valid fine fundamental data for AABA are still under the former ticker folder. // Therefore if no fine fundamental data is found in the 'fundamental/fine/aaba' folder, it searches into the 'yhoo' folder. if (mapFile != null && mapFile.Count() > 2 && !hasFundamentalDataForDate) { var previousTicker = mapFile.LastOrDefault(m => m.Date < date)?.MappedSymbol; if (previousTicker != null) { var previousTickerFineFundamentalFolder = Path.Combine(fineFundamentalFolder.FullName, previousTicker); if (Directory.Exists(previousTickerFineFundamentalFolder)) { var previousTickerFineAvailableDates = Directory.GetFiles(previousTickerFineFundamentalFolder, "*.zip") .Select(f => DateTime.ParseExact(Path.GetFileNameWithoutExtension(f), DateFormat.EightCharacter, CultureInfo.InvariantCulture)) .ToList(); hasFundamentalDataForDate = previousTickerFineAvailableDates.Where(d => d >= firstDate).Any(d => date.AddMonths(-1) <= d && d <= date); } else { Log.Debug($"CoarseUniverseGeneratorProgram.CheckFundamentalData(): fine folder was not found at '{previousTickerFineFundamentalFolder}'"); } } } return hasFundamentalDataForDate; } /// <summary> /// Parses the daily file. /// </summary> /// <param name="dailyFile">The daily file.</param> /// <returns></returns> private static List<TradeBar> ParseDailyFile(FileInfo dailyFile) { var scaleFactor = 1 / 10000m; var output = new List<TradeBar>(); using (var fileStream = dailyFile.OpenRead()) using (var stream = Compression.UnzipStreamToStreamReader(fileStream)) { while (!stream.EndOfStream) { var tradeBar = new TradeBar { Time = stream.GetDateTime(), Open = stream.GetDecimal() * scaleFactor, High = stream.GetDecimal() * scaleFactor, Low = stream.GetDecimal() * scaleFactor, Close = stream.GetDecimal() * scaleFactor, Volume = stream.GetDecimal() }; output.Add(tradeBar); } } return output; } /// <summary> /// Populates the sid contex. /// </summary> /// <param name="mapFileResolver">The map file resolver.</param> /// <param name="exclusions">The exclusions.</param> /// <returns></returns> private IEnumerable<SecurityIdentifierContext> PopulateSidContex(MapFileResolver mapFileResolver, HashSet<string> exclusions) { Log.Trace("CoarseUniverseGeneratorProgram.PopulateSidContex(): Generating SID context from QuantQuote's map files."); foreach (var mapFile in mapFileResolver) { if (exclusions.Contains(mapFile.Last().MappedSymbol)) { continue; } yield return new SecurityIdentifierContext(mapFile, _market); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Text.Formatting; using System.Buffers.Text; using System.IO; namespace System.Text.JsonLab.Tests { public class JsonWriterTests { private const int ExtraArraySize = 500; [Fact] public void WriteJsonUtf8() { var formatter = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8); var json = new Utf8JsonWriter<ArrayFormatterWrapper>(formatter, prettyPrint: false); Write(ref json); var formatted = formatter.Formatted; var str = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count); Assert.Equal(expected, str.Replace(" ", "")); formatter.Clear(); json = new Utf8JsonWriter<ArrayFormatterWrapper>(formatter, prettyPrint: true); Write(ref json); formatted = formatter.Formatted; str = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count); Assert.Equal(expected, str.Replace("\r\n", "").Replace("\n", "").Replace(" ", "")); } static readonly string expected = "{\"age\":30,\"first\":\"John\",\"last\":\"Smith\",\"phoneNumbers\":[\"425-000-1212\",\"425-000-1213\",null],\"address\":{\"street\":\"1MicrosoftWay\",\"city\":\"Redmond\",\"zip\":98052},\"values\":[425121,-425122,425123]}"; static void Write(ref Utf8JsonWriter<ArrayFormatterWrapper> json) { int[] values = { 425121, -425122, 425123 }; byte[] valueString = Encoding.UTF8.GetBytes("values"); json.WriteObjectStart(); json.WriteAttribute("age", 30); json.WriteAttribute("first", "John"); json.WriteAttribute("last", "Smith"); json.WriteArrayStart("phoneNumbers"); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteNull(); json.WriteArrayEnd(); json.WriteObjectStart("address"); json.WriteAttribute("street", "1 Microsoft Way"); json.WriteAttribute("city", "Redmond"); json.WriteAttribute("zip", 98052); json.WriteObjectEnd(); json.WriteArrayUtf8(valueString, values); json.WriteObjectEnd(); json.Flush(); } [Theory] [InlineData(true)] [InlineData(false)] public void WriteHelloWorldJsonUtf8(bool prettyPrint) { string expectedStr = GetHelloWorldExpectedString(prettyPrint, isUtf8: true); var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8); var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output, prettyPrint); jsonUtf8.WriteObjectStart(); jsonUtf8.WriteAttribute("message", "Hello, World!"); jsonUtf8.WriteObjectEnd(); jsonUtf8.Flush(); ArraySegment<byte> formatted = output.Formatted; string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count); Assert.Equal(expectedStr, actualStr); } [Theory] [InlineData(true)] [InlineData(false)] public void WriteBasicJsonUtf8(bool prettyPrint) { int[] data = GetData(ExtraArraySize, 42, -10000, 10000); byte[] ExtraArray = Encoding.UTF8.GetBytes("ExtraArray"); string expectedStr = GetExpectedString(prettyPrint, isUtf8: true, data); var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8); var jsonUtf8 = new Utf8JsonWriter<ArrayFormatterWrapper>(output, prettyPrint); jsonUtf8.WriteObjectStart(); jsonUtf8.WriteAttribute("age", 42); jsonUtf8.WriteAttribute("first", null); jsonUtf8.WriteAttribute("last", "Smith"); jsonUtf8.WriteArrayStart("phoneNumbers"); jsonUtf8.WriteValue("425-000-1212"); jsonUtf8.WriteValue("425-000-1213"); jsonUtf8.WriteArrayEnd(); jsonUtf8.WriteObjectStart("address"); jsonUtf8.WriteAttribute("street", "1 Microsoft Way"); jsonUtf8.WriteAttribute("city", "Redmond"); jsonUtf8.WriteAttribute("zip", 98052); jsonUtf8.WriteObjectEnd(); // Add a large array of values jsonUtf8.WriteArrayUtf8(ExtraArray, data); jsonUtf8.WriteObjectEnd(); jsonUtf8.Flush(); ArraySegment<byte> formatted = output.Formatted; string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count); Assert.Equal(expectedStr, actualStr); } private static int[] GetData(int size, int seed, int minValue, int maxValue) { int[] data = new int[size]; Random rand = new Random(seed); for (int i = 0; i < ExtraArraySize; i++) { data[i] = rand.Next(minValue, maxValue); } return data; } private static string GetHelloWorldExpectedString(bool prettyPrint, bool isUtf8) { MemoryStream ms = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true); StringBuilder sb = new StringBuilder(); StringWriter stringWriter = new StringWriter(sb); TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter; var json = new Newtonsoft.Json.JsonTextWriter(writer) { Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None }; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteValue("Hello, World!"); json.WriteEnd(); json.Flush(); return isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString(); } private static string GetExpectedString(bool prettyPrint, bool isUtf8, int[] data) { MemoryStream ms = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true); StringBuilder sb = new StringBuilder(); StringWriter stringWriter = new StringWriter(sb); TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter; var json = new Newtonsoft.Json.JsonTextWriter(writer) { Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None }; json.WriteStartObject(); json.WritePropertyName("age"); json.WriteValue(42); json.WritePropertyName("first"); json.WriteValue((string)null); json.WritePropertyName("last"); json.WriteValue("Smith"); json.WritePropertyName("phoneNumbers"); json.WriteStartArray(); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteEnd(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEnd(); // Add a large array of values json.WritePropertyName("ExtraArray"); json.WriteStartArray(); for (var i = 0; i < ExtraArraySize; i++) { json.WriteValue(data[i]); } json.WriteEnd(); json.WriteEnd(); json.Flush(); return isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { // This type is used for headers supporting a list of values. It essentially just forwards calls to // the actual header-store in HttpHeaders. // // This type can deal with a so called "special value": The RFC defines some headers which are collection of // values, but the RFC only defines 1 value, e.g. Transfer-Encoding: chunked, Connection: close, // Expect: 100-continue. // We expose strongly typed properties for these special values: TransferEncodingChunked, ConnectionClose, // ExpectContinue. // So we have 2 properties for each of these headers ('Transfer-Encoding' => TransferEncoding, // TransferEncodingChunked; 'Connection' => Connection, ConnectionClose; 'Expect' => Expect, ExpectContinue) // // The following solution was chosen: // - Keep HttpHeaders clean: HttpHeaders is unaware of these "special values"; it just stores the collection of // headers. // - It is the responsibility of "higher level" components (HttpHeaderValueCollection, HttpRequestHeaders, // HttpResponseHeaders) to deal with special values. // - HttpHeaderValueCollection can be configured with an IEqualityComparer and a "special value". // // Example: Server sends header "Transfer-Encoding: gzip, custom, chunked" to the client. // - HttpHeaders: HttpHeaders will have an entry in the header store for "Transfer-Encoding" with values // "gzip", "custom", "chunked" // - HttpGeneralHeaders: // - Property TransferEncoding: has three values "gzip", "custom", and "chunked" // - Property TransferEncodingChunked: is set to "true". public sealed class HttpHeaderValueCollection<T> : ICollection<T> where T : class { private string _headerName; private HttpHeaders _store; private T _specialValue; private Action<HttpHeaderValueCollection<T>, T> _validator; public int Count { get { return GetCount(); } } public bool IsReadOnly { get { return false; } } internal bool IsSpecialValueSet { get { // If this collection instance has a "special value", then check whether that value was already set. if (_specialValue == null) { return false; } return _store.ContainsParsedValue(_headerName, _specialValue); } } internal HttpHeaderValueCollection(string headerName, HttpHeaders store) : this(headerName, store, null, null) { } internal HttpHeaderValueCollection(string headerName, HttpHeaders store, Action<HttpHeaderValueCollection<T>, T> validator) : this(headerName, store, null, validator) { } internal HttpHeaderValueCollection(string headerName, HttpHeaders store, T specialValue) : this(headerName, store, specialValue, null) { } internal HttpHeaderValueCollection(string headerName, HttpHeaders store, T specialValue, Action<HttpHeaderValueCollection<T>, T> validator) { Contract.Requires(headerName != null); Contract.Requires(store != null); _store = store; _headerName = headerName; _specialValue = specialValue; _validator = validator; } public void Add(T item) { CheckValue(item); _store.AddParsedValue(_headerName, item); } public void ParseAdd(string input) { _store.Add(_headerName, input); } public bool TryParseAdd(string input) { return _store.TryParseAndAddValue(_headerName, input); } public void Clear() { _store.Remove(_headerName); } public bool Contains(T item) { CheckValue(item); return _store.ContainsParsedValue(_headerName, item); } public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } // Allow arrayIndex == array.Length in case our own collection is empty if ((arrayIndex < 0) || (arrayIndex > array.Length)) { throw new ArgumentOutOfRangeException("arrayIndex"); } object storeValue = _store.GetParsedValues(_headerName); if (storeValue == null) { return; } List<object> storeValues = storeValue as List<object>; if (storeValues == null) { // We only have 1 value: If it is the "special value" just return, otherwise add the value to the // array and return. Debug.Assert(storeValue is T); if (arrayIndex == array.Length) { throw new ArgumentException(SR.net_http_copyto_array_too_small); } array[arrayIndex] = storeValue as T; } else { storeValues.CopyTo(array, arrayIndex); } } public bool Remove(T item) { CheckValue(item); return _store.RemoveParsedValue(_headerName, item); } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { object storeValue = _store.GetParsedValues(_headerName); if (storeValue == null) { yield break; } List<object> storeValues = storeValue as List<object>; if (storeValues == null) { Debug.Assert(storeValue is T); yield return storeValue as T; } else { // We have multiple values. Iterate through the values and return them. foreach (object item in storeValues) { Debug.Assert(item is T); yield return item as T; } } } #endregion #region IEnumerable Members Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion public override string ToString() { return _store.GetHeaderString(_headerName); } internal string GetHeaderStringWithoutSpecial() { if (!IsSpecialValueSet) { return ToString(); } return _store.GetHeaderString(_headerName, _specialValue); } internal void SetSpecialValue() { Debug.Assert(_specialValue != null, "This method can only be used if the collection has a 'special value' set."); if (!_store.ContainsParsedValue(_headerName, _specialValue)) { _store.AddParsedValue(_headerName, _specialValue); } } internal void RemoveSpecialValue() { Debug.Assert(_specialValue != null, "This method can only be used if the collection has a 'special value' set."); // We're not interested in the return value. It's OK if the "special value" wasn't in the store // before calling RemoveParsedValue(). _store.RemoveParsedValue(_headerName, _specialValue); } private void CheckValue(T item) { if (item == null) { throw new ArgumentNullException("item"); } // If this instance has a custom validator for validating arguments, call it now. if (_validator != null) { _validator(this, item); } } private int GetCount() { // This is an O(n) operation. object storeValue = _store.GetParsedValues(_headerName); if (storeValue == null) { return 0; } List<object> storeValues = storeValue as List<object>; if (storeValues == null) { return 1; } else { return storeValues.Count; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Configuration; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> [Serializable] public class ClientConfiguration : MessagingConfiguration, IStatisticsConfiguration { internal const string DEPRECATE_DEPLOYMENT_ID_MESSAGE = "DeploymentId is the same as ClusterId. Please use ClusterId instead of DeploymentId."; /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { /// <summary>No provider specified</summary> None, /// <summary>use Azure, requires SystemStore element</summary> AzureTable, /// <summary>use ADO.NET, requires SystemStore element</summary> AdoNet, /// <summary>use ZooKeeper, requires SystemStore element</summary> ZooKeeper, /// <summary>use Config based static list, requires Config element(s)</summary> Config, /// <summary>use provider from third-party assembly</summary> Custom } /// <summary> /// The name of this client. /// </summary> public string ClientName { get; set; } = "Client"; /// <summary>Gets the configuration source file path</summary> public string SourceFile { get; private set; } /// <summary> /// The list fo the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Service Id. /// </summary> public Guid ServiceId { get; set; } /// <summary> /// Specifies a unique identifier for this cluster. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string ClusterId { get; set; } /// <summary> /// Deployment Id. This is the same as ClusterId and has been deprecated in favor of it. /// </summary> [Obsolete(DEPRECATE_DEPLOYMENT_ID_MESSAGE)] public string DeploymentId { get => this.ClusterId; set => this.ClusterId = value; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } /// <summary> /// Whether Trace.CorrelationManager.ActivityId settings should be propagated into grain calls. /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary>Gets the true host name, no IP address. It equals Dns.GetHostName()</summary> public string DNSHostName { get; private set; } /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } [Obsolete("Statistics table is no longer supported.")] public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public TelemetryConfiguration TelemetryConfiguration { get; } = new TelemetryConfiguration(); public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseAdoNetSystemStore { get { return GatewayProvider == GatewayProviderType.AdoNet && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <summary>Initializes a new instance of <see cref="ClientConfiguration"/>.</summary> public ClientConfiguration() : base(false) { SourceFile = null; PreferedGatewayIndex = GatewayOptions.DEFAULT_PREFERED_GATEWAY_INDEX; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = ClientMessagingOptions.DEFAULT_PREFERRED_FAMILY; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); this.ClusterId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; PropagateActivityId = MessagingOptions.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; GatewayListRefreshPeriod = GatewayOptions.DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = StatisticsOptions.DEFAULT_LOG_WRITE_PERIOD; StatisticsCollectionLevel = StatisticsOptions.DEFAULT_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { this.ClusterId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute("ServiceId")) { this.ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"), "Invalid Guid value for the ServiceId attribute"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": if (ConfigUtilities.TryParsePropagateActivityId(child, ClientName, out var propagateActivityId)) this.PropagateActivityId = propagateActivityId; break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child, this.TelemetryConfiguration); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } /// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(this.ClusterId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" ClusterId: ").Append(this.ClusterId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.AdoNet: if (!UseAdoNetSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but ClusterId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Returns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
using System.Threading.Tasks; namespace Attest.Fake.Setup.Contracts { /// <summary> /// Represents visitor for different async callbacks with return value and no parameters /// </summary> public interface IMethodCallbackWithResultVisitorAsync<TResult> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <returns>Return value</returns> Task<TResult> Visit(OnErrorCallbackWithResult<TResult> onErrorCallback); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <returns>Return value</returns> Task<TResult> Visit(OnCancelCallbackWithResult<TResult> onCancelCallback); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallbackWithResult">Callback</param> /// <returns>Return value</returns> Task<TResult> Visit(OnCompleteCallbackWithResult<TResult> onCompleteCallbackWithResult); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback</param> /// <returns>Return value</returns> Task<TResult> Visit(ProgressCallbackWithResult<TResult> progressCallback); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <returns>Return value</returns> Task<TResult> Visit(OnWithoutCallbackWithResult<TResult> withoutCallback); } /// <summary> /// Represents visitor for different async callbacks with return value and one parameter. /// </summary> public interface IMethodCallbackWithResultVisitorAsync<T, TResult> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg">Parameter</param> /// <returns>Return value</returns> Task<TResult> Visit(OnErrorCallbackWithResult<T, TResult> onErrorCallback, T arg); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg">Parameter</param> /// <returns>Return value</returns> Task<TResult> Visit(OnCancelCallbackWithResult<T, TResult> onCancelCallback, T arg); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallbackWithResult">Callback</param> /// <param name="arg">Parameter</param> /// <returns>Return value</returns> Task<TResult> Visit(OnCompleteCallbackWithResult<T, TResult> onCompleteCallbackWithResult, T arg); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback</param> /// <param name="arg">Parameter</param> /// <returns>Return value</returns> Task<TResult> Visit(ProgressCallbackWithResult<T, TResult> progressCallback, T arg); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg">Parameter</param> /// <returns>Return value</returns> Task<TResult> Visit(OnWithoutCallbackWithResult<T, TResult> withoutCallback, T arg); } /// <summary> /// Represents visitor for different async callbacks with return value and two parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> public interface IMethodCallbackWithResultVisitorAsync<T1, T2, TResult> { /// <summary> /// Visits the specified error-throwing callback. /// </summary> /// <param name="onErrorCallback">The error-throwing callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(OnErrorCallbackWithResult<T1, T2, TResult> onErrorCallback, T1 arg1, T2 arg2); /// <summary> /// Visits the specified cancellation callback. /// </summary> /// <param name="onCancelCallback">The cancellation callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCancelCallbackWithResult<T1, T2, TResult> onCancelCallback, T1 arg1, T2 arg2); /// <summary> /// Visits the specified successful completion callback. /// </summary> /// <param name="onCompleteCallbackWithResult">The successful completion callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCompleteCallbackWithResult<T1, T2, TResult> onCompleteCallbackWithResult, T1 arg1, T2 arg2); /// <summary> /// Visits the specified progress callback. /// </summary> /// <param name="progressCallback">The progress callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(ProgressCallbackWithResult<T1, T2, TResult> progressCallback, T1 arg1, T2 arg2); /// <summary> /// Visits the specified never-ending callback. /// </summary> /// <param name="onWithoutCallback">The never-ending callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(OnWithoutCallbackWithResult<T1, T2, TResult> onWithoutCallback, T1 arg1, T2 arg2); } /// <summary> /// Represents visitor for different async callbacks with return value and three parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> public interface IMethodCallbackWithResultVisitorAsync<T1, T2, T3, TResult> { /// <summary> /// Visits the specified error-throwing callback. /// </summary> /// <param name="onErrorCallback">The error-throwing callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <returns></returns> Task<TResult> Visit(OnErrorCallbackWithResult<T1, T2, T3, TResult> onErrorCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits the specified cancellation callback. /// </summary> /// <param name="onCancelCallback">The cancellation callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCancelCallbackWithResult<T1, T2, T3, TResult> onCancelCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits the specified successful completion callback. /// </summary> /// <param name="onCompleteCallbackWithResult">The successful completion callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The second parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCompleteCallbackWithResult<T1, T2, T3, TResult> onCompleteCallbackWithResult, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits the specified progress callback. /// </summary> /// <param name="progressCallback">The progress callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <returns></returns> Task<TResult> Visit(ProgressCallbackWithResult<T1, T2, T3, TResult> progressCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits the specified never-ending callback. /// </summary> /// <param name="onWithoutCallback">The never-ending callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <returns></returns> Task<TResult> Visit(OnWithoutCallbackWithResult<T1, T2, T3, TResult> onWithoutCallback, T1 arg1, T2 arg2, T3 arg3); } /// <summary> /// Represents visitor for different async callbacks with return value and four parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> public interface IMethodCallbackWithResultVisitorAsync<T1, T2, T3, T4, TResult> { /// <summary> /// Visits the specified error-throwing callback. /// </summary> /// <param name="onErrorCallback">The error-throwing callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnErrorCallbackWithResult<T1, T2, T3, T4, TResult> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits the specified cancellation callback. /// </summary> /// <param name="onCancelCallback">The cancellation callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCancelCallbackWithResult<T1, T2, T3, T4, TResult> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits the specified successful completion callback. /// </summary> /// <param name="onCompleteCallbackWithResult">The successful completion callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The second parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCompleteCallbackWithResult<T1, T2, T3, T4, TResult> onCompleteCallbackWithResult, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits the specified progress callback. /// </summary> /// <param name="progressCallback">The progress callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <returns></returns> Task<TResult> Visit(ProgressCallbackWithResult<T1, T2, T3, T4, TResult> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits the specified never-ending callback. /// </summary> /// <param name="onWithoutCallback">The never-ending callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnWithoutCallbackWithResult<T1, T2, T3, T4, TResult> onWithoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); } /// <summary> /// Represents visitor for different callbacks with return value and five parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="T5">The type of the fifth parameter.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> public interface IMethodCallbackWithResultVisitorAsync<T1, T2, T3, T4, T5, TResult> { /// <summary> /// Visits the specified error-throwing callback. /// </summary> /// <param name="onErrorCallback">The error-throwing callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <param name="arg5">The fifth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnErrorCallbackWithResult<T1, T2, T3, T4, T5, TResult> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits the specified cancellation callback. /// </summary> /// <param name="onCancelCallback">The cancellation callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <param name="arg5">The fifth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCancelCallbackWithResult<T1, T2, T3, T4, T5, TResult> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits the specified successful completion callback. /// </summary> /// <param name="onCompleteCallbackWithResult">The successful completion callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The second parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <param name="arg5">The fifth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnCompleteCallbackWithResult<T1, T2, T3, T4, T5, TResult> onCompleteCallbackWithResult, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits the specified progress callback. /// </summary> /// <param name="progressCallback">The progress callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <param name="arg5">The fifth parameter.</param> /// <returns></returns> Task<TResult> Visit(ProgressCallbackWithResult<T1, T2, T3, T4, T5, TResult> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits the specified never-ending callback. /// </summary> /// <param name="onWithoutCallback">The never-ending callback.</param> /// <param name="arg1">The first parameter.</param> /// <param name="arg2">The second parameter.</param> /// <param name="arg3">The third parameter.</param> /// <param name="arg4">The fourth parameter.</param> /// <param name="arg5">The fifth parameter.</param> /// <returns></returns> Task<TResult> Visit(OnWithoutCallbackWithResult<T1, T2, T3, T4, T5, TResult> onWithoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Collections; using System.Threading; using System.Net; using System.Net.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication.ExtendedProtection; using System.Security.Authentication.ExtendedProtection.Configuration; static class ChannelBindingUtility { static ExtendedProtectionPolicy disabledPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); static ExtendedProtectionPolicy defaultPolicy = disabledPolicy; public static ExtendedProtectionPolicy DisabledPolicy { get { return disabledPolicy; } } public static ExtendedProtectionPolicy DefaultPolicy { get { return defaultPolicy; } } public static bool IsDefaultPolicy(ExtendedProtectionPolicy policy) { return Object.ReferenceEquals(policy, defaultPolicy); } public static void CopyFrom(ExtendedProtectionPolicyElement source, ExtendedProtectionPolicyElement destination) { destination.PolicyEnforcement = source.PolicyEnforcement; destination.ProtectionScenario = source.ProtectionScenario; destination.CustomServiceNames.Clear(); foreach (ServiceNameElement sourceEntry in source.CustomServiceNames) { ServiceNameElement entry = new ServiceNameElement(); entry.Name = sourceEntry.Name; destination.CustomServiceNames.Add(entry); } } public static void InitializeFrom(ExtendedProtectionPolicy source, ExtendedProtectionPolicyElement destination) { if (!IsDefaultPolicy(source)) { destination.PolicyEnforcement = source.PolicyEnforcement; destination.ProtectionScenario = source.ProtectionScenario; destination.CustomServiceNames.Clear(); if (source.CustomServiceNames != null) { foreach (string name in source.CustomServiceNames) { ServiceNameElement entry = new ServiceNameElement(); entry.Name = name; destination.CustomServiceNames.Add(entry); } } } } public static ExtendedProtectionPolicy BuildPolicy(ExtendedProtectionPolicyElement configurationPolicy) { //using this pattern allows us to have a different default policy //than the NCL team chooses. if (configurationPolicy.ElementInformation.IsPresent) { return configurationPolicy.BuildPolicy(); } else { return ChannelBindingUtility.DefaultPolicy; } } public static ChannelBinding GetToken(SslStream stream) { return GetToken(stream.TransportContext); } public static ChannelBinding GetToken(TransportContext context) { ChannelBinding token = null; if (context != null) { token = context.GetChannelBinding(ChannelBindingKind.Endpoint); } return token; } public static ChannelBinding DuplicateToken(ChannelBinding source) { if (source == null) { return null; } return DuplicatedChannelBinding.CreateCopy(source); } public static void TryAddToMessage(ChannelBinding channelBindingToken, Message message, bool messagePropertyOwnsCleanup) { if (channelBindingToken != null) { ChannelBindingMessageProperty property = new ChannelBindingMessageProperty(channelBindingToken, messagePropertyOwnsCleanup); property.AddTo(message); property.Dispose(); //message.Properties.Add() creates a copy... } } //does not validate the ExtendedProtectionPolicy.CustomServiceNames collections on the policies public static bool AreEqual(ExtendedProtectionPolicy policy1, ExtendedProtectionPolicy policy2) { Fx.Assert(policy1 != null, "policy1 param cannot be null"); Fx.Assert(policy2 != null, "policy2 param cannot be null"); if (policy1.PolicyEnforcement == PolicyEnforcement.Never && policy2.PolicyEnforcement == PolicyEnforcement.Never) { return true; } if (policy1.PolicyEnforcement != policy2.PolicyEnforcement) { return false; } if (policy1.ProtectionScenario != policy2.ProtectionScenario) { return false; } if (policy1.CustomChannelBinding != policy2.CustomChannelBinding) { return false; } return true; } public static bool IsSubset(ServiceNameCollection primaryList, ServiceNameCollection subset) { bool result = false; if (subset == null || subset.Count == 0) { result = true; } else if (primaryList == null || primaryList.Count < subset.Count) { result = false; } else { ServiceNameCollection merged = primaryList.Merge(subset); //The merge routine only adds an entry if it is unique. result = (merged.Count == primaryList.Count); } return result; } public static void Dispose(ref ChannelBinding channelBinding) { // Explicitly cast to IDisposable to avoid the SecurityException. IDisposable disposable = (IDisposable)channelBinding; channelBinding = null; if (disposable != null) { disposable.Dispose(); } } class DuplicatedChannelBinding : ChannelBinding { [Fx.Tag.SecurityNote(Critical = "Used when referencing raw native memory")] [SecurityCritical] int size; DuplicatedChannelBinding() { } public override int Size { [Fx.Tag.SecurityNote(Critical = "Used when referencing raw native memory", Safe = "All inputs are validated during initization")] [SecuritySafeCritical] get { return this.size; } } [Fx.Tag.SecurityNote(Critical = "Invokes unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] internal static ChannelBinding CreateCopy(ChannelBinding source) { Fx.Assert(source != null, "source ChannelBinding should have been checked for null previously"); if (source.IsInvalid || source.IsClosed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(source.GetType().FullName)); } if (source.Size <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("source.Size", source.Size, SR.GetString(SR.ValueMustBePositive))); } //Instantiate the SafeHandle before trying to allocate the native memory DuplicatedChannelBinding duplicate = new DuplicatedChannelBinding(); //allocate the native memory and make a deep copy of the original. duplicate.Initialize(source); return duplicate; } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.")] [SecurityCritical] unsafe void Initialize(ChannelBinding source) { //allocates the memory pointed to by this.handle //and sets this.size after allocation succeeds. AllocateMemory(source.Size); byte* sourceBuffer = (byte*)source.DangerousGetHandle().ToPointer(); byte* destinationBuffer = (byte*)this.handle.ToPointer(); for (int i = 0; i < source.Size; i++) { destinationBuffer[i] = sourceBuffer[i]; } this.size = source.Size; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] void AllocateMemory(int bytesToAllocate) { Fx.Assert(bytesToAllocate > 0, "bytesToAllocate must be positive"); //this protects us from problems like an appdomain shutdown occuring //after allocating the native memory but before the handle gets set (which would result in a memory leak) RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { base.SetHandle(Marshal.AllocHGlobal(bytesToAllocate)); } } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(this.handle); base.SetHandle(IntPtr.Zero); return true; } } } }
using Rhino; using Rhino.Geometry; using Rhino.DocObjects; using Rhino.Collections; using GH_IO; using GH_IO.Serialization; using Grasshopper; using Grasshopper.Kernel; using Grasshopper.Kernel.Data; using Grasshopper.Kernel.Types; using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Linq; using System.Data; using System.Drawing; using System.Reflection; using System.Collections; using System.Windows.Forms; using System.Collections.Generic; using System.Runtime.InteropServices; /// <summary> /// This class will be instantiated on demand by the Script component. /// </summary> public class Script_Instance : GH_ScriptInstance { #region Utility functions /// <summary>Print a String to the [Out] Parameter of the Script component.</summary> /// <param name="text">String to print.</param> private void Print(string text) { __out.Add(text); } /// <summary>Print a formatted String to the [Out] Parameter of the Script component.</summary> /// <param name="format">String format.</param> /// <param name="args">Formatting parameters.</param> private void Print(string format, params object[] args) { __out.Add(string.Format(format, args)); } /// <summary>Print useful information about an object instance to the [Out] Parameter of the Script component. </summary> /// <param name="obj">Object instance to parse.</param> private void Reflect(object obj) { __out.Add(GH_ScriptComponentUtilities.ReflectType_CS(obj)); } /// <summary>Print the signatures of all the overloads of a specific method to the [Out] Parameter of the Script component. </summary> /// <param name="obj">Object instance to parse.</param> private void Reflect(object obj, string method_name) { __out.Add(GH_ScriptComponentUtilities.ReflectType_CS(obj, method_name)); } #endregion #region Members /// <summary>Gets the current Rhino document.</summary> private RhinoDoc RhinoDocument; /// <summary>Gets the Grasshopper document that owns this script.</summary> private GH_Document GrasshopperDocument; /// <summary>Gets the Grasshopper script component that owns this script.</summary> private IGH_Component Component; /// <summary> /// Gets the current iteration count. The first call to RunScript() is associated with Iteration==0. /// Any subsequent call within the same solution will increment the Iteration count. /// </summary> private int Iteration; #endregion /// <summary> /// This procedure contains the user code. Input parameters are provided as regular arguments, /// Output parameters as ref arguments. You don't have to assign output parameters, /// they will have a default value. /// </summary> private void RunScript(int n, System.Object sigma, double mu, int seed, ref object normal1, ref object normal2, ref object uniform1, ref object uniform2) { double _sigma = 1; if (sigma != null) { _sigma = Convert.ToDouble(sigma); } // Generate 2 uniform distributions. init_genrand((uint) seed); var u1 = genUniformRandom(n); var u2 = genUniformRandom(n); // Box-Muller method. // Generates 2 normal distributions from 2 uniform distributions. double[] result1 = new double[n]; double[] result2 = new double[n]; for (int i = 0; i < n; i++) { result1[i] = mu + _sigma * Math.Sqrt(-2.0 * Math.Log(u1[i])) * Math.Sin(2.0 * Math.PI * u2[i]); result2[i] = mu + _sigma * Math.Sqrt(-2.0 * Math.Log(u1[i])) * Math.Cos(2.0 * Math.PI * u2[i]); } // Result. uniform1 = u1; uniform2 = u2; normal1 = result1; normal2 = result2; } // <Custom additional code> private double[] genUniformRandom(int n) { double[] result = new double[n]; for (int i = 0; i < n; i++) { result[i] = genrand_res53(); } return (result); } /* ---- MODIFIED ORIGINAL CODE ---- */ /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not 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. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ /* Period parameters */ const uint N = 624; const uint M = 397; const ulong MATRIX_A = 0x9908b0dfUL; /* constant vector a */ const ulong UPPER_MASK = 0x80000000UL; /* most significant w-r bits */ const ulong LOWER_MASK = 0x7fffffffUL; /* least significant r bits */ ulong[] mt = new ulong[N]; /* the array for the state vector */ uint mti = N + 1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void init_genrand(ulong s) { mt[0] = s & 0xffffffffUL; for (mti = 1; mti < N; mti++) { mt[mti] = (1812433253UL * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ void init_by_array(ulong[] init_key, uint key_length) { uint i, j, k; init_genrand(19650218UL); i = 1; j = 0; k = (N > key_length ? N : key_length); for (; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525UL)) + init_key[j] + j; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; j++; if (i >= N) { mt[0] = mt[N - 1]; i = 1; } if (j >= key_length) j = 0; } for (k = N - 1; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i >= N) { mt[0] = mt[N - 1]; i = 1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ } /* generates a random number on [0,0xffffffff]-interval */ ulong genrand_int32() { ulong y; ulong[] mag01 = {0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[unchecked((int)(kk+(M-N)))] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } /* generates a random number on [0,0x7fffffff]-interval */ long genrand_int31() { return (long) (genrand_int32() >> 1); } /* generates a random number on [0,1]-real-interval */ double genrand_real1() { return genrand_int32() * (1.0 / 4294967295.0); /* divided by 2^32-1 */ } /* generates a random number on [0,1)-real-interval */ double genrand_real2() { return genrand_int32() * (1.0 / 4294967296.0); /* divided by 2^32 */ } /* generates a random number on (0,1)-real-interval */ double genrand_real3() { return (((double) genrand_int32()) + 0.5) * (1.0 / 4294967296.0); /* divided by 2^32 */ } /* generates a random number on [0,1) with 53-bit resolution*/ double genrand_res53() { ulong a=genrand_int32() >> 5, b = genrand_int32() >> 6; return(a * 67108864.0 + b) * (1.0 / 9007199254740992.0); } /* These real versions are due to Isaku Wada, 2002/01/09 added */ // </Custom additional code> private List<string> __err = new List<string>(); //Do not modify this list directly. private List<string> __out = new List<string>(); //Do not modify this list directly. private RhinoDoc doc = RhinoDoc.ActiveDoc; //Legacy field. private IGH_ActiveObject owner; //Legacy field. private int runCount; //Legacy field. public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List<object> inputs, IGH_DataAccess DA) { //Prepare for a new run... //1. Reset lists this.__out.Clear(); this.__err.Clear(); this.Component = owner; this.Iteration = iteration; this.GrasshopperDocument = owner.OnPingDocument(); this.RhinoDocument = rhinoDocument as Rhino.RhinoDoc; this.owner = this.Component; this.runCount = this.Iteration; this. doc = this.RhinoDocument; //2. Assign input parameters int n = default(int); if (inputs[0] != null) { n = (int)(inputs[0]); } System.Object sigma = default(System.Object); if (inputs[1] != null) { sigma = (System.Object)(inputs[1]); } double mu = default(double); if (inputs[2] != null) { mu = (double)(inputs[2]); } int seed = default(int); if (inputs[3] != null) { seed = (int)(inputs[3]); } //3. Declare output parameters object normal1 = null; object normal2 = null; object uniform1 = null; object uniform2 = null; //4. Invoke RunScript RunScript(n, sigma, mu, seed, ref normal1, ref normal2, ref uniform1, ref uniform2); try { //5. Assign output parameters to component... if (normal1 != null) { if (GH_Format.TreatAsCollection(normal1)) { IEnumerable __enum_normal1 = (IEnumerable)(normal1); DA.SetDataList(1, __enum_normal1); } else { if (normal1 is Grasshopper.Kernel.Data.IGH_DataTree) { //merge tree DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(normal1)); } else { //assign direct DA.SetData(1, normal1); } } } else { DA.SetData(1, null); } if (normal2 != null) { if (GH_Format.TreatAsCollection(normal2)) { IEnumerable __enum_normal2 = (IEnumerable)(normal2); DA.SetDataList(2, __enum_normal2); } else { if (normal2 is Grasshopper.Kernel.Data.IGH_DataTree) { //merge tree DA.SetDataTree(2, (Grasshopper.Kernel.Data.IGH_DataTree)(normal2)); } else { //assign direct DA.SetData(2, normal2); } } } else { DA.SetData(2, null); } if (uniform1 != null) { if (GH_Format.TreatAsCollection(uniform1)) { IEnumerable __enum_uniform1 = (IEnumerable)(uniform1); DA.SetDataList(3, __enum_uniform1); } else { if (uniform1 is Grasshopper.Kernel.Data.IGH_DataTree) { //merge tree DA.SetDataTree(3, (Grasshopper.Kernel.Data.IGH_DataTree)(uniform1)); } else { //assign direct DA.SetData(3, uniform1); } } } else { DA.SetData(3, null); } if (uniform2 != null) { if (GH_Format.TreatAsCollection(uniform2)) { IEnumerable __enum_uniform2 = (IEnumerable)(uniform2); DA.SetDataList(4, __enum_uniform2); } else { if (uniform2 is Grasshopper.Kernel.Data.IGH_DataTree) { //merge tree DA.SetDataTree(4, (Grasshopper.Kernel.Data.IGH_DataTree)(uniform2)); } else { //assign direct DA.SetData(4, uniform2); } } } else { DA.SetData(4, null); } } catch (Exception ex) { this.__err.Add(string.Format("Script exception: {0}", ex.Message)); } finally { //Add errors and messages... if (owner.Params.Output.Count > 0) { if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String) { List<string> __errors_plus_messages = new List<string>(); if (this.__err != null) { __errors_plus_messages.AddRange(this.__err); } if (this.__out != null) { __errors_plus_messages.AddRange(this.__out); } if (__errors_plus_messages.Count > 0) DA.SetDataList(0, __errors_plus_messages); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Text; namespace IrcDotNet.Collections { /// <summary> /// Represents a read-only collection of keys and values. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam> #if !SILVERLIGHT [Serializable()] #endif [DebuggerDisplay("Count = {Count}")] public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable #if !SILVERLIGHT , ISerializable, IDeserializationCallback #endif { // Dictionary to expose as read-only. private IDictionary<TKey, TValue> dictionary; /// <summary> /// Initializes a new instance of the <see cref="ReadOnlyDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="dictionary">The dictionary to wrap.</param> /// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is <see langword="null"/>.</exception> public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); this.dictionary = dictionary; } #region IDictionary<TKey, TValue> Members /// <summary> /// Gets a collection containing the keys in the dictionary. /// </summary> /// <value>A collection containing the keys in the dictionary.</value> public ICollection<TKey> Keys { get { return this.dictionary.Keys; } } /// <summary> /// Gets a collection containing the values in the dictionary. /// </summary> /// <value>A collection containing the values in the dictionary.</value> public ICollection<TValue> Values { get { return this.dictionary.Values; } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <value>The element with the specified key.</value> /// <exception cref="NotSupportedException">This operation is not supported on a read-only dictionary. /// </exception> public TValue this[TKey key] { get { return this.dictionary[key]; } set { throw new NotSupportedException(); } } /// <summary> /// Determines whether the dictionary contains the specified key. /// </summary> /// <param name="key">The key to locate in the dictionary.</param> /// <returns><see langword="true"/> if the dictionary contains an element with the specified key; /// <see langword="false"/>, otherwise.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <see langword="null"/>.</exception> public bool ContainsKey(TKey key) { if (key == null) throw new ArgumentNullException("key"); return this.dictionary.ContainsKey(key); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, contains the value associated with the specified key, if the /// key is found; otherwise, the default value for the type of the value parameter. This parameter is passed /// uninitialized.</param> /// <returns><see langword="true"/> if the dictionary contains an element with the specified key; /// <see langword="false"/>, otherwise.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <see langword="null"/>.</exception> public bool TryGetValue(TKey key, out TValue value) { if (key == null) throw new ArgumentNullException("key"); return this.dictionary.TryGetValue(key, out value); } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(); } bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(); } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Gets the number of key/value pairs contained in the dictionary. /// </summary> /// <value>The number of key/value pairs contained in the dictionary.</value> public int Count { get { return this.dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return this.dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.dictionary.CopyTo(array, arrayIndex); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the dictionary. /// </summary> /// <returns>An enumerator for the dictionary.</returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return ((IEnumerable<KeyValuePair<TKey, TValue>>)this.dictionary).GetEnumerator(); } #endregion #region IDictionary Members ICollection IDictionary.Keys { get { return ((IDictionary)this.dictionary).Keys; } } ICollection IDictionary.Values { get { return ((IDictionary)this.dictionary).Values; } } bool IDictionary.IsFixedSize { get { return ((IDictionary)this.dictionary).IsFixedSize; } } bool IDictionary.IsReadOnly { get { return true; } } object IDictionary.this[object key] { get { return ((IDictionary)this.dictionary)[key]; } set { throw new NotSupportedException(); } } void IDictionary.Add(object key, object value) { throw new NotSupportedException(); } void IDictionary.Remove(object key) { throw new NotSupportedException(); } void IDictionary.Clear() { throw new NotSupportedException(); } bool IDictionary.Contains(object key) { return ((IDictionary)this.dictionary).Contains(key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return ((IDictionary)this.dictionary).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ((ICollection)this.dictionary).CopyTo(array, index); } int ICollection.Count { get { return ((ICollection)this.dictionary).Count; } } bool ICollection.IsSynchronized { get { return ((ICollection)this.dictionary).IsSynchronized; } } object ICollection.SyncRoot { get { return ((ICollection)this.dictionary).SyncRoot; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this.dictionary).GetEnumerator(); } #endregion #if !SILVERLIGHT #region ISerializable Members void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { ((ISerializable)this.dictionary).GetObjectData(info, context); } #endregion #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) { ((IDeserializationCallback)this.dictionary).OnDeserialization(sender); } #endregion #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Linq; using Marten.Linq.QueryHandlers; using Marten.Schema; using Marten.Schema.Arguments; using Marten.Services; using Marten.Services.BatchQuerying; using Marten.Storage; using Marten.Util; using Npgsql; using Remotion.Linq.Parsing.Structure; namespace Marten { public class QuerySession : IQuerySession, ILoader { public ITenant Tenant { get; } private readonly IManagedConnection _connection; private readonly IQueryParser _parser; private readonly IIdentityMap _identityMap; protected readonly CharArrayTextWriter.Pool WriterPool; private bool _disposed; protected readonly DocumentStore _store; public QuerySession(DocumentStore store, IManagedConnection connection, IQueryParser parser, IIdentityMap identityMap, ITenant tenant) { Tenant = tenant; _store = store; _connection = connection; _parser = parser; _identityMap = identityMap; WriterPool = store.CreateWriterPool(); } public IDocumentStore DocumentStore => _store; public IJsonLoader Json => new JsonLoader(_connection, Tenant); protected void assertNotDisposed() { if (_disposed) throw new ObjectDisposedException("This session has been disposed"); } public IMartenQueryable<T> Query<T>() { assertNotDisposed(); var executor = new MartenQueryExecutor(_connection, _store, _identityMap, Tenant); var queryProvider = new MartenQueryProvider(typeof(MartenQueryable<>), _parser, executor); return new MartenQueryable<T>(queryProvider); } public IList<T> Query<T>(string sql, params object[] parameters) { assertNotDisposed(); var handler = new UserSuppliedQueryHandler<T>(_store, sql, parameters); return _connection.Fetch(handler, _identityMap.ForQuery(), null, Tenant); } public Task<IList<T>> QueryAsync<T>(string sql, CancellationToken token, params object[] parameters) { assertNotDisposed(); var handler = new UserSuppliedQueryHandler<T>(_store, sql, parameters); return _connection.FetchAsync(handler, _identityMap.ForQuery(), null, Tenant, token); } public IBatchedQuery CreateBatchQuery() { assertNotDisposed(); return new BatchedQuery(_store, _connection, _identityMap.ForQuery(), this); } private IDocumentStorage<T> storage<T>() { return Tenant.StorageFor<T>(); } public FetchResult<T> LoadDocument<T>(object id) where T : class { assertNotDisposed(); var storage = storage<T>(); var resolver = storage.As<IDocumentStorage<T>>(); var cmd = storage.LoaderCommand(id); if (DocumentStore.Tenancy.Style == TenancyStyle.Conjoined) { cmd.AddNamedParameter(TenantIdArgument.ArgName, Tenant.TenantId); cmd.CommandText += $" and {TenantIdColumn.Name} = :{TenantIdArgument.ArgName}"; } return _connection.Execute(cmd, c => { using (var reader = cmd.ExecuteReader()) { return resolver.Fetch(reader, _store.Serializer); } }); } public Task<FetchResult<T>> LoadDocumentAsync<T>(object id, CancellationToken token) where T : class { assertNotDisposed(); var storage = storage<T>(); var resolver = storage.As<IDocumentStorage<T>>(); var cmd = storage.LoaderCommand(id); return _connection.ExecuteAsync(cmd, async (c, tkn) => { using (var reader = await cmd.ExecuteReaderAsync(tkn).ConfigureAwait(false)) { return await resolver.FetchAsync(reader, _store.Serializer, token).ConfigureAwait(false); } }, token); } public T Load<T>(string id) { return load<T>(id); } public Task<T> LoadAsync<T>(string id, CancellationToken token) { return loadAsync<T>(id, token); } public T Load<T>(ValueType id) { return load<T>(id); } private T load<T>(object id) { if (id == null) throw new ArgumentNullException(nameof(id)); assertNotDisposed(); assertCorrectIdType<T>(id); return storage<T>().Resolve(_identityMap, this, id); } private void assertCorrectIdType<T>(object id) { var mapping = Tenant.MappingFor(typeof(T)); if (id.GetType() != mapping.IdType) { if (id.GetType() == typeof(int) && mapping.IdType == typeof(long)) return; throw new InvalidOperationException( $"The id type for {typeof(T).FullName} is {mapping.IdType.Name}, but got {id.GetType().Name}"); } } private Task<T> loadAsync<T>(object id, CancellationToken token) { assertNotDisposed(); assertCorrectIdType<T>(id); return storage<T>().As<IDocumentStorage<T>>().ResolveAsync(_identityMap, this, token, id); } public ILoadByKeys<T> LoadMany<T>() { assertNotDisposed(); return new LoadByKeys<T>(this); } public IList<T> LoadMany<T>(params string[] ids) { assertNotDisposed(); return LoadMany<T>().ById(ids); } public IList<T> LoadMany<T>(params Guid[] ids) { assertNotDisposed(); return LoadMany<T>().ById(ids); } public IList<T> LoadMany<T>(params int[] ids) { assertNotDisposed(); return LoadMany<T>().ById(ids); } public IList<T> LoadMany<T>(params long[] ids) { assertNotDisposed(); return LoadMany<T>().ById(ids); } public Task<IList<T>> LoadManyAsync<T>(params string[] ids) { return LoadMany<T>().ByIdAsync(ids); } public Task<IList<T>> LoadManyAsync<T>(params Guid[] ids) { return LoadMany<T>().ByIdAsync(ids); } public Task<IList<T>> LoadManyAsync<T>(params int[] ids) { return LoadMany<T>().ByIdAsync(ids); } public Task<IList<T>> LoadManyAsync<T>(params long[] ids) { return LoadMany<T>().ByIdAsync(ids); } public Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params string[] ids) { return LoadMany<T>().ByIdAsync(ids, token); } public Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params Guid[] ids) { return LoadMany<T>().ByIdAsync(ids, token); } public Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params int[] ids) { return LoadMany<T>().ByIdAsync(ids, token); } public Task<IList<T>> LoadManyAsync<T>(CancellationToken token, params long[] ids) { return LoadMany<T>().ByIdAsync(ids, token); } private class LoadByKeys<TDoc> : ILoadByKeys<TDoc> { private readonly QuerySession _parent; public LoadByKeys(QuerySession parent) { _parent = parent; } public IList<TDoc> ById<TKey>(params TKey[] keys) { assertCorrectIdType<TKey>(); var hitsAndMisses = this.hitsAndMisses(keys); var hits = hitsAndMisses.Item1; var misses = hitsAndMisses.Item2; var documents = fetchDocuments(misses); return concatDocuments(hits, documents); } private void assertCorrectIdType<TKey>() { var mapping = _parent.Tenant.MappingFor(typeof(TDoc)); if (typeof(TKey) != mapping.IdType) { if (typeof(TKey) == typeof(int) && mapping.IdType == typeof(long)) return; throw new InvalidOperationException( $"The id type for {typeof(TDoc).FullName} is {mapping.IdType.Name}, but got {typeof(TKey).Name}"); } } public Task<IList<TDoc>> ByIdAsync<TKey>(params TKey[] keys) { return ByIdAsync(keys, CancellationToken.None); } public IList<TDoc> ById<TKey>(IEnumerable<TKey> keys) { return ById(keys.ToArray()); } public async Task<IList<TDoc>> ByIdAsync<TKey>(IEnumerable<TKey> keys, CancellationToken token = default(CancellationToken)) { assertCorrectIdType<TKey>(); var hitsAndMisses = this.hitsAndMisses(keys.ToArray()); var hits = hitsAndMisses.Item1; var misses = hitsAndMisses.Item2; var documents = await fetchDocumentsAsync(misses, token).ConfigureAwait(false); return concatDocuments(hits, documents); } private IList<TDoc> concatDocuments<TKey>(TKey[] hits, IEnumerable<TDoc> documents) { return hits.Select(key => _parent._identityMap.Retrieve<TDoc>(key)) .Concat(documents) .ToList(); } private Tuple<TKey[], TKey[]> hitsAndMisses<TKey>(TKey[] keys) { var hits = keys.Where(key => _parent._identityMap.Has<TDoc>(key)).ToArray(); var misses = keys.Where(x => !hits.Contains(x)).ToArray(); return new Tuple<TKey[], TKey[]>(hits, misses); } private IEnumerable<TDoc> fetchDocuments<TKey>(TKey[] keys) { var storage = _parent.Tenant.StorageFor(typeof(TDoc)); var resolver = storage.As<IDocumentStorage<TDoc>>(); var tenancyStyle = _parent._store.Tenancy.Style; var cmd = storage.LoadByArrayCommand(tenancyStyle, keys); if (tenancyStyle == TenancyStyle.Conjoined) { cmd.AddNamedParameter(TenantIdArgument.ArgName, _parent.Tenant.TenantId); } var list = new List<TDoc>(); _parent._connection.Execute(cmd, c => { using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var doc = resolver.Resolve(0, reader, _parent._identityMap); list.Add(doc); } } }); return list; } private async Task<IEnumerable<TDoc>> fetchDocumentsAsync<TKey>(TKey[] keys, CancellationToken token) { var storage = _parent.Tenant.StorageFor(typeof(TDoc)); var resolver = storage.As<IDocumentStorage<TDoc>>(); var cmd = storage.LoadByArrayCommand(_parent._store.Tenancy.Style, keys); var list = new List<TDoc>(); await _parent._connection.ExecuteAsync(cmd, async (conn, tkn) => { using (var reader = await cmd.ExecuteReaderAsync(tkn).ConfigureAwait(false)) { while (await reader.ReadAsync(tkn).ConfigureAwait(false)) { var doc = resolver.Resolve(0, reader, _parent._identityMap); list.Add(doc); } } }, token).ConfigureAwait(false); return list; } } public TOut Query<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query) { assertNotDisposed(); QueryStatistics stats; var handler = _store.HandlerFactory.HandlerFor(query, out stats); return _connection.Fetch(handler, _identityMap.ForQuery(), stats, Tenant); } public Task<TOut> QueryAsync<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query, CancellationToken token = new CancellationToken()) { assertNotDisposed(); QueryStatistics stats; var handler = _store.HandlerFactory.HandlerFor(query, out stats); return _connection.FetchAsync(handler, _identityMap.ForQuery(), stats, Tenant, token); } public NpgsqlConnection Connection { get { assertNotDisposed(); return _connection.Connection; } } public IMartenSessionLogger Logger { get { return _connection.As<ManagedConnection>().Logger; } set { _connection.As<ManagedConnection>().Logger = value; } } public int RequestCount => _connection.RequestCount; public void Dispose() { _disposed = true; _connection.Dispose(); WriterPool?.Dispose(); } public T Load<T>(int id) { return load<T>(id); } public T Load<T>(long id) { return load<T>(id); } public T Load<T>(Guid id) { return load<T>(id); } public Task<T> LoadAsync<T>(int id, CancellationToken token = new CancellationToken()) { return loadAsync<T>(id, token); } public Task<T> LoadAsync<T>(long id, CancellationToken token = new CancellationToken()) { return loadAsync<T>(id, token); } public Task<T> LoadAsync<T>(Guid id, CancellationToken token = new CancellationToken()) { return loadAsync<T>(id, token); } } }
using System; using System.IO; using System.Linq; using System.Text; using System.Collections.Generic; using System.Collections.Concurrent; using System.Text.RegularExpressions; using LanguageExt.ClassInstances; using LanguageExt.UnsafeValueAccess; using static LanguageExt.Prelude; namespace LanguageExt.Sys { /// <summary> /// Encapsulated in-memory file-system /// No public API exists for this other than for adding and getting the logical in-memory drives /// </summary> /// <remarks> /// Primarily used for testing (for use with Sys.Test.Runtime or your own runtimes) /// /// This isn't anywhere near as strict as the real file-system, and so it shouldn't really be used to test /// file-operations. It should be used to test simple access to files without having to create them for /// real, or worry about what drives exist. Error messages shouldn't be relied on, only success and failure. /// </remarks> public class MemoryFS { readonly Atom<Entry> machine = Atom<Entry>(new FolderEntry("[machine]", DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, default)); readonly static char[] invalidPath = Path.GetInvalidPathChars(); readonly static char[] invalidFile = Path.GetInvalidFileNameChars(); public string CurrentDir = "C:\\"; public MemoryFS() => AddLogicalDrive("C"); /// <summary> /// Get the logical in-memory drives /// </summary> /// <returns>Sequence of drive names</returns> public Seq<string> GetLogicalDrives() => EnumerateFolders("[root]", "*", SearchOption.TopDirectoryOnly).ToSeq(); /// <summary> /// Add a logical in-memory drive /// </summary> public Unit AddLogicalDrive(string name) => CreateFolder($"{name.TrimEnd(':')}:", DateTime.MinValue); Seq<string> ParsePath(string path) => System.IO.Path.IsPathRooted(path) ? ParsePath1(path) :throw new IOException($"Path not rooted: {path}"); static Seq<string> ParsePath1(string path) => ValidatePathNames(path.Trim() .TrimEnd(new[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}) .Split(new[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}) .ToSeq()); static Seq<string> ValidatePathNames(Seq<string> path) { if (path.IsEmpty) throw new IOException($"Invalid path: {string.Join(Path.DirectorySeparatorChar.ToString(), path)}"); if (path.Head.Exists(invalidPath.Contains)) throw new IOException($"Invalid path: {string.Join(Path.DirectorySeparatorChar.ToString(), path)}"); foreach (var name in path.Tail) { if (name.Exists(invalidFile.Contains)) throw new IOException($"Invalid path: {string.Join(Path.DirectorySeparatorChar.ToString(), path)}"); } return path; } Entry? FindEntry(string path) => FindEntry(machine, ParsePath(path)); Entry? FindEntry(Entry entry, Seq<string> path) => path.IsEmpty ? entry : entry.GetChild(path.Head) switch { null => null, var e => FindEntry(e, path.Tail) }; internal IEnumerable<string> EnumerateFolders(string path, string searchPattern, SearchOption option) { var regex = MakePathSearchRegex(searchPattern); var entry = FindEntry(path); return entry == null || entry is FileEntry ? throw new DirectoryNotFoundException($"Directory not found: {path}") : entry.EnumerateFolders(Empty, regex, option, false) .Map(e => string.Join(Path.DirectorySeparatorChar.ToString(), e.Path)); } internal IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption option) { var regex = MakePathSearchRegex(searchPattern); var entry = FindEntry(path); return entry == null || entry is FileEntry ? throw new DirectoryNotFoundException($"Directory not found: {path}") : entry.EnumerateFiles(Empty, regex, option) .Map(e => string.Join(Path.DirectorySeparatorChar.ToString(), e.Path)); } internal IEnumerable<string> EnumerateEntries(string path, string searchPattern, SearchOption option) { var regex = MakePathSearchRegex(searchPattern); var entry = FindEntry(path); return entry == null || entry is FileEntry ? throw new DirectoryNotFoundException($"Directory not found: {path}") : entry.EnumerateEntries(Empty, regex, option, false) .Map(e => string.Join(Path.DirectorySeparatorChar.ToString(), e.Path)); } static Regex MakePathSearchRegex(string searchPattern) => new Regex(MakeAnchor( searchPattern.Replace("\\", "\\\\") .Replace(".", "\\.") .Replace("$", "\\$") .Replace("^", "\\^") .Replace("+", "\\+") .Replace("{", "\\{") .Replace("}", "\\}") .Replace("[", "\\[") .Replace("]", "\\]") .Replace("(", "\\(") .Replace(")", "\\)") .Replace("|", "\\|") .Replace("?", ".??") .Replace("*", ".*?"))); static string MakeAnchor(string p) => $"^{p}$"; internal Unit CreateFolder(string path, DateTime now) { var path1 = ParsePath(path); machine.Swap(m => path1.NonEmptyInits.Fold(m, go)); return default; Entry go(Entry m, Seq<string> path1) { var folder = new FolderEntry(path1.Last, now, now, now, default); return FindEntry(m, path1) switch { null => m.Add(path1, folder, now).IfLeft(e => throw e), var e => e is FolderEntry ? m : throw new IOException($"File with same name already exists: {path}") }; } } internal bool FolderExists(string path) => FindEntry(path) is FolderEntry; internal Unit DeleteFolder(string path, bool recursive, DateTime now) { machine.Swap(m => m.Delete(ParsePath(path), recursive, now).Case switch { Exception ex => throw ex, Entry m1 => m1, _ => throw new InvalidOperationException() }); return default; } internal Unit SetFolderCreationTime(string path, DateTime dt, DateTime now) { machine.Swap( m => m.Update( ParsePath(path), e => e.SetCreationTime(dt), _ => throw new DirectoryNotFoundException($"Directory not found: {path}"), now).Case switch { Exception ex => throw ex, Entry e => e, _ => throw new InvalidOperationException() } ); return default; } internal Unit SetFolderLastAccessTime(string path, DateTime dt, DateTime now) { machine.Swap( m => m.Update( ParsePath(path), e => e.SetLastAccessTime(dt), _ => throw new DirectoryNotFoundException($"Directory not found: {path}"), now).Case switch { Exception ex => throw ex, Entry e => e, _ => throw new InvalidOperationException() } ); return default; } internal Unit SetFolderLastWriteTime(string path, DateTime dt, DateTime now) { machine.Swap( m => m.Update( ParsePath(path), e => e.SetLastWriteTime(dt), _ => throw new DirectoryNotFoundException($"Directory not found: {path}"), now).Case switch { Exception ex => throw ex, Entry e => e, _ => throw new InvalidOperationException() } ); return default; } internal DateTime GetFolderCreationTime(string path) => FindEntry(path) switch { null => throw new DirectoryNotFoundException($"Directory not found: {path}"), var e => e.CreationTime }; internal DateTime GetFolderLastAccessTime(string path) => FindEntry(path) switch { null => throw new DirectoryNotFoundException($"Directory not found: {path}"), var e => e.LastAccessTime }; internal DateTime GetFolderLastWriteTime(string path) => FindEntry(path) switch { null => throw new DirectoryNotFoundException($"Directory not found: {path}"), var e => e.LastWriteTime }; internal Unit Delete(string path, DateTime now) { machine.Swap(m => FindEntry(m, ParsePath(path)) is FileEntry f ? m.Delete(ParsePath(path), false, now).Case switch { Exception => throw new FileNotFoundException("File not found", path), Entry m1 => m1, _ => throw new InvalidOperationException() } : throw new FileNotFoundException("File not found", path)); return default; } internal bool Exists(string path) => FindEntry(path) is FileEntry; internal byte[] GetFile(string path) => FindEntry(path) is FileEntry f ? f.Data : throw new FileNotFoundException("File not found", path); internal string GetText(string path) => Encoding.UTF8.GetString(GetFile(path)); internal string[] GetLines(string path) => Encoding.UTF8.GetString(GetFile(path)).Split('\n'); internal Unit PutFile(string path, byte[] data, bool overwrite, DateTime now) { var path1 = ParsePath(path); var file = new FileEntry(path1.Last, now, now, now, data); machine.Swap( m => FindEntry(m, path1) switch { null => m.Add(path1, file, now).IfLeft(e => throw e), var e => overwrite ? m.Update(path1, _ => file, _ => new FileNotFoundException(), now).IfLeft(e => throw e) : throw new IOException($"File-system entry already exists: {path}") }); return default; } internal Unit PutText(string path, string text, bool overwrite, DateTime now) => PutFile(path, Encoding.UTF8.GetBytes(text), overwrite, now); internal Unit PutLines(string path, IEnumerable<string> text, bool overwrite, DateTime now) => PutText(path, string.Join("\n", text), overwrite, now); internal Unit Append(string path, byte[] data, DateTime now) { var pre = GetFile(path); var fin = new byte[pre.Length + data.Length]; System.Array.Copy(pre, fin, pre.Length); System.Array.Copy(data, pre.Length, fin, 0, data.Length); return PutFile(path, fin, true, now); } internal Unit AppendText(string path, string text, DateTime now) => PutText(path, GetText(path) + text, true, now); internal Unit AppendLines(string path, IEnumerable<string> lines, DateTime now) => PutLines(path, GetLines(path).Concat(lines).ToArray(), true, now); internal Unit CopyFile(string src, string dest, bool overwrite, DateTime now) => PutFile(dest, GetFile(src), overwrite, now); internal Unit Move(string src, string dest, DateTime now) { var srcp = ParsePath(src); var destp = ParsePath(dest); var parent = Path.GetDirectoryName(dest); if (parent == null) throw new DirectoryNotFoundException($"Parent directory not found: {dest}"); machine.Swap( m => { // Get the source file or folder (it should exist) var esrc = FindEntry(m, srcp); if (esrc == null) throw new IOException($"Source doesn't exist: {src}"); // Get the destination file or folder (it shouldn't exist) var edest = FindEntry(m, destp); if (edest != null) throw new IOException($"Destination already exists: {dest}"); // Create the destination folder var parent1 = ParsePath(parent); var parentFolder = new FolderEntry(parent1.Last, now, now, now, default); var eparent = FindEntry(m, parent1); if(eparent == null) m = m.Add(parent1, parentFolder, now).IfLeft(e => throw e); // Delete the original m = m.Delete(srcp, true, now).IfLeft(e => throw e); // Write the entry in the new location and update the path and name m = m.Add(destp, esrc.UpdateName(destp.Last), now).IfLeft(e => throw e); return m; }); return default; } abstract class Entry { public readonly string Name; public readonly DateTime CreationTime; public readonly DateTime LastAccessTime; public readonly DateTime LastWriteTime; protected Entry(string name, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) { Name = name; CreationTime = creationTime; LastAccessTime = lastAccessTime; LastWriteTime = lastWriteTime; } public abstract IEnumerable<(Seq<string> Path, Entry Entry)> EnumerateEntries(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf); public abstract IEnumerable<(Seq<string> Path, FolderEntry Entry)> EnumerateFolders(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf); public abstract IEnumerable<(Seq<string> Path, FileEntry Entry)> EnumerateFiles(Seq<string> parent, Regex searchPattern, SearchOption option); public abstract Entry? GetChild(string name); public abstract Either<Exception, Entry> Add(Seq<string> path, Entry entry, DateTime now); public abstract Either<Exception, Entry> Update(Seq<string> path, Func<Entry, Either<Exception, Entry>> update, Func<Entry, Either<Exception, Entry>> notFound, DateTime now); public abstract Either<Exception, Entry> Delete(Seq<string> path, bool recursive, DateTime now); public abstract bool IsEmpty { get; } public abstract Entry SetCreationTime(DateTime dt); public abstract Entry SetLastAccessTime(DateTime dt); public abstract Entry SetLastWriteTime(DateTime dt); public abstract Entry UpdateName(string name); } class FileEntry : Entry { public readonly byte[] Data; public FileEntry(string name, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, byte[] data) : base(name, creationTime, lastAccessTime, lastWriteTime) => Data = data; public override IEnumerable<(Seq<string> Path, FolderEntry Entry)> EnumerateFolders(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf) => new (Seq<string>, FolderEntry)[0]; public override IEnumerable<(Seq<string> Path, FileEntry Entry)> EnumerateFiles(Seq<string> parent, Regex searchPattern, SearchOption option) => searchPattern.IsMatch(Name) ? new[] {(parent.Add(Name), this)} : new (Seq<string>, FileEntry)[0]; public override IEnumerable<(Seq<string> Path, Entry Entry)> EnumerateEntries(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf) => includeSelf && searchPattern.IsMatch(Name) ? new[] {(parent.Add(Name), (Entry)this)} : new (Seq<string>, Entry)[0]; public override Entry? GetChild(string name) => null; public override Either<Exception, Entry> Add(Seq<string> path, Entry entry, DateTime now) => new DirectoryNotFoundException(); public override Either<Exception, Entry> Update(Seq<string> path, Func<Entry, Either<Exception, Entry>> update, Func<Entry, Either<Exception, Entry>> notFound, DateTime now) => path.IsEmpty ? update(this) : notFound(this); public override Either<Exception, Entry> Delete(Seq<string> path, bool recursive, DateTime now) => new DirectoryNotFoundException(); public override bool IsEmpty => true; public override Entry SetCreationTime(DateTime dt) => new FileEntry(Name, dt, LastAccessTime, LastWriteTime, Data); public override Entry SetLastAccessTime(DateTime dt) => new FileEntry(Name, CreationTime, dt, LastWriteTime, Data); public override Entry SetLastWriteTime(DateTime dt) => new FileEntry(Name, CreationTime, LastAccessTime, dt, Data); public override Entry UpdateName(string name) => new FileEntry(name, CreationTime, LastAccessTime, LastWriteTime, Data); } class FolderEntry : Entry { readonly Map<OrdStringOrdinalIgnoreCase, string, Entry> Entries; public FolderEntry(string name, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, Map<OrdStringOrdinalIgnoreCase, string, Entry> entries) : base(name, creationTime, lastAccessTime, lastWriteTime) => Entries = entries; IEnumerable<FileEntry> Files => Entries.Values.Choose(e => e is FileEntry f ? Some(f) : None); public override IEnumerable<(Seq<string> Path, FolderEntry Entry)> EnumerateFolders(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf) { var self = includeSelf && searchPattern.IsMatch(Name) ? new [] {(parent.Add(Name), this)} : new (Seq<string>, FolderEntry)[0]; var children = option == SearchOption.AllDirectories ? Entries.Values.Choose(e => e is FolderEntry f ? Some(f.EnumerateFolders(parent.Add(Name), searchPattern, option, true)) : None).Bind(identity) : new (Seq<string>, FolderEntry)[0]; return self.Concat(children); } public override IEnumerable<(Seq<string> Path, FileEntry Entry)> EnumerateFiles(Seq<string> parent, Regex searchPattern, SearchOption option) { var files = Files.Bind(f => f.EnumerateFiles(parent.Add(Name), searchPattern, option)); var children = option == SearchOption.AllDirectories ? Entries.Values.Choose(e => e is FolderEntry f ? Some(f.EnumerateFiles(parent.Add(Name), searchPattern, option)) : None).Bind(identity) : new (Seq<string>, FileEntry) [0]; return files.Concat(children); } public override IEnumerable<(Seq<string> Path, Entry Entry)> EnumerateEntries(Seq<string> parent, Regex searchPattern, SearchOption option, bool includeSelf) { var self = includeSelf && searchPattern.IsMatch(Name) ? new [] {(parent.Add(Name), (Entry)this)} : new (Seq<string>, Entry)[0]; var files = Files.Bind(f => f.EnumerateEntries(parent.Add(Name), searchPattern, option, true)); var children = option == SearchOption.AllDirectories ? Entries.Values.Choose(e => e is FolderEntry f ? Some(f.EnumerateEntries(parent.Add(Name), searchPattern, option, true)) : None).Bind(identity) : new (Seq<string>, Entry) [0]; return self.Concat(files).Concat(children); } public override Either<Exception, Entry> Add(Seq<string> path, Entry entry, DateTime now) => path.Length switch { 0 => entry, 1 => new FolderEntry(Name, CreationTime, now, now, Entries.AddOrUpdate(entry.Name, entry)), _ => Entries.Find(path.Head).Case switch { Entry e => e.Add(path.Tail, entry, now).Case switch { Exception ex => ex, Entry ne => new FolderEntry(Name, CreationTime, now, now, Entries.SetItem(ne.Name, ne)), _ => new InvalidOperationException(), }, _ => new DirectoryNotFoundException() } }; public override Either<Exception, Entry> Update(Seq<string> path, Func<Entry, Either<Exception, Entry>> update, Func<Entry, Either<Exception, Entry>> notFound, DateTime now) => path.IsEmpty ? update(this) : Entries.Find(path.Head).Case switch { Entry e => e.Update(path.Tail, update, notFound, now).Case switch { Exception ex => ex, Entry ne => new FolderEntry(Name, CreationTime, now, now, Entries.SetItem(ne.Name, ne)), _ => new InvalidOperationException(), }, _ => notFound(this), }; public override Either<Exception, Entry> Delete(Seq<string> path, bool recursive, DateTime now) => path.Length switch { 0 => new DirectoryNotFoundException(), 1 => Entries.Find(path.Head).Case switch { Entry e when recursive || e.IsEmpty => new FolderEntry(Name, CreationTime, now, now, Entries.Remove(e.Name)), Entry e => new IOException("Directory not empty"), _ => new IOException("Invalid path") }, _ => Entries.Find(path.Head).Case switch { Entry e => e.Delete(path.Tail, recursive, now).Case switch { Exception ex => ex, Entry ne => new FolderEntry(Name, CreationTime, now, now, Entries.SetItem(ne.Name, ne)), _ => new InvalidOperationException(), }, _ => new DirectoryNotFoundException() } }; public override Entry? GetChild(string name) => Entries.Find(name).Case switch { Entry e => e, _ => null }; public override bool IsEmpty => Entries.IsEmpty; public override Entry SetCreationTime(DateTime dt) => new FolderEntry(Name, dt, LastAccessTime, LastWriteTime, Entries); public override Entry SetLastAccessTime(DateTime dt) => new FolderEntry(Name, CreationTime, dt, LastWriteTime, Entries); public override Entry SetLastWriteTime(DateTime dt) => new FolderEntry(Name, CreationTime, LastAccessTime, dt, Entries); public override Entry UpdateName(string name) => new FolderEntry(name, CreationTime, LastAccessTime, LastWriteTime, Entries); } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 LeanIX GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using LeanIX.Api.Common; using LeanIX.Api.Models; namespace LeanIX.Api { public class BusinessObjectsApi { private readonly ApiClient apiClient = ApiClient.GetInstance(); public ApiClient getClient() { return apiClient; } /// <summary> /// Read all Data Object /// </summary> /// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param> /// <param name="filter">Full-text filter</param> /// <returns></returns> public List<BusinessObject> getBusinessObjects (bool relations, string filter) { // create path and map variables var path = "/businessObjects".Replace("{format}","json"); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); string paramStr = null; if (relations != null){ paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations); queryParams.Add("relations", paramStr); } if (filter != null){ paramStr = (filter != null && filter is DateTime) ? ((DateTime)(object)filter).ToString("u") : Convert.ToString(filter); queryParams.Add("filter", paramStr); } try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (List<BusinessObject>) ApiClient.deserialize(response, typeof(List<BusinessObject>)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Create a new Data Object /// </summary> /// <param name="body">Message-Body</param> /// <returns></returns> public BusinessObject createBusinessObject (BusinessObject body) { // create path and map variables var path = "/businessObjects".Replace("{format}","json"); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); string paramStr = null; try { var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams); if(response != null){ return (BusinessObject) ApiClient.deserialize(response, typeof(BusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Read a Data Object by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param> /// <returns></returns> public BusinessObject getBusinessObject (string ID, bool relations) { // create path and map variables var path = "/businessObjects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; if (relations != null){ paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations); queryParams.Add("relations", paramStr); } try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (BusinessObject) ApiClient.deserialize(response, typeof(BusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Update a Data Object by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="body">Message-Body</param> /// <returns></returns> public BusinessObject updateBusinessObject (string ID, BusinessObject body) { // create path and map variables var path = "/businessObjects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams); if(response != null){ return (BusinessObject) ApiClient.deserialize(response, typeof(BusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Delete a Data Object by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <returns></returns> public void deleteBusinessObject (string ID) { // create path and map variables var path = "/businessObjects/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams); if(response != null){ return ; } else { return ; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return ; } else { throw ex; } } } /// <summary> /// Read all of relation /// </summary> /// <param name="ID">Unique ID</param> /// <returns></returns> public List<ServiceHasBusinessObject> getServiceHasBusinessObjects (string ID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasBusinessObjects".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (List<ServiceHasBusinessObject>) ApiClient.deserialize(response, typeof(List<ServiceHasBusinessObject>)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Create a new relation /// </summary> /// <param name="ID">Unique ID</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasBusinessObject createServiceHasBusinessObject (string ID, BusinessObject body) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasBusinessObjects".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams); if(response != null){ return (ServiceHasBusinessObject) ApiClient.deserialize(response, typeof(ServiceHasBusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Read by relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public ServiceHasBusinessObject getServiceHasBusinessObject (string ID, string relationID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasBusinessObjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (ServiceHasBusinessObject) ApiClient.deserialize(response, typeof(ServiceHasBusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Update relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasBusinessObject updateServiceHasBusinessObject (string ID, string relationID, BusinessObject body) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasBusinessObjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams); if(response != null){ return (ServiceHasBusinessObject) ApiClient.deserialize(response, typeof(ServiceHasBusinessObject)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Delete relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public void deleteServiceHasBusinessObject (string ID, string relationID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasBusinessObjects/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams); if(response != null){ return ; } else { return ; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return ; } else { throw ex; } } } /// <summary> /// Read all of relation /// </summary> /// <param name="ID">Unique ID</param> /// <returns></returns> public List<ServiceHasInterface> getServiceHasInterfaces (string ID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasInterfaces".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (List<ServiceHasInterface>) ApiClient.deserialize(response, typeof(List<ServiceHasInterface>)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Create a new relation /// </summary> /// <param name="ID">Unique ID</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasInterface createServiceHasInterface (string ID, BusinessObject body) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasInterfaces".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams); if(response != null){ return (ServiceHasInterface) ApiClient.deserialize(response, typeof(ServiceHasInterface)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Read by relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public ServiceHasInterface getServiceHasInterface (string ID, string relationID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasInterfaces/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (ServiceHasInterface) ApiClient.deserialize(response, typeof(ServiceHasInterface)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Update relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasInterface updateServiceHasInterface (string ID, string relationID, BusinessObject body) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasInterfaces/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams); if(response != null){ return (ServiceHasInterface) ApiClient.deserialize(response, typeof(ServiceHasInterface)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Delete relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public void deleteServiceHasInterface (string ID, string relationID) { // create path and map variables var path = "/businessObjects/{ID}/serviceHasInterfaces/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams); if(response != null){ return ; } else { return ; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return ; } else { throw ex; } } } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using System.Drawing; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.MapImageSublayerQuery { [Register("MapImageSublayerQuery")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Query map image sublayer", category: "Layers", description: "Find features in a sublayer based on attributes and location.", instructions: "Specify a minimum population in the input field (values under 1810000 will produce a selection in all layers) and tap the query button to query the sublayers in the current view extent. After a short time, the results for each sublayer will appear as graphics.", tags: new[] { "search and query" })] public class MapImageSublayerQuery : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UITextField _queryEntry; private UIBarButtonItem _queryButton; // Graphics overlay for showing selected features. private GraphicsOverlay _selectedFeaturesOverlay; public MapImageSublayerQuery() { Title = "Query a map image sublayer"; } private void Initialize() { // Create a new Map with a vector streets basemap. Map myMap = new Map(BasemapStyle.ArcGISStreets); // Create and set the map's initial view point. MapPoint initialLocation = new MapPoint(-12716000.00, 4170400.00, SpatialReferences.WebMercator); myMap.InitialViewpoint = new Viewpoint(initialLocation, 6000000); // Create the URI to the USA map service. Uri usaServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer"); // Create a new ArcGISMapImageLayer that uses the service URI. ArcGISMapImageLayer usaMapImageLayer = new ArcGISMapImageLayer(usaServiceUri); // Add the layer to the map. myMap.OperationalLayers.Add(usaMapImageLayer); // Assign the map to the MapView. _myMapView.Map = myMap; // Add a graphics overlay to show selected features. _selectedFeaturesOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(_selectedFeaturesOverlay); } // Function to query map image sublayers when the query button is clicked. private void QuerySublayers_Click(object sender, EventArgs e) { // Clear selected features from the graphics overlay. _selectedFeaturesOverlay.Graphics.Clear(); // Prompt the user for a query. UIAlertController prompt = UIAlertController.Create("Enter query", "Query for places with population(2000) > ", UIAlertControllerStyle.Alert); prompt.AddTextField(obj => { _queryEntry = obj; obj.Text = "181000"; obj.KeyboardType = UIKeyboardType.NumberPad; }); prompt.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, submitQuery)); PresentViewController(prompt, true, null); } private async void submitQuery(UIAlertAction obj) { // If the population value entered is not numeric, warn the user and exit. double populationNumber; if (!double.TryParse(_queryEntry.Text.Trim(), out populationNumber)) { UIAlertController alert = UIAlertController.Create("Invalid number", "Population value must be numeric.", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); return; } // Get the USA map image layer (the first and only operational layer in the map). ArcGISMapImageLayer usaMapImageLayer = (ArcGISMapImageLayer) _myMapView.Map.OperationalLayers[0]; try { // Use a utility method on the map image layer to load all the sublayers and tables. await usaMapImageLayer.LoadTablesAndLayersAsync(); // Get the sublayers of interest (skip 'Highways' since it doesn't have the POP2000 field). ArcGISMapImageSublayer citiesSublayer = (ArcGISMapImageSublayer) usaMapImageLayer.Sublayers[0]; ArcGISMapImageSublayer statesSublayer = (ArcGISMapImageSublayer) usaMapImageLayer.Sublayers[2]; ArcGISMapImageSublayer countiesSublayer = (ArcGISMapImageSublayer) usaMapImageLayer.Sublayers[3]; // Get the service feature table for each of the sublayers. ServiceFeatureTable citiesTable = citiesSublayer.Table; ServiceFeatureTable statesTable = statesSublayer.Table; ServiceFeatureTable countiesTable = countiesSublayer.Table; // Create the query parameters that will find features in the current extent with a population greater than the value entered. QueryParameters populationQuery = new QueryParameters { WhereClause = "POP2000 > " + populationNumber, Geometry = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry }; // Query each of the sublayers with the query parameters. FeatureQueryResult citiesQueryResult = await citiesTable.QueryFeaturesAsync(populationQuery); FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery); FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery); // Display the selected cities in the graphics overlay. SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 16); foreach (Feature city in citiesQueryResult) { Graphic cityGraphic = new Graphic(city.Geometry, citySymbol); _selectedFeaturesOverlay.Graphics.Add(cityGraphic); } // Display the selected counties in the graphics overlay. SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Cyan, 2); SimpleFillSymbol countySymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, Color.Cyan, countyLineSymbol); foreach (Feature county in countiesQueryResult) { Graphic countyGraphic = new Graphic(county.Geometry, countySymbol); _selectedFeaturesOverlay.Graphics.Add(countyGraphic); } // Display the selected states in the graphics overlay. SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkCyan, 6); SimpleFillSymbol stateSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, Color.Cyan, stateLineSymbol); foreach (Feature state in statesQueryResult) { Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol); _selectedFeaturesOverlay.Graphics.Add(stateGraphic); } } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show(); } } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; View.AddSubview(_myMapView); _queryButton = new UIBarButtonItem(); _queryButton.Title = "Query"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _queryButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; // Add the views. View.AddSubviews(_myMapView, toolbar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _queryButton.Clicked += QuerySublayers_Click; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _queryButton.Clicked -= QuerySublayers_Click; } } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // 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.Collections.Generic; using Yaapii.Atoms.Enumerable; using Yaapii.Atoms.Scalar; namespace Yaapii.Atoms.Number { /// <summary> /// Average of numbers. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(1, 2, 3, 4).intValue(); /// long sum = new AvgOf(1L, 2L, 3L).longValue(); /// int sum = new AvgOf(numbers.toArray(new Integer[numbers.size()])).intValue(); /// </code> /// </summary> public sealed class AvgOf : NumberEnvelope { /// <summary> /// Average of doubles. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;double&gt;(1D, 2D, 3D, 4D)).AsInt(); /// </code> /// </summary> /// <param name="src">doubles</param> public AvgOf(params double[] src) : this( new ManyOf<double>(src)) { } /// <summary> /// Average of integers. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;int&gt;(1, 2, 3, 4)).AsInt(); /// </code> /// </summary> /// <param name="src">integers</param> public AvgOf(params int[] src) : this( new ManyOf<int>(src)) { } /// <summary> /// Average of longs. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;long&gt;(1, 2, 3, 4)).AsInt(); /// </code> /// </summary> /// <param name="src"></param> public AvgOf(params long[] src) : this( new ManyOf<long>(src)) { } /// <summary> /// Average of floats. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;float&gt;(1F, 2F, 3F, 4F)).AsInt(); /// </code> /// </summary> /// <param name="src">floats</param> public AvgOf(params float[] src) : this( new ManyOf<float>(src)) { } /// <summary> /// Average of doubles. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;double&gt;(1D, 2D, 3D, 4D)).AsInt(); /// </code> /// </summary> /// <param name="src"></param> public AvgOf(IEnumerable<double> src) : base( new ScalarOf<double>(() => { double sum = 0D; double total = 0D; foreach (double val in src) { sum += (double)val; ++total; } if (total == 0D) { total = 1D; } return sum / total; }), new ScalarOf<int>(() => { int sum = 0; int total = 0; foreach (int val in src) { sum += (int)val; ++total; } if (total == 0) { total = 1; } return sum / total; }), new ScalarOf<long>(() => { long sum = 0L; long total = 0L; foreach (long val in src) { sum += (long)val; ++total; } if (total == 0) { total = 1L; } return sum / total; }), new ScalarOf<float>(() => { float sum = 0F; float total = 0F; foreach (float val in src) { sum += (float)val; ++total; } if (total == 0) { total = 1F; } return sum / total; }) ) { } /// <summary> /// Average of integers. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;int&gt;(1, 2, 3, 4)).AsInt(); /// </code> /// </summary> /// <param name="src"></param> public AvgOf(IEnumerable<int> src) : base( new ScalarOf<double>(() => { double sum = 0D; double total = 0D; foreach (double val in src) { sum += (double)val; ++total; } if (total == 0D) { total = 1D; } return sum / total; }), new ScalarOf<int>(() => { int sum = 0; int total = 0; foreach (int val in src) { sum += (int)val; ++total; } if (total == 0) { total = 1; } return sum / total; }), new ScalarOf<long>(() => { long sum = 0L; long total = 0L; foreach (long val in src) { sum += (long)val; ++total; } if (total == 0) { total = 1L; } return sum / total; }), new ScalarOf<float>(() => { float sum = 0F; float total = 0F; foreach (float val in src) { sum += (float)val; ++total; } if (total == 0) { total = 1F; } return sum / total; }) ) { } /// <summary> /// Average of integers. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// int sum = new AvgOf(new Many.Of&lt;long&gt;(1L, 2L, 3L, 4L)).AsInt(); /// </code> /// </summary> /// <param name="src"></param> public AvgOf(IEnumerable<long> src) : base( new ScalarOf<double>(() => { double sum = 0D; double total = 0D; foreach (double val in src) { sum += (double)val; ++total; } if (total == 0D) { total = 1D; } return sum / total; }), new ScalarOf<int>(() => { int sum = 0; int total = 0; foreach (int val in src) { sum += (int)val; ++total; } if (total == 0) { total = 1; } return sum / total; }), new ScalarOf<long>(() => { long sum = 0L; long total = 0L; foreach (long val in src) { sum += (long)val; ++total; } if (total == 0) { total = 1L; } return sum / total; }), new ScalarOf<float>(() => { float sum = 0F; float total = 0F; foreach (float val in src) { sum += (float)val; ++total; } if (total == 0) { total = 1F; } return sum / total; }) ) { } /// <summary> /// Average of integers. /// /// <para>Here is how you can use it to fine mathematical average of numbers:</para> /// /// <code> /// long sum = new AvgOf(new Many.Of&lt;float&gt;(1F, 2F, 3F, 4F)).AsLong(); /// </code> /// </summary> /// <param name="src"></param> public AvgOf(IEnumerable<float> src) : base( new ScalarOf<double>(() => { double sum = 0D; double total = 0D; foreach (double val in src) { sum += (double)val; ++total; } if (total == 0D) { total = 1D; } return sum / total; }), new ScalarOf<int>(() => { int sum = 0; int total = 0; foreach (int val in src) { sum += (int)val; ++total; } if (total == 0) { total = 1; } return sum / total; }), new ScalarOf<long>(() => { long sum = 0L; long total = 0L; foreach (long val in src) { sum += (long)val; ++total; } if (total == 0) { total = 1L; } return sum / total; }), new ScalarOf<float>(() => { float sum = 0F; float total = 0F; foreach (float val in src) { sum += (float)val; ++total; } if (total == 0) { total = 1F; } return sum / total; }) ) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MRTutorial.ProtectedApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * Created 09.07.2017 20:22 * * Copyright (c) Jonas Kohl <https://jonaskohl.de/> */ using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace CapsLockIndicatorV3 { /// <summary> /// A form that indicates if a keystate has changed. /// </summary> public partial class IndicatorOverlay : Form { [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, uint dwNewLong); [DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true)] static extern int SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte bAlpha, uint dwFlags); [DllImport("user32.dll", SetLastError = true, EntryPoint = "GetWindowLong")] static extern int GetWindowLongInt(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong); const uint WS_EX_LAYERED = 0x80000; const uint WS_EX_TOPMOST = 0x00000008; const uint WS_EX_TOOLWINDOW = 0x00000080; const uint WS_EX_TRANSPARENT = 0x00000020; const uint LWA_ALPHA = 0x2; const uint LWA_COLORKEY = 0x1; const int GWL_EXSTYLE = -20; const int WM_NCHITTEST = 0x84; const int HTTRANSPARENT = -1; private Size originalSize; private IndicatorDisplayPosition pos = IndicatorDisplayPosition.BottomRight; const int WINDOW_MARGIN = 16; private double lastOpacity = 1; double opacity_timer_value = 2.0; Color BorderColour = Color.FromArgb( 0xFF, 0x34, 0x4D, 0xB4 ); int BorderSize = 4; protected override void OnFormClosing(FormClosingEventArgs e) { fadeTimer.Stop(); windowCloseTimer.Stop(); positionUpdateTimer.Stop(); base.OnFormClosing(e); } protected override bool ShowWithoutActivation { get { return true; } } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= (int)(WS_EX_TOPMOST | WS_EX_TOOLWINDOW); return cp; } } protected override void WndProc(ref Message m) { if (m.Msg == WM_NCHITTEST) m.Result = (IntPtr)HTTRANSPARENT; else base.WndProc(ref m); } protected override void OnShown(EventArgs e) { UpdatePosition(); base.OnShown(e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } void UpdatePosition() { Rectangle workingArea = Screen.GetWorkingArea(Cursor.Position); Size = new Size(Width, Height); switch (pos) { case IndicatorDisplayPosition.TopLeft: Left = workingArea.X + WINDOW_MARGIN; Top = workingArea.Y + WINDOW_MARGIN; break; case IndicatorDisplayPosition.TopCenter: Left = workingArea.X + (workingArea.Width / 2 - Width / 2); Top = workingArea.Y + WINDOW_MARGIN; break; case IndicatorDisplayPosition.TopRight: Left = workingArea.X + workingArea.Left + (workingArea.Width - Width - WINDOW_MARGIN - workingArea.Left); Top = workingArea.Y + WINDOW_MARGIN; break; case IndicatorDisplayPosition.MiddleLeft: Left = workingArea.X + WINDOW_MARGIN; Top = workingArea.Y + (workingArea.Height / 2 - Height / 2); break; case IndicatorDisplayPosition.MiddleCenter: Left = workingArea.X + (workingArea.Width / 2 - Width / 2); Top = workingArea.Y + (workingArea.Height / 2 - Height / 2); break; case IndicatorDisplayPosition.MiddleRight: Left = workingArea.X + workingArea.Left + (workingArea.Width - Width - WINDOW_MARGIN - workingArea.Left); Top = workingArea.Y + (workingArea.Height / 2 - Height / 2); break; case IndicatorDisplayPosition.BottomLeft: Left = workingArea.X + WINDOW_MARGIN; Top = workingArea.Y + workingArea.Top + (workingArea.Height - Height - WINDOW_MARGIN - workingArea.Top); break; case IndicatorDisplayPosition.BottomCenter: Left = workingArea.X + (workingArea.Width / 2 - Width / 2); Top = workingArea.Y + workingArea.Top + (workingArea.Height - Height - WINDOW_MARGIN - workingArea.Top); break; case IndicatorDisplayPosition.BottomRight: Left = workingArea.X + workingArea.Left + (workingArea.Width - Width - WINDOW_MARGIN - workingArea.Left); Top = workingArea.Y + workingArea.Top + (workingArea.Height - Height - WINDOW_MARGIN - workingArea.Top); break; default: break; } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var factor = DPIHelper.GetScalingFactorPercent(Handle); if (BorderSize > 0) e.Graphics.DrawRectangle(new Pen(BorderColour, (int)(BorderSize * factor)), e.ClipRectangle); using (var sf = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }) using (var b = new SolidBrush(contentLabel.ForeColor)) e.Graphics.DrawString(contentLabel.Text, contentLabel.Font, b, ClientRectangle, sf); } private int ClickThroughWindow(double opacity = 1d) { if (IsDisposed) return -1; uint windowLong = GetWindowLong(Handle, GWL_EXSTYLE); SetWindowLong32(Handle, GWL_EXSTYLE, windowLong | WS_EX_LAYERED); SetLayeredWindowAttributes(Handle, 0, (byte)(opacity * 255), LWA_ALPHA); SetWindowStyles(); return 0; } private void SetWindowStyles() { var style = GetWindowLong(Handle, GWL_EXSTYLE); SetWindowLong(Handle, GWL_EXSTYLE, style | WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST); } public IndicatorOverlay(string content) { InitializeComponent(); } public IndicatorOverlay(string content, int timeoutInMs, IndicatorDisplayPosition position) { pos = position; if (IsDisposed) return; InitializeComponent(); if (IsDisposed) return; contentLabel.Text = content; originalSize = Size; if (timeoutInMs < 1) { windowCloseTimer.Enabled = false; fadeTimer.Enabled = false; } else { windowCloseTimer.Interval = timeoutInMs; fadeTimer.Interval = (int)Math.Floor((decimal)(timeoutInMs / 20)); } ClickThroughWindow(); } public IndicatorOverlay(string content, int timeoutInMs, Color bgColour, Color fgColour, Color bdColour, int bdSize, Font font, IndicatorDisplayPosition position, int indOpacity, bool alwaysShow) { var ret = 0; pos = position; InitializeComponent(); contentLabel.Text = content; Font = font; originalSize = Size; var op = indOpacity / 100d; lastOpacity = op; ret |= SetOpacity(op); if (timeoutInMs < 0 || alwaysShow) { windowCloseTimer.Enabled = false; fadeTimer.Enabled = false; } else { windowCloseTimer.Interval = timeoutInMs; fadeTimer.Interval = (int)Math.Floor((decimal)(timeoutInMs / 20)); } BackColor = bgColour; ForeColor = fgColour; BorderColour = bdColour; BorderSize = bdSize; ret |= ClickThroughWindow(op); if (ret != -1) Show(); } private int SetOpacity(double op) { if (IsDisposed) return -1; byte opb = 0xFF; try { opb = (byte)Math.Min(255, Math.Max(op * 0xFF, 0)); } catch (OverflowException) { } SetLayeredWindowAttributes(Handle, 0, opb, LWA_ALPHA); return 0; } public void UpdateIndicator(string content, IndicatorDisplayPosition position) { pos = position; Opacity = 1; contentLabel.Text = content; opacity_timer_value = 2.0; windowCloseTimer.Stop(); windowCloseTimer.Start(); fadeTimer.Stop(); fadeTimer.Start(); Show(); UpdatePosition(); SetWindowStyles(); } public void UpdateIndicator(string content, int timeoutInMs, IndicatorDisplayPosition position) { pos = position; Opacity = 1; contentLabel.Text = content; opacity_timer_value = 2.0; if (timeoutInMs < 0) { windowCloseTimer.Enabled = false; fadeTimer.Enabled = false; } else { windowCloseTimer.Stop(); windowCloseTimer.Interval = timeoutInMs; windowCloseTimer.Start(); fadeTimer.Stop(); fadeTimer.Interval = (int)Math.Floor((decimal)(timeoutInMs / 20)); fadeTimer.Start(); } Show(); UpdatePosition(); SetWindowStyles(); } public void UpdateIndicator(string content, int timeoutInMs, Color bgColour, Color fgColour, Color bdColour, int bdSize, Font font, IndicatorDisplayPosition position, int indOpacity, bool alwaysShow) { pos = position; var op = indOpacity / 100d; lastOpacity = op; SetOpacity(op); contentLabel.Text = content; Font = font; opacity_timer_value = 2.0; if (timeoutInMs < 0 || alwaysShow) { windowCloseTimer.Enabled = false; fadeTimer.Enabled = false; } else { windowCloseTimer.Stop(); windowCloseTimer.Interval = timeoutInMs; windowCloseTimer.Start(); fadeTimer.Stop(); fadeTimer.Interval = (int)Math.Floor((decimal)(timeoutInMs / 20)); fadeTimer.Start(); } BackColor = bgColour; ForeColor = fgColour; BorderColour = bdColour; BorderSize = bdSize; Show(); Invalidate(); UpdatePosition(); SetWindowStyles(); } void WindowCloseTimerTick(object sender, EventArgs e) { Hide(); } private void fadeTimer_Tick(object sender, EventArgs e) { if (opacity_timer_value > 0) { opacity_timer_value -= 0.1; opacity_timer_value = Math.Max(opacity_timer_value, 0); if (opacity_timer_value <= 1.0) SetOpacity(opacity_timer_value * lastOpacity); } } private void positionUpdateTimer_Tick(object sender, EventArgs e) { UpdatePosition(); SetWindowStyles(); } } }