context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Mail.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // Defines the mail class. // </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.Mails { using System; using System.ComponentModel; using System.Configuration; using System.IO; using System.Net.Mail; using System.Web; using Diagnostics; using DomainModel.Configurations; using DomainModel.Mails; using Links; using SecurityModel; using Sitecore.Data.Items; using Sitecore.Web; using Text; using Utils; /// <summary> /// Defines the mail class. /// </summary> public class Mail : IMail { #region Consts /// <summary> /// The encrypt key. /// </summary> private const string EncryptKey = "5dfkjek5"; /// <summary> Could not load mailtemplate message. </summary> private const string CouldNotLoadTemplateMessage = "Could not load mailtemplate: from {0}"; /// <summary> The Invalid Email address message. </summary> private const string InvalidEmailAddressMessage = "'{0}' is not a valid email address. Check '{2}' field in mail template '{1}'"; /// <summary> The mail sent message. </summary> private const string MailSentToMessage = "Mail sent to {0} with subject: {1}"; /// <summary> The could not send mail message. </summary> private const string CouldNotSendMailMessage = "Could not send Mail: '{0}' To:{1}"; #endregion #region Mail Data fields /// <summary> /// The mail from address. /// </summary> private string mailFrom = string.Empty; /// <summary> /// The mail to adrress. /// </summary> private string mailTo = string.Empty; /// <summary> /// The mail body. /// </summary> private string mailBody = string.Empty; /// <summary> /// The mail subject. /// </summary> private string mailSubject = string.Empty; /// <summary> /// The mail attachment file name. /// </summary> private string mailAttachmentFileName = string.Empty; #endregion /// <summary> /// Sends the mail. /// </summary> /// <param name="to">The mail recipient.</param> /// <param name="from">The mail sender.</param> /// <param name="subject">The mail subject.</param> /// <param name="body">The mail body.</param> /// <param name="attachmentFileName">Name of the attachment file.</param> public virtual void SendMail([NotNull] string to, [NotNull] string from, [NotNull] string subject, [NotNull] string body, [NotNull] string attachmentFileName) { Assert.ArgumentNotNull(to, "to"); Assert.ArgumentNotNull(from, "from"); Assert.ArgumentNotNull(subject, "subject"); Assert.ArgumentNotNull(body, "body"); Assert.ArgumentNotNull(attachmentFileName, "attachmentFileName"); this.mailTo = to; this.mailFrom = from; this.mailBody = body; this.mailAttachmentFileName = attachmentFileName; this.mailSubject = subject; System.Web.UI.Page page = HttpContext.Current.CurrentHandler as System.Web.UI.Page; if (page != null && page.IsAsync) { BackgroundWorker backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; backgroundWorker.DoWork += this.BackgroundWorker_DoWork; backgroundWorker.RunWorkerAsync(); } else { this.SendMail(); } } /// <summary> /// Sends the mail. /// </summary> /// <param name="templateName">Name of the template.</param> /// <param name="parameters">The parameters.</param> /// <param name="queryString">The query string.</param> /// <exception cref="ConfigurationErrorsException"><c>The Configuration errors exception</c>.</exception> public virtual void SendMail([NotNull] string templateName, [NotNull] object parameters, [NotNull] string queryString) { Assert.ArgumentNotNull(templateName, "templateName"); Assert.ArgumentNotNull(parameters, "parameters"); Assert.ArgumentNotNull(queryString, "queryString"); GeneralSettings generalSettings = Context.Entity.GetConfiguration<GeneralSettings>(); Item templateItem = Sitecore.Context.Database.GetItem(generalSettings.MailTemplatesLink); if (templateItem == null) { return; } string templatePath = string.Format("{0}/{1}", templateItem.Paths.FullPath, templateName); Item mailTemplate = Sitecore.Context.Database.GetItem(templatePath); if (mailTemplate == null) { Log.Warn(string.Format(CouldNotLoadTemplateMessage, templatePath), this); return; } string body = mailTemplate["Body"].FormatWith(parameters); string subject = mailTemplate["Subject"].FormatWith(parameters); // Get body from external source string bodySourceId = mailTemplate["BodySource"]; Item bodySourceItem = Sitecore.Context.Database.GetItem(bodySourceId); if (bodySourceItem != null) { UrlString qs = new UrlString(queryString); string orderId = qs["orderid"]; Assert.IsNotNullOrEmpty(orderId, "Unable to send mail. Order number is null or empty."); string encryptKey = Crypto.EncryptTripleDES(orderId, EncryptKey); encryptKey = Uri.EscapeDataString(encryptKey); UrlString url = new UrlString(LinkManager.GetItemUrl(bodySourceItem)); url.Add("key", encryptKey); url.Append(new UrlString(queryString)); using (new SecurityDisabler()) { body += WebUtil.ExecuteWebPage(url.ToString()); } } // Replace relative url with absolute url string urlPrefix = "http://" + HttpContext.Current.Request.Url.Host + "/"; body = body.Replace("href=\"/", "href=\"" + urlPrefix); body = body.Replace("href='/", "href='" + urlPrefix); body = body.Replace("HREF=\"/", "href=\"" + urlPrefix); body = body.Replace("HREF='/", "href='" + urlPrefix); body = body.Replace("src=\"/", "src=\"" + urlPrefix); body = body.Replace("src='/", "src='" + urlPrefix); body = body.Replace("SRC=\"/", "src=\"" + urlPrefix); body = body.Replace("SRC='/", "src='" + urlPrefix); // Configuration.OrderGrid string from = mailTemplate["From"].FormatWith(parameters); if (!MainUtil.IsValidEmailAddress(from)) { string info = string.Format(InvalidEmailAddressMessage, from, templateName, "From"); ConfigurationErrorsException configurationErrorsException = new ConfigurationErrorsException(info); Log.Warn(configurationErrorsException.Message, configurationErrorsException, this); return; } string to = mailTemplate["To"].FormatWith(parameters); if (!MainUtil.IsValidEmailAddress(to)) { string info = string.Format(InvalidEmailAddressMessage, to, templateName, "To"); ConfigurationErrorsException configurationErrorsException = new ConfigurationErrorsException(info); Log.Warn(configurationErrorsException.Message, configurationErrorsException, this); return; } this.SendMail(to, from, subject, body, string.Empty); } /// <summary> /// Handles the DoWork event of the imageEncoder control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param> protected virtual void BackgroundWorker_DoWork([NotNull] object sender, [NotNull] DoWorkEventArgs e) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(e, "e"); this.SendMail(); } /// <summary> /// Sends the mail. /// </summary> protected virtual void SendMail() { MailMessage message = new MailMessage { From = new MailAddress(this.mailFrom), Body = this.mailBody, Subject = this.mailSubject, IsBodyHtml = true }; message.To.Add(this.mailTo); if (this.mailAttachmentFileName != null && File.Exists(this.mailAttachmentFileName)) { Attachment attachment = new Attachment(this.mailAttachmentFileName); message.Attachments.Add(attachment); } try { Sitecore.MainUtil.SendMail(message); Log.Info(string.Format(MailSentToMessage, message.To, message.Subject), "SendMailFromTemplate"); } catch (Exception err) { Log.Error(string.Format(CouldNotSendMailMessage, message.Subject, message.To), err, "SendMailFromTemplate"); HttpContext.Current.Request.Params.Add("MailException", string.Empty); } } } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Account.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "account.google_access_tokens". /// </summary> public class GoogleAccessToken : DbAccess, IGoogleAccessTokenRepository { /// <summary> /// The schema of this table. Returns literal "account". /// </summary> public override string _ObjectNamespace => "account"; /// <summary> /// The schema unqualified name of this table. Returns literal "google_access_tokens". /// </summary> public override string _ObjectName => "google_access_tokens"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "account.google_access_tokens". /// </summary> /// <returns>Returns the number of rows of the table "account.google_access_tokens".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM account.google_access_tokens;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.google_access_tokens" to return all instances of the "GoogleAccessToken" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.google_access_tokens" to return all instances of the "GoogleAccessToken" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "account.google_access_tokens" with a where filter on the column "user_id" to return a single instance of the "GoogleAccessToken" class. /// </summary> /// <param name="userId">The column "user_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.GoogleAccessToken Get(int userId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"GoogleAccessToken\" filtered by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens WHERE user_id=@0;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql, userId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "account.google_access_tokens". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.GoogleAccessToken GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"GoogleAccessToken\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "account.google_access_tokens" sorted by userId. /// </summary> /// <param name="userId">The column "user_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.GoogleAccessToken GetPrevious(int userId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"GoogleAccessToken\" by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens WHERE user_id < @0 ORDER BY user_id DESC LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql, userId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "account.google_access_tokens" sorted by userId. /// </summary> /// <param name="userId">The column "user_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.GoogleAccessToken GetNext(int userId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"GoogleAccessToken\" by \"UserId\" with value {UserId} was denied to the user with Login ID {_LoginId}", userId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens WHERE user_id > @0 ORDER BY user_id LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql, userId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "account.google_access_tokens". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Account.Entities.GoogleAccessToken GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"GoogleAccessToken\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id DESC LIMIT 1;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "account.google_access_tokens" with a where filter on the column "user_id" to return a multiple instances of the "GoogleAccessToken" class. /// </summary> /// <param name="userIds">Array of column "user_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "GoogleAccessToken" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> Get(int[] userIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. userIds: {userIds}.", this._LoginId, userIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens WHERE user_id IN (@0);"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql, userIds); } /// <summary> /// Custom fields are user defined form elements for account.google_access_tokens. /// </summary> /// <returns>Returns an enumerable custom field collection for the table account.google_access_tokens</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='account.google_access_tokens' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('account.google_access_tokens'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of account.google_access_tokens. /// </summary> /// <returns>Returns an enumerable name and value collection for the table account.google_access_tokens</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT user_id AS key, user_id as value FROM account.google_access_tokens;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of GoogleAccessToken class on the database table "account.google_access_tokens". /// </summary> /// <param name="googleAccessToken">The instance of "GoogleAccessToken" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic googleAccessToken, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } object primaryKeyValue = googleAccessToken.user_id; if (Cast.To<int>(primaryKeyValue) > 0) { this.Update(googleAccessToken, Cast.To<int>(primaryKeyValue)); } else { primaryKeyValue = this.Add(googleAccessToken); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('account.google_access_tokens')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('account.google_access_tokens', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of GoogleAccessToken class on the database table "account.google_access_tokens". /// </summary> /// <param name="googleAccessToken">The instance of "GoogleAccessToken" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic googleAccessToken) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. {GoogleAccessToken}", this._LoginId, googleAccessToken); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, googleAccessToken, "account.google_access_tokens", "user_id"); } /// <summary> /// Inserts or updates multiple instances of GoogleAccessToken class on the database table "account.google_access_tokens"; /// </summary> /// <param name="googleAccessTokens">List of "GoogleAccessToken" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> googleAccessTokens) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. {googleAccessTokens}", this._LoginId, googleAccessTokens); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic googleAccessToken in googleAccessTokens) { line++; object primaryKeyValue = googleAccessToken.user_id; if (Cast.To<int>(primaryKeyValue) > 0) { result.Add(googleAccessToken.user_id); db.Update("account.google_access_tokens", "user_id", googleAccessToken, googleAccessToken.user_id); } else { result.Add(db.Insert("account.google_access_tokens", "user_id", googleAccessToken)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "account.google_access_tokens" with an instance of "GoogleAccessToken" class against the primary key value. /// </summary> /// <param name="googleAccessToken">The instance of "GoogleAccessToken" class to update.</param> /// <param name="userId">The value of the column "user_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic googleAccessToken, int userId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"GoogleAccessToken\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {GoogleAccessToken}", userId, this._LoginId, googleAccessToken); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, googleAccessToken, userId, "account.google_access_tokens", "user_id"); } /// <summary> /// Deletes the row of the table "account.google_access_tokens" against the primary key value. /// </summary> /// <param name="userId">The value of the column "user_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(int userId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"GoogleAccessToken\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", userId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM account.google_access_tokens WHERE user_id=@0;"; Factory.NonQuery(this._Catalog, sql, userId); } /// <summary> /// Performs a select statement on table "account.google_access_tokens" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "account.google_access_tokens" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM account.google_access_tokens ORDER BY user_id LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='account.google_access_tokens' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "account.google_access_tokens". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "GoogleAccessToken" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.google_access_tokens WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.GoogleAccessToken(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "account.google_access_tokens" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM account.google_access_tokens WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.GoogleAccessToken(), filters); sql.OrderBy("user_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "account.google_access_tokens". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "GoogleAccessToken" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM account.google_access_tokens WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.GoogleAccessToken(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "account.google_access_tokens" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "GoogleAccessToken" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Account.Entities.GoogleAccessToken> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"GoogleAccessToken\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM account.google_access_tokens WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Account.Entities.GoogleAccessToken(), filters); sql.OrderBy("user_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Account.Entities.GoogleAccessToken>(this._Catalog, sql); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; class Player { const string WaitAction = "WAIT"; const string BlockAction = "BLOCK"; static Level s_level; static Clone s_activeClone; static Func<bool>[] s_blockConditions; static void Main(string[] args) { ReadLevelInfo(); s_blockConditions = new Func<bool>[] { WhenExitIsBehindOfClone, WhenElevatorIsBehindOfClone, }; // game loop while (true) { ReadActiveCloneInfo(); // check if any of block conditions returns true. if ( s_blockConditions.Any( condition => condition() == true ) ) { Console.WriteLine( BlockAction ); continue; } Console.WriteLine( WaitAction ); } } static bool WhenExitIsBehindOfClone() { if ( !s_activeClone.IsOnSameFloor( s_level.ExitAt.Floor ) ) // exit is on different floor. return false; if ( s_activeClone.IsDirectedTo( s_level.ExitAt.Pos ) ) // clone is heading to the exit. return false; // clone is heading to an opposite direction of exit. return true; } static bool WhenElevatorIsBehindOfClone() { Position? elevator = s_level.GetElevator( s_activeClone.Position.Floor ); if ( null == elevator ) // there is no elevator on this floor. return false; if ( s_activeClone.IsDirectedTo( elevator.Value.Pos ) ) // clone is heading to the elevator. return false; // clone is heading to an opposite direction of elevator. return true; } static void ReadLevelInfo() { string[] inputs; inputs = Console.ReadLine().Split(' '); int nbFloors = int.Parse(inputs[0]); // number of floors int width = int.Parse(inputs[1]); // width of the area int nbRounds = int.Parse(inputs[2]); // maximum number of rounds int exitFloor = int.Parse(inputs[3]); // floor on which the exit is found int exitPos = int.Parse(inputs[4]); // position of the exit on its floor int nbTotalClones = int.Parse(inputs[5]); // number of generated clones int nbAdditionalElevators = int.Parse(inputs[6]); // ignore (always zero) int nbElevators = int.Parse(inputs[7]); // number of elevators // read position of all elevators. var elevatorsAt = new List<Position>(); for (int i = 0; i < nbElevators; i++) { inputs = Console.ReadLine().Split(' '); int elevatorFloor = int.Parse(inputs[0]); // floor on which this elevator is found int elevatorPos = int.Parse(inputs[1]); // position of the elevator on its floor elevatorsAt.Add( new Position( elevatorFloor, elevatorPos ) ); } // initialize level. s_level = new Level { Width = width, Floors = nbFloors, Rounds = nbRounds, TotalClones = nbTotalClones, ExitAt = new Position( exitFloor, exitPos ), }; s_level.SetElevators( elevatorsAt ); // initialize clone. s_activeClone = new Clone(); } static void ReadActiveCloneInfo() { string[] inputs = Console.ReadLine().Split(' '); int cloneFloor = int.Parse(inputs[0]); // floor of the leading clone int clonePos = int.Parse(inputs[1]); // position of the leading clone on its floor string direction = inputs[2]; // direction of the leading clone: LEFT or RIGHT s_activeClone.SetPosition( cloneFloor, clonePos ); s_activeClone.SetDirection( direction ); } } class Level { readonly Dictionary<int, Position> _floorElevators = new Dictionary<int, Position>(); public int Width { get; set; } public int Floors { get; set; } public int Rounds { get; set; } public int TotalClones { get; set; } public int Elevators { get { return this.ElevatorsAt.Count; } } public Position ExitAt { get; set; } public HashSet<Position> ElevatorsAt { get; private set; } public void SetElevators(IList<Position> elevators) { ElevatorsAt = new HashSet<Position>( elevators ); // index on which floor there are elevators. _floorElevators.Clear(); foreach (var el in elevators) _floorElevators.Add( el.Floor, el ); } public Position? GetElevator(int floor) { if ( !_floorElevators.ContainsKey( floor ) ) return null; return _floorElevators[ floor ]; } } class Clone { public Position Position { get; private set; } public Direction Direction { get; private set; } public Clone() { this.Position = new Position(); } public void SetPosition(int floor, int position) { this.Position = new Position( floor, position ); } public void SetDirection(string value) { this.Direction = value == "RIGHT" ? Direction.Right : Direction.Left; } public bool IsDirectedTo(int position) { if ( position <= this.Position.Pos && this.Direction == Direction.Left ) return true; if ( position >= this.Position.Pos && this.Direction == Direction.Right ) return true; // directed to other direction. return false; } public bool IsOnSameFloor(int floor) { return floor == this.Position.Floor; } } struct Position : IEquatable<Position> { public int Floor { get; set; } public int Pos { get; set; } public Position(int floor, int position) { this.Floor = floor; this.Pos = position; } public bool Equals(Position other) { return this.Floor == other.Floor && this.Pos == other.Pos; } public override bool Equals(object obj) { if ( obj == null || GetType() != obj.GetType() ) { return false; } return Equals( (Position)obj ); } public override int GetHashCode() { unchecked { var hashcode = this.Floor; hashcode = (hashcode * 397) ^ this.Pos; return hashcode; } } } enum Direction { Left, Right, }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using Xunit; using System.Linq; using UnitTests.TimerTests; // ReSharper disable InconsistentNaming // ReSharper disable UnusedVariable namespace Tester.AzureUtils.TimerTests { [TestCategory("Reminders"), TestCategory("Azure")] public class ReminderTests_AzureTable : ReminderTests_Base, IClassFixture<ReminderTests_AzureTable.Fixture> { public class Fixture : BaseAzureTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { Guid serviceId = Guid.NewGuid(); builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.ServiceId = serviceId; legacy.ClusterConfiguration.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.AzureTable; }); } } public ReminderTests_AzureTable(Fixture fixture) : base(fixture) { fixture.EnsurePreconditionsMet(); } // Basic tests [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_StopByRef() { await Test_Reminders_Basic_StopByRef(); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_ListOps() { await Test_Reminders_Basic_ListOps(); } // Single join tests ... multi grain, multi reminders [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1J_MultiGrainMultiReminders() { await Test_Reminders_1J_MultiGrainMultiReminders(); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_ReminderNotFound() { await Test_Reminders_ReminderNotFound(); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic() { // start up a test grain and get the period that it's programmed to use. IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await grain.GetReminderPeriod(DR); // start up the 'DR' reminder and wait for two ticks to pass. await grain.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway // retrieve the value of the counter-- it should match the sequence number which is the number of periods // we've waited. long last = await grain.GetCounter(DR); Assert.Equal(2, last); // stop the timer and wait for a whole period. await grain.StopReminder(DR); Thread.Sleep(period.Multiply(1) + LEEWAY); // giving some leeway // the counter should not have changed. long curr = await grain.GetCounter(DR); Assert.Equal(last, curr); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_Restart() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await grain.GetReminderPeriod(DR); await grain.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway long last = await grain.GetCounter(DR); Assert.Equal(2, last); await grain.StopReminder(DR); TimeSpan sleepFor = period.Multiply(1) + LEEWAY; Thread.Sleep(sleepFor); // giving some leeway long curr = await grain.GetCounter(DR); Assert.Equal(last, curr); AssertIsInRange(curr, last, last + 1, grain, DR, sleepFor); // start the same reminder again await grain.StartReminder(DR); sleepFor = period.Multiply(2) + LEEWAY; Thread.Sleep(sleepFor); // giving some leeway curr = await grain.GetCounter(DR); AssertIsInRange(curr, 2, 3, grain, DR, sleepFor); await grain.StopReminder(DR); // cleanup } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_MultipleReminders() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); await PerGrainMultiReminderTest(grain); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_2J_MultiGrainMultiReminders() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task<bool>[] tasks = { Task.Run(() => PerGrainMultiReminderTestChurn(g1)), Task.Run(() => PerGrainMultiReminderTestChurn(g2)), Task.Run(() => PerGrainMultiReminderTestChurn(g3)), Task.Run(() => PerGrainMultiReminderTestChurn(g4)), Task.Run(() => PerGrainMultiReminderTestChurn(g5)), }; await Task.Delay(period.Multiply(5)); // start two extra silos ... although it will take it a while before they stabilize log.Info("Starting 2 extra silos"); await this.HostedCluster.StartAdditionalSilosAsync(2, true); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); //Block until all tasks complete. await Task.WhenAll(tasks).WithTimeout(ENDWAIT); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_MultiGrainMultiReminders() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); Task<bool>[] tasks = { Task.Run(() => PerGrainMultiReminderTest(g1)), Task.Run(() => PerGrainMultiReminderTest(g2)), Task.Run(() => PerGrainMultiReminderTest(g3)), Task.Run(() => PerGrainMultiReminderTest(g4)), Task.Run(() => PerGrainMultiReminderTest(g5)), }; //Block until all tasks complete. await Task.WhenAll(tasks).WithTimeout(ENDWAIT); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1F_Basic() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task<bool> test = Task.Run(async () => { await PerGrainFailureTest(g1); return true; }); Thread.Sleep(period.Multiply(failAfter)); // stop the secondary silo log.Info("Stopping secondary silo"); await this.HostedCluster.StopSiloAsync(this.HostedCluster.SecondarySilos.First()); await test; // Block until test completes. } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_2F_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(2,true); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerGrainFailureTest(g3)), Task.Run(() => PerGrainFailureTest(g4)), Task.Run(() => PerGrainFailureTest(g5)), }; Thread.Sleep(period.Multiply(failAfter)); // stop a couple of silos log.Info("Stopping 2 silos"); int i = random.Next(silos.Count); await this.HostedCluster.StopSiloAsync(silos[i]); silos.RemoveAt(i); await this.HostedCluster.StopSiloAsync(silos[random.Next(silos.Count)]); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1F1J_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(1); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerGrainFailureTest(g3)), Task.Run(() => PerGrainFailureTest(g4)), Task.Run(() => PerGrainFailureTest(g5)), }; Thread.Sleep(period.Multiply(failAfter)); var siloToKill = silos[random.Next(silos.Count)]; // stop a silo and join a new one in parallel log.Info("Stopping a silo and joining a silo"); Task t1 = Task.Factory.StartNew(async () => await this.HostedCluster.StopSiloAsync(siloToKill)); Task t2 = this.HostedCluster.StartAdditionalSilosAsync(1, true).ContinueWith(t => { t.GetAwaiter().GetResult(); }); await Task.WhenAll(new[] { t1, t2 }).WithTimeout(ENDWAIT); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. log.Info("\n\n\nReminderTest_1F1J_MultiGrain passed OK.\n\n\n"); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_RegisterSameReminderTwice() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); Task<IGrainReminder> promise1 = grain.StartReminder(DR); Task<IGrainReminder> promise2 = grain.StartReminder(DR); Task<IGrainReminder>[] tasks = { promise1, promise2 }; await Task.WhenAll(tasks).WithTimeout(TimeSpan.FromSeconds(15)); //Assert.NotEqual(promise1.Result, promise2.Result); // TODO: write tests where period of a reminder is changed } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_GT_Basic() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestCopyGrain g2 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); // using same period await g1.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway await g2.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway long last1 = await g1.GetCounter(DR); Assert.Equal(4, last1); long last2 = await g2.GetCounter(DR); Assert.Equal(2, last2); // CopyGrain fault await g1.StopReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway await g2.StopReminder(DR); long curr1 = await g1.GetCounter(DR); Assert.Equal(last1, curr1); long curr2 = await g2.GetCounter(DR); Assert.Equal(4, curr2); // CopyGrain fault } [SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4319"), TestCategory("Functional")] public async Task Rem_Azure_GT_1F1J_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(1); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestCopyGrain g3 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); IReminderTestCopyGrain g4 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerCopyGrainFailureTest(g3)), Task.Run(() => PerCopyGrainFailureTest(g4)), }; Thread.Sleep(period.Multiply(failAfter)); var siloToKill = silos[random.Next(silos.Count)]; // stop a silo and join a new one in parallel log.Info("Stopping a silo and joining a silo"); Task t1 = Task.Run(async () => await this.HostedCluster.StopSiloAsync(siloToKill)); Task t2 = Task.Run(async () => await this.HostedCluster.StartAdditionalSilosAsync(1)); await Task.WhenAll(new[] { t1, t2 }).WithTimeout(ENDWAIT); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Wrong_LowerThanAllowedPeriod() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); await Assert.ThrowsAsync<ArgumentException>(() => grain.StartReminder(DR, TimeSpan.FromMilliseconds(3000), true)); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Wrong_Grain() { IReminderGrainWrong grain = this.GrainFactory.GetGrain<IReminderGrainWrong>(0); await Assert.ThrowsAsync<InvalidOperationException>(() => grain.StartReminder(DR)); } } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedVariable
// // // Copyright (c) Microsoft. 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. namespace Relay.Tests.ScenarioTests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.Relay; using Microsoft.Azure.Management.Relay.Models; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Relay.Tests.TestHelper; using Xunit; public partial class ScenarioTests { [Fact] public void WCFRelayCreateGetUpdateDeleteAuthorizationRules() { using (MockContext context = MockContext.Start(this.GetType())) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(RelayManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } // Create Namespace var namespaceName = TestUtilities.GenerateName(RelayManagementHelper.NamespacePrefix); var createNamespaceResponse = this.RelayManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName, new RelayNamespace() { Location = location, Tags = new Dictionary<string, string>() { {"tag1", "value1"}, {"tag2", "value2"} } }); Assert.NotNull(createNamespaceResponse); Assert.Equal(createNamespaceResponse.Name, namespaceName); Assert.Equal(2, createNamespaceResponse.Tags.Count); Assert.Equal("Microsoft.Relay/Namespaces", createNamespaceResponse.Type); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created namespace var getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); if (string.Compare(getNamespaceResponse.ProvisioningState.ToString(), "Succeeded", true) != 0) TestUtilities.Wait(TimeSpan.FromSeconds(5)); getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); Assert.NotNull(getNamespaceResponse); Assert.Equal("Succeeded", getNamespaceResponse.ProvisioningState.ToString(), StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getNamespaceResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Get all namespaces created within a resourceGroup var getAllNamespacesResponse = RelayManagementClient.Namespaces.ListByResourceGroup(resourceGroup); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); Assert.True(getAllNamespacesResponse.All(ns => ns.Id.Contains(resourceGroup))); // Get all namespaces created within the subscription irrespective of the resourceGroup getAllNamespacesResponse = RelayManagementClient.Namespaces.List(); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); // Create WCF Relay - var wcfRelayName = TestUtilities.GenerateName(RelayManagementHelper.WcfPrefix); var createdWCFRelayResponse = RelayManagementClient.WCFRelays.CreateOrUpdate(resourceGroup, namespaceName, wcfRelayName, new WcfRelay() { RelayType = Relaytype.NetTcp, RequiresClientAuthorization = true, RequiresTransportSecurity = true }); Assert.NotNull(createdWCFRelayResponse); Assert.Equal(createdWCFRelayResponse.Name, wcfRelayName); Assert.True(createdWCFRelayResponse.RequiresClientAuthorization); Assert.True(createdWCFRelayResponse.RequiresTransportSecurity); Assert.Equal(Relaytype.NetTcp, createdWCFRelayResponse.RelayType); var getWCFRelaysResponse = RelayManagementClient.WCFRelays.Get(resourceGroup, namespaceName, wcfRelayName); // Create a WCFRelay AuthorizationRule var authorizationRuleName = TestUtilities.GenerateName(RelayManagementHelper.AuthorizationRulesPrefix); string createPrimaryKey = HttpMockServer.GetVariable("CreatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); var createAutorizationRuleParameter = new AuthorizationRule() { Rights = new List<AccessRights?>() { AccessRights.Listen, AccessRights.Send } }; var jsonStr = RelayManagementHelper.ConvertObjectToJSon(createAutorizationRuleParameter); var test = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, createAutorizationRuleParameter); var createNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, createAutorizationRuleParameter); Assert.NotNull(createNamespaceAuthorizationRuleResponse); Assert.True(createNamespaceAuthorizationRuleResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(createNamespaceAuthorizationRuleResponse.Rights, r => r == right); } // Get created WCFRelay AuthorizationRules var getNamespaceAuthorizationRulesResponse = RelayManagementClient.WCFRelays.GetAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRulesResponse); Assert.True(getNamespaceAuthorizationRulesResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == right); } // Get all WCFRelay AuthorizationRules var getAllNamespaceAuthorizationRulesResponse = RelayManagementClient.WCFRelays.ListAuthorizationRules(resourceGroup, namespaceName,wcfRelayName); Assert.NotNull(getAllNamespaceAuthorizationRulesResponse); Assert.True(getAllNamespaceAuthorizationRulesResponse.Count() >= 1); Assert.Contains(getAllNamespaceAuthorizationRulesResponse, ns => ns.Name == authorizationRuleName); // Update WCFRelay authorizationRule string updatePrimaryKey = HttpMockServer.GetVariable("UpdatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); AuthorizationRule updateNamespaceAuthorizationRuleParameter = new AuthorizationRule(); updateNamespaceAuthorizationRuleParameter.Rights = new List<AccessRights?>() { AccessRights.Listen }; var updateNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, updateNamespaceAuthorizationRuleParameter); Assert.NotNull(updateNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, updateNamespaceAuthorizationRuleResponse.Name); Assert.True(updateNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(updateNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the WCFRelay namespace AuthorizationRule var getNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.GetAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, getNamespaceAuthorizationRuleResponse.Name); Assert.True(getNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the connectionString to the WCFRelay for a Authorization rule created var listKeysResponse = RelayManagementClient.WCFRelays.ListKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(listKeysResponse); Assert.NotNull(listKeysResponse.PrimaryConnectionString); Assert.NotNull(listKeysResponse.SecondaryConnectionString); // Regenerate AuthorizationRules var regenerateKeysParameters = new RegenerateAccessKeyParameters(); regenerateKeysParameters.KeyType = KeyType.PrimaryKey; //Primary Key var regenerateKeysPrimaryResponse = RelayManagementClient.WCFRelays.RegenerateKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysPrimaryResponse); Assert.NotEqual(regenerateKeysPrimaryResponse.PrimaryKey, listKeysResponse.PrimaryKey); Assert.Equal(regenerateKeysPrimaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); regenerateKeysParameters.KeyType = KeyType.SecondaryKey; //Secondary Key var regenerateKeysSecondaryResponse = RelayManagementClient.WCFRelays.RegenerateKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysSecondaryResponse); Assert.NotEqual(regenerateKeysSecondaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); Assert.Equal(regenerateKeysSecondaryResponse.PrimaryKey, regenerateKeysPrimaryResponse.PrimaryKey); // Delete WCFRelay authorizationRule RelayManagementClient.WCFRelays.DeleteAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); try { RelayManagementClient.WCFRelays.Delete(resourceGroup, namespaceName, wcfRelayName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } try { // Delete namespace RelayManagementClient.Namespaces.Delete(resourceGroup, namespaceName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // 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 [assembly: Elmah.Scc("$Id: JScriptAssertion.cs 623 2009-05-30 00:46:46Z azizatif $")] namespace Elmah.Assertions { #region Imports using System; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using Microsoft.JScript; using Microsoft.JScript.Vsa; using Convert=Microsoft.JScript.Convert; using System.Collections.Generic; #endregion /// <summary> /// An assertion implementation that uses a JScript expression to /// determine the outcome. /// </summary> /// <remarks> /// Each instance of this type maintains a separate copy of the JScript /// engine so use it sparingly. For example, instead of creating several /// objects, each with different a expression, try and group all /// expressions that apply to particular context into a single compound /// JScript expression using the conditional-OR (||) operator. /// </remarks> public sealed class JScriptAssertion : IAssertion { private static readonly Regex _directiveExpression = new Regex( @"^ \s* // \s* @([a-zA-Z]+)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private readonly EvaluationStrategy _evaluationStrategy; public JScriptAssertion(string expression) : this(expression, null, null) {} public JScriptAssertion(string expression, string[] assemblyNames, string[] imports) { if (string.IsNullOrEmpty(expression) || expression.TrimStart().Length == 0) { return; } ProcessDirectives(expression, ref assemblyNames, ref imports); var engine = VsaEngine.CreateEngineAndGetGlobalScope(/* fast */ false, assemblyNames ?? new string[0]).engine; if (imports != null && imports.Length > 0) { foreach (var import in imports) Import.JScriptImport(import, engine); } // // We pick on of two expression evaluation strategies depending // on the level of trust available. The full trust version is // faster as it compiles the expression once into a JScript // function and then simply invokes at the time it needs to // evaluate the context. The partial trust strategy is slower // as it compiles the expression each time an evaluation occurs // using the JScript eval. // _evaluationStrategy = FullTrustEvaluationStrategy.IsApplicable() ? (EvaluationStrategy) new FullTrustEvaluationStrategy(expression, engine) : new PartialTrustEvaluationStrategy(expression, engine); } public JScriptAssertion(NameValueCollection settings) : this(settings["expression"], settings.GetValues("assembly"), settings.GetValues("import")) {} public bool Test(object context) { if (context == null) throw new ArgumentNullException("context"); return _evaluationStrategy != null && _evaluationStrategy.Eval(context); } private static void ProcessDirectives(string expression, ref string[] assemblyNames, ref string[] imports) { Debug.Assert(expression != null); List<string> assemblyNameList = null, importList = null; using (var reader = new StringReader(expression)) { string line; var lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; if (line.Trim().Length == 0) continue; var match = _directiveExpression.Match(line); if (!match.Success) // Exit processing on first non-match break; var directive = match.Groups[1].Value; var tail = line.Substring(match.Index + match.Length).Trim(); try { switch (directive) { case "assembly": assemblyNameList = AddDirectiveParameter(directive, tail, assemblyNameList, assemblyNames); break; case "import": importList = AddDirectiveParameter(directive, tail, importList, imports); break; default: throw new FormatException(string.Format("'{0}' is not a recognized directive.", directive)); } } catch (FormatException e) { throw new ArgumentException( string.Format( "Error processing directives section (lead comment) of the JScript expression (see line {0}). {1}", lineNumber.ToString("N0"), e.Message), "expression"); } } } assemblyNames = ListOrElseArray(assemblyNameList, assemblyNames); imports = ListOrElseArray(importList, imports); } private static List<string> AddDirectiveParameter(string directive, string parameter, List<string> list, string[] inits) { Debug.AssertStringNotEmpty(directive); Debug.Assert(parameter != null); if (parameter.Length == 0) throw new FormatException(string.Format("Missing parameter for {0} directive.", directive)); if (list == null) { list = new List<string>(/* capacity */ (inits != null ? inits.Length : 0) + 4); if (inits != null) list.AddRange(inits); } list.Add(parameter); return list; } private static string[] ListOrElseArray(List<string> list, string[] array) { return list != null ? list.ToArray() : array; } private abstract class EvaluationStrategy { private readonly VsaEngine _engine; protected EvaluationStrategy(VsaEngine engine) { Debug.Assert(engine != null); _engine = engine; } public VsaEngine Engine { get { return _engine; } } public abstract bool Eval(object context); } /// <summary> /// Uses the JScript eval function to compile and evaluate the /// expression against the context on each evaluation. /// </summary> private sealed class PartialTrustEvaluationStrategy : EvaluationStrategy { private readonly string _expression; private readonly GlobalScope _scope; private readonly FieldInfo _oldContextField; private readonly FieldInfo _newContextField; public PartialTrustEvaluationStrategy(string expression, VsaEngine engine) : base(engine) { // // Following is equivalent to declaring a "var" in JScript // at the level of the Global object. // _scope = (GlobalScope)engine.GetGlobalScope().GetObject(); _oldContextField = _scope.AddField("$context"); _newContextField = _scope.AddField("$"); _expression = expression; } public override bool Eval(object context) { var engine = Engine; // // Following is equivalent to calling eval in JScript, // with the value of the context variable established at the // global scope in order for it to be available to the // expression source. // _oldContextField.SetValue(_scope, context); _newContextField.SetValue(_scope, context); try { With.JScriptWith(context, engine); return Convert.ToBoolean(Microsoft.JScript.Eval.JScriptEvaluate(_expression, engine)); } finally { engine.PopScriptObject(/* with */); } } } /// <summary> /// Compiles the given expression into a JScript function at time of /// construction and then simply invokes it during evaluation, using /// the context as a parameter. /// </summary> private sealed class FullTrustEvaluationStrategy : EvaluationStrategy { private readonly object _function; public FullTrustEvaluationStrategy(string expression, VsaEngine engine) : base(engine) { // // Equivalent to following in JScript: // new Function('$context', 'with ($context) return (' + expression + ')'); // // IMPORTANT! Leave the closing parentheses surrounding the // return expression on a separate line. This is to guard // against someone using a double-slash (//) to comment out // the remainder of an expression. // const string context = "$context"; _function = LateBinding.CallValue( DefaultThisObject(engine), engine.LenientGlobalObject.Function, new object[] { /* parameters */ context + ",$", /* body... */ @" with (" + context + @") { return ( " + expression + @" ); }" }, /* construct */ true, /* brackets */ false, engine); } public override bool Eval(object context) { // // Following is equivalent to calling apply in JScript. // See http://msdn.microsoft.com/en-us/library/84ht5z59.aspx. // var result = LateBinding.CallValue( DefaultThisObject(Engine), _function, /* args */ new[] { context, context }, /* construct */ false, /* brackets */ false, Engine); return Convert.ToBoolean(result); } private static object DefaultThisObject(VsaEngine engine) { Debug.Assert(engine != null); return ((IActivationObject) engine.ScriptObjectStackTop()).GetDefaultThisObject(); } public static bool IsApplicable() { try { // // FullTrustEvaluationStrategy uses Microsoft.JScript.GlobalObject.Function.CreateInstance, // which requires unmanaged code permission... // new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); return true; } catch (SecurityException) { return false; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Extensibility.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Roslyn.Test.EditorUtilities.NavigateTo; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo { public class NavigateToTests : AbstractNavigateToTests { protected override string Language => "csharp"; protected override Task<TestWorkspace> CreateWorkspace(string content, ExportProvider exportProvider) => TestWorkspace.CreateCSharpAsync(content, exportProvider: exportProvider); [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NoItemsForEmptyFile() { await TestAsync("", async w => { Assert.Empty(await _aggregator.GetItemsAsync("Hello")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClass() { await TestAsync( @"class Foo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimClass() { await TestAsync( @"class @static { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("static")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static"); // Check searching for @static too item = (await _aggregator.GetItemsAsync("@static")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Class, displayName: "@static"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindNestedClass() { await TestAsync( @"class Foo { class Bar { internal class DogBed { } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DogBed")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DogBed", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMemberInANestedClass() { await TestAsync( @"class Foo { class Bar { class DogBed { public void Method() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Method")).Single(); VerifyNavigateToResultItem(item, "Method", MatchKind.Exact, NavigateToItemKind.Method, "Method()", $"{FeaturesResources.type_space}Foo.Bar.DogBed"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericClassWithConstraints() { await TestAsync( @"using System.Collections; class Foo<T> where T : IEnumerable { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class, displayName: "Foo<T>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindGenericMethodWithConstraints() { await TestAsync( @"using System; class Foo<U> { public void Bar<T>(T item) where T : IComparable<T> { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar<T>(T)", $"{FeaturesResources.type_space}Foo<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialClass() { await TestAsync( @"public partial class Foo { int a; } partial class Foo { int b; }", async w => { var expecteditem1 = new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindTypesInMetadata() { await TestAsync( @"using System; Class Program { FileStyleUriParser f; }", async w => { var items = await _aggregator.GetItemsAsync("FileStyleUriParser"); Assert.Equal(items.Count(), 0); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassInNamespace() { await TestAsync( @"namespace Bar { class Foo { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupClass, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Foo")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Class); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStruct() { await TestAsync( @"struct Bar { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupStruct, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("B")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Structure); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnum() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnum, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("Colors")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "Colors", MatchKind.Exact, NavigateToItemKind.Enum); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEnumMember() { await TestAsync( @"enum Colors { Red, Green, Blue }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEnumMember, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("R")).Single(); VerifyNavigateToResultItem(item, "Red", MatchKind.Prefix, NavigateToItemKind.EnumItem); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField1() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField2() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindField3() { await TestAsync( @"class Foo { int bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimField() { await TestAsync( @"class Foo { int @string; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("string")).Single(); VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{FeaturesResources.type_space}Foo"); // Check searching for@string too item = (await _aggregator.GetItemsAsync("@string")).Single(); VerifyNavigateToResultItem(item, "string", MatchKind.Exact, NavigateToItemKind.Field, displayName: "@string", additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField1() { await TestAsync( @"class Foo { int* bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); Assert.Empty(await _aggregator.GetItemsAsync("ar")); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPtrField2() { await TestAsync( @"class Foo { int* bar; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("b")).Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstField() { await TestAsync( @"class Foo { const int bar = 7; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupConstant, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("ba")).Single(); VerifyNavigateToResultItem(item, "bar", MatchKind.Prefix, NavigateToItemKind.Constant); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindIndexer() { var program = @"class Foo { int[] arr; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("this")).Single(); VerifyNavigateToResultItem(item, "this[]", MatchKind.Exact, NavigateToItemKind.Property, displayName: "this[int]", additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindEvent() { var program = "class Foo { public event EventHandler ChangedEventHandler; }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupEvent, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("CEH")).Single(); VerifyNavigateToResultItem(item, "ChangedEventHandler", MatchKind.Regular, NavigateToItemKind.Event, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindAutoProperty() { await TestAsync( @"class Foo { int Bar { get; set; } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("B")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Prefix, NavigateToItemKind.Property, additionalInfo: $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethod() { await TestAsync( @"class Foo { void DoSomething(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindVerbatimMethod() { await TestAsync( @"class Foo { void @static(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("static")).Single(); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{FeaturesResources.type_space}Foo"); // Verify if we search for @static too item = (await _aggregator.GetItemsAsync("@static")).Single(); VerifyNavigateToResultItem(item, "static", MatchKind.Exact, NavigateToItemKind.Method, "@static()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedMethod() { await TestAsync( @"class Foo { void DoSomething(int a, string b) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("DS")).Single(); VerifyNavigateToResultItem(item, "DoSomething", MatchKind.Regular, NavigateToItemKind.Method, "DoSomething(int, string)", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindConstructor() { await TestAsync( @"class Foo { public Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindParameterizedConstructor() { await TestAsync( @"class Foo { public Foo(int i) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "Foo(int)", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindStaticConstructor() { await TestAsync( @"class Foo { static Foo() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Foo")).Single(t => t.Kind == NavigateToItemKind.Method && t.Name != ".ctor"); VerifyNavigateToResultItem(item, "Foo", MatchKind.Exact, NavigateToItemKind.Method, "static Foo()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethods() { await TestAsync("partial class Foo { partial void Bar(); } partial class Foo { partial void Bar() { Console.Write(\"hello\"); } }", async w => { var expecteditem1 = new NavigateToItem("Bar", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Bar"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodDefinitionOnly() { await TestAsync( @"partial class Foo { partial void Bar(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindPartialMethodImplementationOnly() { await TestAsync( @"partial class Foo { partial void Bar() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("Bar")).Single(); VerifyNavigateToResultItem(item, "Bar", MatchKind.Exact, NavigateToItemKind.Method, "Bar()", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindOverriddenMembers() { var program = "class Foo { public virtual string Name { get; set; } } class DogBed : Foo { public override string Name { get { return base.Name; } set {} } }"; await TestAsync(program, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.GlyphItemPublic); var expecteditem1 = new NavigateToItem("Name", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem1 }; var items = await _aggregator.GetItemsAsync("Name"); VerifyNavigateToResultItems(expecteditems, items); var item = items.ElementAt(0); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}DogBed", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); item = items.ElementAt(1); itemDisplay = item.DisplayFactory.CreateItemDisplay(item); unused = itemDisplay.Glyph; Assert.Equal("Name", itemDisplay.Name); Assert.Equal($"{FeaturesResources.type_space}Foo", itemDisplay.AdditionalInformation); _glyphServiceMock.Verify(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindInterface() { await TestAsync( @"public interface IFoo { }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupInterface, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("IF")).Single(); VerifyNavigateToResultItem(item, "IFoo", MatchKind.Prefix, NavigateToItemKind.Interface); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindDelegateInNamespace() { await TestAsync( @"namespace Foo { delegate void DoStuff(); }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupDelegate, StandardGlyphItem.GlyphItemFriend); var item = (await _aggregator.GetItemsAsync("DoStuff")).Single(x => x.Kind != "Method"); VerifyNavigateToResultItem(item, "DoStuff", MatchKind.Exact, NavigateToItemKind.Delegate); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindLambdaExpression() { await TestAsync( @"using System; class Foo { Func<int, int> sqr = x => x * x; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("sqr")).Single(); VerifyNavigateToResultItem(item, "sqr", MatchKind.Exact, NavigateToItemKind.Field, "sqr", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindArray() { await TestAsync( @"class Foo { object[] itemArray; }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("itemArray")).Single(); VerifyNavigateToResultItem(item, "itemArray", MatchKind.Exact, NavigateToItemKind.Field, "itemArray", $"{FeaturesResources.type_space}Foo"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindClassAndMethodWithSameName() { await TestAsync( @"class Foo { } class Test { void Foo() { } }", async w => { var expectedItems = new List<NavigateToItem> { new NavigateToItem("Foo", NavigateToItemKind.Method, "csharp", "Foo", null, MatchKind.Exact, true, null), new NavigateToItem("Foo", NavigateToItemKind.Class, "csharp", "Foo", null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("Foo"); VerifyNavigateToResultItems(expectedItems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindMethodNestedInGenericTypes() { await TestAsync( @"class A<T> { class B { struct C<U> { void M() { } } } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, displayName: "M()", additionalInfo: $"{FeaturesResources.type_space}A<T>.B.C<U>"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task OrderingOfConstructorsAndTypes() { await TestAsync( @"class C1 { C1(int i) { } } class C2 { C2(float f) { } static C2() { } }", async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("C1", NavigateToItemKind.Class, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C1", NavigateToItemKind.Method, "csharp", "C1", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Class, "csharp", "C2", null, MatchKind.Prefix, true, null), new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), // this is the static ctor new NavigateToItem("C2", NavigateToItemKind.Method, "csharp", "C2", null, MatchKind.Prefix, true, null), }; var items = (await _aggregator.GetItemsAsync("C")).ToList(); items.Sort(CompareNavigateToItems); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToMethodWithNullableParameter() { await TestAsync( @"class C { void M(object? o) { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("M")).Single(); VerifyNavigateToResultItem(item, "M", MatchKind.Exact, NavigateToItemKind.Method, "M(object?)"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task StartStopSanity() { // Verify that multiple calls to start/stop and dispose don't blow up await TestAsync( @"public class Foo { }", async w => { // Do one set of queries Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Do the same query again, make sure nothing was left over Assert.Single((await _aggregator.GetItemsAsync("Foo")).Where(x => x.Kind != "Method")); _provider.StopSearch(); // Dispose the provider _provider.Dispose(); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DescriptionItems() { await TestAsync("public\r\nclass\r\nFoo\r\n{ }", async w => { var item = (await _aggregator.GetItemsAsync("F")).Single(x => x.Kind != "Method"); var itemDisplay = item.DisplayFactory.CreateItemDisplay(item); var descriptionItems = itemDisplay.DescriptionItems; Action<string, string> assertDescription = (label, value) => { var descriptionItem = descriptionItems.Single(i => i.Category.Single().Text == label); Assert.Equal(value, descriptionItem.Details.Single().Text); }; assertDescription("File:", w.Documents.Single().Name); assertDescription("Line:", "3"); // one based line number assertDescription("Project:", "Test"); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest1() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_keyword", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem3 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2, expecteditem3 }; var items = await _aggregator.GetItemsAsync("GK"); Assert.Equal(expecteditems.Count(), items.Count()); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest2() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("GKW"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest3() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditem1 = new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Regular, null); var expecteditem2 = new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Substring, true, null); var expecteditems = new List<NavigateToItem> { expecteditem1, expecteditem2 }; var items = await _aggregator.GetItemsAsync("K W"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest4() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("WKG"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest5() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPrivate); var item = (await _aggregator.GetItemsAsync("G_K_W")).Single(); VerifyNavigateToResultItem(item, "get_key_word", MatchKind.Regular, NavigateToItemKind.Field); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest6() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("get_key_word", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, true, null), new NavigateToItem("GetKeyWord", NavigateToItemKind.Field, "csharp", null, null, MatchKind.Prefix, null) }; var items = await _aggregator.GetItemsAsync("get word"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermSplittingTest7() { var source = "class SyllableBreaking {int GetKeyWord; int get_key_word; string get_keyword; int getkeyword; int wake;}"; await TestAsync(source, async w => { var items = await _aggregator.GetItemsAsync("GTW"); Assert.Empty(items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task TermIndexer1() { var source = @"class C { public int this[int y] { get { } } } class D { void Foo() { var q = new C(); var b = q[4]; } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("this[]", NavigateToItemKind.Property, "csharp", null, null, MatchKind.Exact, true, null), }; var items = await _aggregator.GetItemsAsync("this"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern1() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("B.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern2() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { }; var items = await _aggregator.GetItemsAsync("C.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern3() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("B.B.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern4() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("Baz.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern5() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null) }; var items = await _aggregator.GetItemsAsync("F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task DottedPattern6() { var source = "namespace Foo { namespace Bar { class Baz { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { }; var items = await _aggregator.GetItemsAsync("F.F.B.B.Quux"); VerifyNavigateToResultItems(expecteditems, items); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] [WorkItem(7855, "https://github.com/dotnet/Roslyn/issues/7855")] public async Task DottedPattern7() { var source = "namespace Foo { namespace Bar { class Baz<X,Y,Z> { void Quux() { } } } }"; await TestAsync(source, async w => { var expecteditems = new List<NavigateToItem> { new NavigateToItem("Quux", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; var items = await _aggregator.GetItemsAsync("Baz.Q"); VerifyNavigateToResultItems(expecteditems, items); }); } [WorkItem(1174255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174255")] [WorkItem(8009, "https://github.com/dotnet/roslyn/issues/8009")] [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task NavigateToGeneratedFiles() { using (var workspace = await TestWorkspace.CreateAsync(@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document FilePath=""File1.cs""> namespace N { public partial class C { public void VisibleMethod() { } } } </Document> <Document FilePath=""File1.g.cs""> namespace N { public partial class C { public void VisibleMethod_Generated() { } } } </Document> </Project> </Workspace> ", exportProvider: s_exportProvider)) { var aggregateListener = AggregateAsynchronousOperationListener.CreateEmptyListener(); _provider = new NavigateToItemProvider( workspace, _glyphServiceMock.Object, aggregateListener, workspace.ExportProvider.GetExportedValues<Lazy<INavigateToHostVersionService, VisualStudioVersionMetadata>>()); _aggregator = new NavigateToTestAggregator(_provider); var items = await _aggregator.GetItemsAsync("VisibleMethod"); var expectedItems = new List<NavigateToItem>() { new NavigateToItem("VisibleMethod", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Exact, true, null), new NavigateToItem("VisibleMethod_Generated", NavigateToItemKind.Method, "csharp", null, null, MatchKind.Prefix, true, null) }; // The pattern matcher should match 'VisibleMethod' to both 'VisibleMethod' and 'VisibleMethod_Not', except that // the _Not method is declared in a generated file. VerifyNavigateToResultItems(expectedItems, items); } } [WorkItem(11474, "https://github.com/dotnet/roslyn/pull/11474")] [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public async Task FindFuzzy1() { await TestAsync( @"class C { public void ToError() { } }", async w => { SetupVerifiableGlyph(StandardGlyphGroup.GlyphGroupMethod, StandardGlyphItem.GlyphItemPublic); var item = (await _aggregator.GetItemsAsync("ToEror")).Single(); VerifyNavigateToResultItem(item, "ToError", MatchKind.Regular, NavigateToItemKind.Method, displayName: "ToError()"); }); } } }
using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; namespace ChartboostSDK { public class CBExternal { private static bool initialized = false; private static string _logTag = "ChartboostSDK"; public static void Log (string message) { if(CBSettings.isLogging() && Debug.isDebugBuild) Debug.Log(_logTag + "/" + message); } public static bool isInitialized() { return initialized; } private static bool checkInitialized() { if (initialized) { return true; } else { Debug.LogError("The Chartboost SDK needs to be initialized before we can show any ads"); return false; } } #if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE) /// Initializes the Chartboost plugin. /// This must be called before using any other Chartboost features. public static void init() { Log("Unity : init with version " + Application.unityVersion); // Will verify all the id and signatures against example ones. CBSettings.getIOSAppId (); CBSettings.getIOSAppSecret (); CBSettings.getAndroidAppId (); CBSettings.getAndroidAppSecret (); CBSettings.getAmazonAppId (); CBSettings.getAmazonAppSecret (); } /// Initialize the Chartboost plugin with a specific appId and signature /// Either one of the init() methods must be called before using any other Chartboost feature public static void initWithAppId(string appId, string appSignature) { Log("Unity : initWithAppId " + appId + " and version " + Application.unityVersion); } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { Log("Unity : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { Log("Unity : hasInterstitial at location = " + location.ToString()); return false; } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { Log("Unity : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { Log("Unity : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { Log("Unity : hasMoreApps at location = " + location.ToString()); return false; } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { Log("Unity : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { Log("Unity : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { Log("Unity : hasInPlay at location = " + location.ToString()); return false; } public static CBInPlay getInPlay(CBLocation location) { Log("Unity : getInPlay at location = " + location.ToString()); return null; } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { Log("Unity : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { Log("Unity : hasRewardedVideo at location = " + location.ToString()); return false; } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { Log("Unity : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { Log("Unity : chartBoostShouldDisplayMoreAppsCallbackResult"); } /// Sets the name of the game object to be used by the Chartboost iOS SDK public static void setGameObjectName(string name) { Log("Unity : Set Game object name for callbacks to = " + name); } /// Set the custom id used for rewarded video call public static void setCustomId(string id) { Log("Unity : setCustomId to = " + id); } /// Get the custom id used for rewarded video call public static string getCustomId() { Log("Unity : getCustomId"); return ""; } /// Confirm if an age gate passed or failed. When specified /// Chartboost will wait for this call before showing the ios app store public static void didPassAgeGate(bool pass) { Log("Unity : didPassAgeGate with value = " + pass); } /// Open a URL using a Chartboost Custom Scheme public static void handleOpenURL(string url, string sourceApp) { Log("Unity : handleOpenURL at url = " + url + " for app = " + sourceApp); } /// Set to true if you would like to implement confirmation for ad clicks, such as an age gate. /// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial. public static void setShouldPauseClickForConfirmation(bool pause) { Log("Unity : setShouldPauseClickForConfirmation with value = " + pause); } /// Set to false if you want interstitials to be disabled in the first user session public static void setShouldRequestInterstitialsInFirstSession(bool request) { Log("Unity : setShouldRequestInterstitialsInFirstSession with value = " + request); } public static bool getAutoCacheAds() { Log("Unity : getAutoCacheAds"); return false; } public static void setAutoCacheAds(bool autoCacheAds) { Log("Unity : setAutoCacheAds with value = " + autoCacheAds); } public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) { Log("Unity : setStatusBarBehavior with value = " + statusBarBehavior); } public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { Log("Unity : setShouldDisplayLoadingViewForMoreApps with value = " + shouldDisplay); } public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { Log("Unity : setShouldPrefetchVideoContent with value = " + shouldPrefetch); } public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) { int levelType = (int)type; Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) { int levelType = (int)type; Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } public static void pause(bool paused) { Log("Unity : pause"); } /// Shuts down the Chartboost plugin public static void destroy() { Log("Unity : destroy"); } /// Used to notify Chartboost that the Android back button has been pressed /// Returns true to indicate that Chartboost has handled the event and it should not be further processed public static bool onBackPressed() { Log("Unity : onBackPressed"); return true; } public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) { Log("Unity: trackInAppGooglePlayPurchaseEvent"); } public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) { Log("Unity: trackInAppAmazonStorePurchaseEvent"); } public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) { Log("Unity : trackInAppAppleStorePurchaseEvent"); } public static bool isAnyViewVisible() { Log("Unity : isAnyViewVisible"); return false; } public static void setMediation(CBMediation mediator, string version) { Log("Unity : setMediation to = " + mediator.ToString() + " " + version); } public static Boolean isWebViewEnabled() { Log("Unity : isWebViewEnabled"); return false; } #elif UNITY_IPHONE [DllImport("__Internal")] private static extern void _chartBoostInit(string appId, string appSignature, string unityVersion); [DllImport("__Internal")] private static extern bool _chartBoostIsAnyViewVisible(); [DllImport("__Internal")] private static extern void _chartBoostCacheInterstitial(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasInterstitial(string location); [DllImport("__Internal")] private static extern void _chartBoostShowInterstitial(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheRewardedVideo(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasRewardedVideo(string location); [DllImport("__Internal")] private static extern void _chartBoostShowRewardedVideo(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheMoreApps(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasMoreApps(string location); [DllImport("__Internal")] private static extern void _chartBoostShowMoreApps(string location); [DllImport("__Internal")] private static extern void _chartBoostCacheInPlay(string location); [DllImport("__Internal")] private static extern bool _chartBoostHasInPlay(string location); [DllImport("__Internal")] private static extern IntPtr _chartBoostGetInPlay(string location); [DllImport("__Internal")] private static extern void _chartBoostSetCustomId(string id); [DllImport("__Internal")] private static extern void _chartBoostDidPassAgeGate(bool pass); [DllImport("__Internal")] private static extern string _chartBoostGetCustomId(); [DllImport("__Internal")] private static extern void _chartBoostHandleOpenURL(string url, string sourceApp); [DllImport("__Internal")] private static extern void _chartBoostSetShouldPauseClickForConfirmation(bool pause); [DllImport("__Internal")] private static extern void _chartBoostSetShouldRequestInterstitialsInFirstSession(bool request); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayInterstitialCallbackResult(bool result); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayRewardedVideoCallbackResult(bool result); [DllImport("__Internal")] private static extern void _chartBoostShouldDisplayMoreAppsCallbackResult(bool result); [DllImport("__Internal")] private static extern bool _chartBoostGetAutoCacheAds(); [DllImport("__Internal")] private static extern void _chartBoostSetAutoCacheAds(bool autoCacheAds); [DllImport("__Internal")] private static extern void _chartBoostSetShouldDisplayLoadingViewForMoreApps(bool shouldDisplay); [DllImport("__Internal")] private static extern void _chartBoostSetShouldPrefetchVideoContent(bool shouldDisplay); [DllImport("__Internal")] private static extern void _chartBoostTrackInAppPurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier); [DllImport("__Internal")] private static extern void _chartBoostSetGameObjectName(string name); [DllImport("__Internal")] private static extern void _chartBoostSetStatusBarBehavior(CBStatusBarBehavior statusBarBehavior); [DllImport("__Internal")] private static extern void _chartBoostTrackLevelInfo(String eventLabel, int levelType, int mainLevel, int subLevel, String description); [DllImport("__Internal")] private static extern void _chartBoostSetMediation(int mediator, string version); /// Initializes the Chartboost plugin. /// This must be called before using any other Chartboost features. public static void init() { // get the AppID and AppSecret from CBSettings string appID = CBSettings.getIOSAppId (); string appSecret = CBSettings.getIOSAppSecret (); initWithAppId(appID, appSecret); } /// Initialize the Chartboost plugin with a specific appId and signature /// Either one of the init() methods must be called before using any other Chartboost feature public static void initWithAppId(string appId, string appSignature) { Log("Unity : initWithAppId " + appId + " and version " + Application.unityVersion); if (Application.platform == RuntimePlatform.IPhonePlayer) _chartBoostInit(appId, appSignature, Application.unityVersion); initialized = true; } /// Shuts down the Chartboost plugin public static void destroy() { Log("Unity : destroy"); } /// Check to see if any chartboost ad or view is visible public static bool isAnyViewVisible() { bool handled = false; if (!checkInitialized()) return handled; handled = _chartBoostIsAnyViewVisible(); Log("iOS : isAnyViewVisible = " + handled ); return handled; } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheInterstitial(location.ToString()); Log("iOS : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasInterstitial at location = " + location.ToString()); return _chartBoostHasInterstitial(location.ToString()); } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowInterstitial(location.ToString()); Log("iOS : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheMoreApps(location.ToString()); Log("iOS : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasMoreApps at location = " + location.ToString()); return _chartBoostHasMoreApps(location.ToString()); } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowMoreApps(location.ToString()); Log("iOS : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheInPlay(location.ToString()); Log("iOS : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasInPlay at location = " + location.ToString()); return _chartBoostHasInPlay(location.ToString()); } public static CBInPlay getInPlay(CBLocation location) { if (!checkInitialized()) return null; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return null; } IntPtr inPlayId = _chartBoostGetInPlay(location.ToString()); // No Inplay was available right now if(inPlayId == IntPtr.Zero) { return null; } CBInPlay inPlayAd = new CBInPlay(inPlayId); Log("iOS : getInPlay at location = " + location.ToString()); return inPlayAd; } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostCacheRewardedVideo(location.ToString()); Log("iOS : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("iOS : hasRewardedVideo at location = " + location.ToString()); return _chartBoostHasRewardedVideo(location.ToString()); } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _chartBoostShowRewardedVideo(location.ToString()); Log("iOS : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayInterstitialCallbackResult(result); Log("iOS : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayRewardedVideoCallbackResult(result); Log("iOS : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { if (!checkInitialized()) return; _chartBoostShouldDisplayMoreAppsCallbackResult(result); Log("iOS : chartBoostShouldDisplayMoreAppsCallbackResult"); } /// Set the custom id used for rewarded video call public static void setCustomId(string id) { if (!checkInitialized()) return; _chartBoostSetCustomId(id); Log("iOS : setCustomId to = " + id); } /// Get the custom id used for rewarded video call public static string getCustomId() { if (!checkInitialized()) return null; Log("iOS : getCustomId"); return _chartBoostGetCustomId(); } /// Confirm if an age gate passed or failed. When specified /// Chartboost will wait for this call before showing the ios app store public static void didPassAgeGate(bool pass) { if (!checkInitialized()) return; _chartBoostDidPassAgeGate(pass); Log("iOS : didPassAgeGate with value = " + pass); } /// Open a URL using a Chartboost Custom Scheme public static void handleOpenURL(string url, string sourceApp) { if (!checkInitialized()) return; _chartBoostHandleOpenURL(url, sourceApp); Log("iOS : handleOpenURL at url = " + url + " for app = " + sourceApp); } /// Set to true if you would like to implement confirmation for ad clicks, such as an age gate. /// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial. public static void setShouldPauseClickForConfirmation(bool pause) { if (!checkInitialized()) return; _chartBoostSetShouldPauseClickForConfirmation(pause); Log("iOS : setShouldPauseClickForConfirmation with value = " + pause); } /// Set to false if you want interstitials to be disabled in the first user session public static void setShouldRequestInterstitialsInFirstSession(bool request) { if (!checkInitialized()) return; _chartBoostSetShouldRequestInterstitialsInFirstSession(request); Log("iOS : setShouldRequestInterstitialsInFirstSession with value = " + request); } /// Sets the name of the game object to be used by the Chartboost iOS SDK public static void setGameObjectName(string name) { _chartBoostSetGameObjectName(name); Log("iOS : Set Game object name for callbacks to = " + name); } /// Check if we are autocaching ads after every show call public static bool getAutoCacheAds() { Log("iOS : getAutoCacheAds"); return _chartBoostGetAutoCacheAds(); } /// Sets whether to autocache after every show call public static void setAutoCacheAds(bool autoCacheAds) { _chartBoostSetAutoCacheAds(autoCacheAds); Log("iOS : Set AutoCacheAds to = " + autoCacheAds); } /// Sets whether to autocache after every show call public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) { _chartBoostSetStatusBarBehavior(statusBarBehavior); Log("iOS : Set StatusBarBehavior to = " + statusBarBehavior); } /// Sets whether to display loading view for moreapps public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { _chartBoostSetShouldDisplayLoadingViewForMoreApps(shouldDisplay); Log("iOS : Set Should Display Loading View for More Apps to = " + shouldDisplay); } /// Sets whether to prefetch videos or not public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { _chartBoostSetShouldPrefetchVideoContent(shouldPrefetch); Log("iOS : Set setShouldPrefetchVideoContent to = " + shouldPrefetch); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) { int levelType = (int)type; _chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, subLevel, description); Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) { int levelType = (int)type; _chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, 0, description); Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } /// IAP Tracking call public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) { _chartBoostTrackInAppPurchaseEvent(receipt, productTitle, productDescription, productPrice, productCurrency, productIdentifier); Log("iOS : trackInAppAppleStorePurchaseEvent"); } public static void setMediation(CBMediation mediator, string version) { // map string mediation to int for ios int library = 0; // CBMediationOther switch(mediator.ToString()) { case "AdMarvel": library = 1; break; case "Fuse": library = 2; break; case "Fyber": library = 3; break; case "HeyZap": library = 4; break; case "MoPub": library = 5; break; case "Supersonic": library = 6; break; } _chartBoostSetMediation(library, version); Log("iOS : setMediation to = " + mediator.ToString() + " " + version); } #elif UNITY_ANDROID private static AndroidJavaObject _plugin; /// Initialize the android sdk public static void init() { // get the AppID and AppSecret from CBSettings string appID = CBSettings.getSelectAndroidAppId (); string appSecret = CBSettings.getSelectAndroidAppSecret (); initWithAppId(appID, appSecret); } /// Initialize the Chartboost plugin with a specific appId and signature /// Either one of the init() methods must be called before using any other Chartboost feature public static void initWithAppId(string appId, string appSignature) { string unityVersion = Application.unityVersion; Log("Unity : initWithAppId " + appId + " and version " + unityVersion); // find the plugin instance using (var pluginClass = new AndroidJavaClass("com.chartboost.sdk.unity.CBPlugin")) _plugin = pluginClass.CallStatic<AndroidJavaObject>("instance"); _plugin.Call("init", appId, appSignature, unityVersion); initialized = true; } /// Check to see if any chartboost ad or view is visible public static bool isAnyViewVisible() { bool handled = false; if (!checkInitialized()) return handled; handled = _plugin.Call<bool>("isAnyViewVisible"); Log("Android : isAnyViewVisible = " + handled ); return handled; } /// Caches an interstitial. public static void cacheInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheInterstitial", location.ToString()); Log("Android : cacheInterstitial at location = " + location.ToString()); } /// Checks for a cached an interstitial. public static bool hasInterstitial(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasInterstitial at location = " + location.ToString()); return _plugin.Call<bool>("hasInterstitial", location.ToString()); } /// Loads an interstitial. public static void showInterstitial(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showInterstitial", location.ToString()); Log("Android : showInterstitial at location = " + location.ToString()); } /// Caches the more apps screen. public static void cacheMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; }; _plugin.Call("cacheMoreApps", location.ToString()); Log("Android : cacheMoreApps at location = " + location.ToString()); } /// Checks to see if the more apps screen is cached. public static bool hasMoreApps(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasMoreApps at location = " + location.ToString()); return _plugin.Call<bool>("hasMoreApps", location.ToString()); } /// Shows the more apps screen. public static void showMoreApps(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showMoreApps", location.ToString()); Log("Android : showMoreApps at location = " + location.ToString()); } public static void cacheInPlay(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheInPlay", location.ToString()); Log("Android : cacheInPlay at location = " + location.ToString()); } public static bool hasInPlay(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasInPlay at location = " + location.ToString()); return _plugin.Call<bool>("hasCachedInPlay", location.ToString()); } public static CBInPlay getInPlay(CBLocation location) { Log("Android : getInPlay at location = " + location.ToString()); if (!checkInitialized()) return null; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return null; } try { AndroidJavaObject androidInPlayAd = _plugin.Call<AndroidJavaObject>("getInPlay", location.ToString()); CBInPlay inPlayAd = new CBInPlay(androidInPlayAd, _plugin); return inPlayAd; } catch { return null; } } /// Caches a rewarded video. public static void cacheRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("cacheRewardedVideo", location.ToString()); Log("Android : cacheRewardedVideo at location = " + location.ToString()); } /// Checks for a cached a rewarded video. public static bool hasRewardedVideo(CBLocation location) { if (!checkInitialized()) return false; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return false; } Log("Android : hasRewardedVideo at location = " + location.ToString()); return _plugin.Call<bool>("hasRewardedVideo", location.ToString()); } /// Loads a rewarded video. public static void showRewardedVideo(CBLocation location) { if (!checkInitialized()) return; else if(location == null) { Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested"); return; } _plugin.Call("showRewardedVideo", location.ToString()); Log("Android : showRewardedVideo at location = " + location.ToString()); } // Sends back the reponse by the delegate call for ShouldDisplayInterstitial public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayInterstitialCallbackResult", result); Log("Android : chartBoostShouldDisplayInterstitialCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayRewardedVideoCallbackResult", result); Log("Android : chartBoostShouldDisplayRewardedVideoCallbackResult"); } // Sends back the reponse by the delegate call for ShouldDisplayMoreApps public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) { if (!checkInitialized()) return; _plugin.Call("chartBoostShouldDisplayMoreAppsCallbackResult", result); Log("Android : chartBoostShouldDisplayMoreAppsCallbackResult"); } public static void didPassAgeGate(bool pass) { _plugin.Call ("didPassAgeGate",pass); } public static void setShouldPauseClickForConfirmation(bool shouldPause) { _plugin.Call ("setShouldPauseClickForConfirmation",shouldPause); } public static String getCustomId() { return _plugin.Call<String>("getCustomId"); } public static void setCustomId(String customId) { _plugin.Call("setCustomId", customId); } public static bool getAutoCacheAds() { return _plugin.Call<bool>("getAutoCacheAds"); } public static void setAutoCacheAds(bool autoCacheAds) { _plugin.Call ("setAutoCacheAds", autoCacheAds); } public static void setShouldRequestInterstitialsInFirstSession(bool shouldRequest) { _plugin.Call ("setShouldRequestInterstitialsInFirstSession", shouldRequest); } public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) { _plugin.Call ("setShouldDisplayLoadingViewForMoreApps", shouldDisplay); } public static void setShouldPrefetchVideoContent(bool shouldPrefetch) { _plugin.Call ("setShouldPrefetchVideoContent", shouldPrefetch); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) {; int levelType = (int)type; _plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, subLevel, description); Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description)); } /// PIA Level Tracking info call public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) {; int levelType = (int)type; _plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, description); Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description)); } /// Sets the name of the game object to be used by the Chartboost Android SDK public static void setGameObjectName(string name) { _plugin.Call("setGameObjectName", name); } /// Informs the Chartboost SDK about the lifecycle of your app public static void pause(bool paused) { if (!checkInitialized()) return; _plugin.Call("pause", paused); Log("Android : pause"); } /// Shuts down the Chartboost plugin public static void destroy() { if (!checkInitialized()) return; _plugin.Call("destroy"); initialized = false; Log("Android : destroy"); } /// Used to notify Chartboost that the Android back button has been pressed /// Returns true to indicate that Chartboost has handled the event and it should not be further processed public static bool onBackPressed() { bool handled = false; if (!checkInitialized()) return false; handled = _plugin.Call<bool>("onBackPressed"); Log("Android : onBackPressed"); return handled; } public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) { Log("Android: trackInAppGooglePlayPurchaseEvent"); _plugin.Call("trackInAppGooglePlayPurchaseEvent", title,description,price,currency,productID,purchaseData,purchaseSignature); } public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) { Log("Android: trackInAppAmazonStorePurchaseEvent"); _plugin.Call("trackInAppAmazonStorePurchaseEvent", title,description,price,currency,productID,userID,purchaseToken); } public static void setMediation(CBMediation mediator, string version) { _plugin.Call("setMediation", mediator.ToString(), version); Log("Android : setMediation to = " + mediator.ToString() + " " + version); } public static Boolean isWebViewEnabled() { return _plugin.Call<bool>("isWebViewEnabled"); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.Assemblies.EcmaFormat; using System.Reflection.Runtime.General; using System.Reflection.Runtime.MethodInfos; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.CustomAttributes; using System.Runtime.InteropServices; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Runtime.TypeInfos.EcmaFormat { internal sealed partial class EcmaFormatRuntimeNamedTypeInfo : RuntimeNamedTypeInfo { private EcmaFormatRuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle) : base(typeHandle) { _reader = reader; _typeDefinitionHandle = typeDefinitionHandle; _typeDefinition = reader.GetTypeDefinition(_typeDefinitionHandle); } public sealed override Assembly Assembly { get { return EcmaFormatRuntimeAssembly.GetRuntimeAssembly(_reader); } } protected sealed override Guid? ComputeGuidFromCustomAttributes() { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.GetCustomAttributes()) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. CustomAttribute attribute = Reader.GetCustomAttribute(cah); EntityHandle ctorType; EcmaMetadataHelpers.GetAttributeTypeDefRefOrSpecHandle(_reader, attribute.Constructor, out ctorType); StringHandle typeNameHandle; StringHandle typeNamespaceHandle; if (EcmaMetadataHelpers.GetAttributeNamespaceAndName(Reader, ctorType, out typeNamespaceHandle, out typeNameHandle)) { MetadataStringComparer stringComparer = Reader.StringComparer; if (stringComparer.Equals(typeNamespaceHandle, "System.Runtime.InteropServices")) { if (stringComparer.Equals(typeNameHandle, "GuidAttribute")) { ReflectionTypeProvider typeProvider = new ReflectionTypeProvider(throwOnError: false); CustomAttributeValue<RuntimeTypeInfo> customAttributeValue = attribute.DecodeValue(typeProvider); if (customAttributeValue.FixedArguments.Length != 1) continue; CustomAttributeTypedArgument<RuntimeTypeInfo> firstArg = customAttributeValue.FixedArguments[0]; if (firstArg.Value == null) continue; if (!(firstArg.Value is string guidString)) continue; return new Guid(guidString); } } } } return null; } protected sealed override void GetPackSizeAndSize(out int packSize, out int size) { TypeLayout layout = _typeDefinition.GetLayout(); packSize = layout.PackingSize; size = unchecked((int)(layout.Size)); } public sealed override bool IsGenericTypeDefinition { get { return _typeDefinition.GetGenericParameters().Count != 0; } } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return _reader.GetString(_typeDefinition.Namespace).EscapeTypeNameIdentifier(); } } public sealed override Type GetGenericTypeDefinition() { if (IsGenericTypeDefinition) return this; return base.GetGenericTypeDefinition(); } public sealed override int MetadataToken { get { return MetadataTokens.GetToken(_typeDefinitionHandle); } } public sealed override string ToString() { StringBuilder sb = null; foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GetGenericParameters()) { if (sb == null) { sb = new StringBuilder(FullName); sb.Append('['); } else { sb.Append(','); } GenericParameter genericParameter = _reader.GetGenericParameter(genericParameterHandle); sb.Append(genericParameter.Name.GetString(_reader)); } if (sb == null) { return FullName; } else { return sb.Append(']').ToString(); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { TypeAttributes attr = _typeDefinition.Attributes; return attr; } protected sealed override int InternalGetHashCode() { return _typeDefinitionHandle.GetHashCode(); } internal sealed override Type InternalDeclaringType { get { RuntimeTypeInfo declaringType = null; if (EcmaMetadataHelpers.IsNested(_typeDefinition.Attributes)) { TypeDefinitionHandle enclosingTypeDefHandle = _typeDefinition.GetDeclaringType(); declaringType = enclosingTypeDefHandle.ResolveTypeDefinition(_reader); } return declaringType; } } internal sealed override string InternalFullNameOfAssembly { get { return Assembly.FullName; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { string name = _typeDefinition.Name.GetString(_reader); return name.EscapeTypeNameIdentifier(); } protected sealed override IEnumerable<CustomAttributeData> TrueCustomAttributes => RuntimeCustomAttributeData.GetCustomAttributes(_reader, _typeDefinition.GetCustomAttributes()); internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { LowLevelList<RuntimeTypeInfo> genericTypeParameters = new LowLevelList<RuntimeTypeInfo>(); foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GetGenericParameters()) { RuntimeTypeInfo genericParameterType = EcmaFormatRuntimeGenericParameterTypeInfoForTypes.GetRuntimeGenericParameterTypeInfoForTypes(this, genericParameterHandle); genericTypeParameters.Add(genericParameterType); } return genericTypeParameters.ToArray(); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { Handle baseType = _typeDefinition.BaseType; if (baseType.IsNil) return QTypeDefRefOrSpec.Null; return new QTypeDefRefOrSpec(_reader, baseType); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { LowLevelList<QTypeDefRefOrSpec> directlyImplementedInterfaces = new LowLevelList<QTypeDefRefOrSpec>(); foreach (InterfaceImplementationHandle ifcHandle in _typeDefinition.GetInterfaceImplementations()) { InterfaceImplementation interfaceImp = _reader.GetInterfaceImplementation(ifcHandle); directlyImplementedInterfaces.Add(new QTypeDefRefOrSpec(_reader, interfaceImp.Interface)); } return directlyImplementedInterfaces.ToArray(); } } internal MetadataReader Reader { get { return _reader; } } internal TypeDefinitionHandle TypeDefinitionHandle { get { return _typeDefinitionHandle; } } internal EventDefinitionHandleCollection DeclaredEventHandles { get { return _typeDefinition.GetEvents(); } } internal FieldDefinitionHandleCollection DeclaredFieldHandles { get { return _typeDefinition.GetFields(); } } internal MethodDefinitionHandleCollection DeclaredMethodAndConstructorHandles { get { return _typeDefinition.GetMethods(); } } internal PropertyDefinitionHandleCollection DeclaredPropertyHandles { get { return _typeDefinition.GetProperties(); } } public bool Equals(EcmaFormatRuntimeNamedTypeInfo other) { // RuntimeTypeInfo.Equals(object) is the one that encapsulates our unification strategy so defer to him. object otherAsObject = other; return base.Equals(otherAsObject); } #if ENABLE_REFLECTION_TRACE internal sealed override string TraceableTypeName { get { MetadataReader reader = Reader; String s = ""; TypeDefinitionHandle typeDefinitionHandle = TypeDefinitionHandle; do { TypeDefinition typeDefinition = reader.GetTypeDefinition(typeDefinitionHandle); String name = typeDefinition.Name.GetString(reader); if (s == "") s = name; else s = name + "+" + s; typeDefinitionHandle = typeDefinition.GetDeclaringType(); } while (!typeDefinitionHandle.IsNil); if (!_typeDefinition.Namespace.IsNil) { s = _typeDefinition.Namespace.GetString(reader) + "." + s; } return s; } } #endif internal sealed override QTypeDefRefOrSpec TypeDefinitionQHandle { get { return new QTypeDefRefOrSpec(_reader, _typeDefinitionHandle, true); } } private readonly MetadataReader _reader; private readonly TypeDefinitionHandle _typeDefinitionHandle; private readonly TypeDefinition _typeDefinition; } }
using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using Amazon.Runtime; using ThirdParty.Json.LitJson; namespace Amazon.S3.Util { /// <summary> /// A helper class that represents a strongly typed S3 EventNotification item sent to SQS /// </summary> public class S3EventNotification { /// <summary> /// Parse the JSON string into a S3EventNotification object. /// <para> /// The function will try its best to parse input JSON string as best as it can. /// It will not fail even if the JSON string contains unknown properties. /// </para> /// <exception cref="Amazon.Runtime.AmazonClientException">For any parsing errors</exception> /// </summary> public static S3EventNotification ParseJson(string json) { try { var data = JsonMapper.ToObject(json); var s3Event = new S3EventNotification { Records = new List<S3EventNotificationRecord>() }; if (data["Records"] != null) { foreach (JsonData jsonRecord in data["Records"]) { var record = new S3EventNotificationRecord(); record.EventVersion = GetValueAsString(jsonRecord, "eventVersion"); record.EventSource = GetValueAsString(jsonRecord, "eventSource"); record.AwsRegion = GetValueAsString(jsonRecord, "awsRegion"); record.EventVersion = GetValueAsString(jsonRecord, "eventVersion"); if (jsonRecord["eventTime"] != null) record.EventTime = DateTime.Parse((string)jsonRecord["eventTime"], CultureInfo.InvariantCulture); if (jsonRecord["eventName"] != null) { var eventName = (string)jsonRecord["eventName"]; if (!eventName.StartsWith("s3:", StringComparison.OrdinalIgnoreCase)) eventName = "s3:" + eventName; record.EventName = EventType.FindValue(eventName); } if (jsonRecord["userIdentity"] != null) { var jsonUserIdentity = jsonRecord["userIdentity"]; record.UserIdentity = new UserIdentityEntity(); record.UserIdentity.PrincipalId = GetValueAsString(jsonUserIdentity, "principalId"); } if (jsonRecord["requestParameters"] != null) { var jsonRequestParameters = jsonRecord["requestParameters"]; record.RequestParameters = new RequestParametersEntity(); record.RequestParameters.SourceIPAddress = GetValueAsString(jsonRequestParameters, "sourceIPAddress"); } if (jsonRecord["responseElements"] != null) { var jsonResponseElements = jsonRecord["responseElements"]; record.ResponseElements = new ResponseElementsEntity(); record.ResponseElements.XAmzRequestId = GetValueAsString(jsonResponseElements, "x-amz-request-id"); record.ResponseElements.XAmzId2 = GetValueAsString(jsonResponseElements, "x-amz-id-2"); } if (jsonRecord["s3"] != null) { var jsonS3 = jsonRecord["s3"]; record.S3 = new S3Entity(); record.S3.S3SchemaVersion = GetValueAsString(jsonS3, "s3SchemaVersion"); record.S3.ConfigurationId = GetValueAsString(jsonS3, "configurationId"); if (jsonS3["bucket"] != null) { var jsonBucket = jsonS3["bucket"]; record.S3.Bucket = new S3BucketEntity(); record.S3.Bucket.Name = GetValueAsString(jsonBucket, "name"); record.S3.Bucket.Arn = GetValueAsString(jsonBucket, "arn"); if (jsonBucket["ownerIdentity"] != null) { var jsonOwnerIdentity = jsonBucket["ownerIdentity"]; record.S3.Bucket.OwnerIdentity = new UserIdentityEntity(); record.S3.Bucket.OwnerIdentity.PrincipalId = GetValueAsString(jsonOwnerIdentity, "principalId"); } } if (jsonS3["object"] != null) { var jsonObject = jsonS3["object"]; record.S3.Object = new S3ObjectEntity(); record.S3.Object.Key = GetValueAsString(jsonObject, "key"); record.S3.Object.Size = GetValueAsLong(jsonObject, "size"); record.S3.Object.ETag = GetValueAsString(jsonObject, "eTag"); record.S3.Object.VersionId = GetValueAsString(jsonObject, "versionId"); } } s3Event.Records.Add(record); } } return s3Event; } catch(Exception e) { throw new AmazonClientException("Failed to parse json string: " + e.Message, e); } } /// <summary> /// Gets and sets the records for the S3 event notification /// </summary> public List<S3EventNotificationRecord> Records {get;set;} /// <summary> /// The class holds the user identity properties. /// </summary> public class UserIdentityEntity { /// <summary> /// Gets and sets the PrincipalId property. /// </summary> public string PrincipalId { get; set; } } /// <summary> /// This class contains the identity information for an S3 bucket. /// </summary> public class S3BucketEntity { /// <summary> /// Gets and sets the name of the bucket. /// </summary> public string Name {get; set;} /// <summary> /// Gets and sets the bucket owner id. /// </summary> public UserIdentityEntity OwnerIdentity {get; set;} /// <summary> /// Gets and sets the S3 bucket arn. /// </summary> public string Arn {get; set;} } /// <summary> /// This class contains the information for an object in S3. /// </summary> public class S3ObjectEntity { /// <summary> /// Gets and sets the key for the object stored in S3. /// </summary> public string Key {get; set;} /// <summary> /// Gets and sets the size of the object in S3. /// </summary> public long Size {get;set;} /// <summary> /// Gets and sets the etag of the object. This can be used to determine if the object has changed. /// </summary> public string ETag {get;set;} /// <summary> /// Gets and sets the version id of the object in S3. /// </summary> public string VersionId {get;set;} } /// <summary> /// Gets and sets the meta information describing S3. /// </summary> public class S3Entity { /// <summary> /// Gets and sets the ConfigurationId. This ID can be found in the bucket notification configuration. /// </summary> public string ConfigurationId {get;set;} /// <summary> /// Gets and sets the Bucket property. /// </summary> public S3BucketEntity Bucket {get;set;} /// <summary> /// Gets and sets the Object property. /// </summary> public S3ObjectEntity Object { get; set; } /// <summary> /// Gets and sets the S3SchemaVersion property. /// </summary> public string S3SchemaVersion { get; set; } } /// <summary> /// The class holds the request parameters /// </summary> public class RequestParametersEntity { /// <summary> /// Gets and sets the SourceIPAddress. This is the ip address where the request came from. /// </summary> public string SourceIPAddress {get;set;} } /// <summary> /// This class holds the response elements. /// </summary> public class ResponseElementsEntity { /// <summary> /// Gets and sets the XAmzId2 Property. This is the Amazon S3 host that processed the request. /// </summary> public string XAmzId2 {get;set;} /// <summary> /// Gets and sets the XAmzRequestId. This is the Amazon S3 generated request ID. /// </summary> public string XAmzRequestId {get;set;} } /// <summary> /// The class holds the event notification. /// </summary> public class S3EventNotificationRecord { /// <summary> /// Gets and sets the AwsRegion property. /// </summary> public string AwsRegion {get;set;} /// <summary> /// Gets and sets the EventName property. This identities what type of event occurred. /// For example for an object just put in S3 this will be set to EventType.ObjectCreatedPut. /// </summary> public EventType EventName { get; set; } /// <summary> /// Gets and sets the EventSource property. /// </summary> public string EventSource {get;set;} /// <summary> /// Gets and sets the EventType property. The time when S3 finished processing the request. /// </summary> public DateTime EventTime {get;set;} /// <summary> /// Gets and sets the EventVersion property. /// </summary> public string EventVersion {get;set;} /// <summary> /// Gets and sets the RequestParameters property. /// </summary> public RequestParametersEntity RequestParameters { get; set; } /// <summary> /// Gets and sets the ResponseElements property. /// </summary> public ResponseElementsEntity ResponseElements { get; set; } /// <summary> /// Gets and sets the S3 property. /// </summary> public S3Entity S3 { get; set; } /// <summary> /// Gets and sets the UserIdentity property. /// </summary> public UserIdentityEntity UserIdentity { get; set; } } private static string GetValueAsString(JsonData data, string key) { if (data[key] != null) return (string)data[key]; return null; } private static long GetValueAsLong(JsonData data, string key) { if (data[key] != null) { if (data[key].IsInt) return (int)data[key]; else return (long)data[key]; } return 0; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Ref = System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Object pretty printer. /// </summary> public abstract partial class ObjectFormatter { protected ObjectFormatter() { } public string FormatObject(object obj, ObjectFormattingOptions options = null) { return new Formatter(this, options).FormatObject(obj); } #region Reflection Helpers private static bool HasOverriddenToString(Type type) { Ref.MethodInfo method = type.GetMethod( "ToString", Ref.BindingFlags.Public | Ref.BindingFlags.Instance, null, Type.EmptyTypes, null ); return method.DeclaringType != typeof(object); } private static DebuggerDisplayAttribute GetApplicableDebuggerDisplayAttribute(Ref.MemberInfo member) { var result = (DebuggerDisplayAttribute)member.GetCustomAttributes(typeof(DebuggerDisplayAttribute), inherit: true).FirstOrDefault(); if (result != null) { return result; } // TODO (tomat): which assembly should we look at for dd attributes? Type type = member as Type; if (type != null) { foreach (DebuggerDisplayAttribute attr in type.Assembly.GetCustomAttributes(typeof(DebuggerDisplayAttribute), inherit: true)) { if (IsApplicableAttribute(type, attr.Target, attr.TargetTypeName)) { return attr; } } } return null; } private static DebuggerTypeProxyAttribute GetApplicableDebuggerTypeProxyAttribute(Type type) { var result = (DebuggerTypeProxyAttribute)type.GetCustomAttributes(typeof(DebuggerTypeProxyAttribute), inherit: true).FirstOrDefault(); if (result != null) { return result; } // TODO (tomat): which assembly should we look at for proxy attributes? foreach (DebuggerTypeProxyAttribute attr in type.Assembly.GetCustomAttributes(typeof(DebuggerTypeProxyAttribute), inherit: true)) { if (IsApplicableAttribute(type, attr.Target, attr.TargetTypeName)) { return attr; } } return null; } private static bool IsApplicableAttribute(Type type, Type targetType, string targetTypeName) { return type != null && targetType.IsEquivalentTo(type) || targetTypeName != null && type.FullName == targetTypeName; } private static object GetDebuggerTypeProxy(object obj) { // use proxy type if defined: Type type = obj.GetType(); var debuggerTypeProxy = GetApplicableDebuggerTypeProxyAttribute(type); if (debuggerTypeProxy != null) { var proxyType = Type.GetType(debuggerTypeProxy.ProxyTypeName, false, false); if (proxyType != null) { try { if (proxyType.IsGenericTypeDefinition) { proxyType = proxyType.MakeGenericType(type.GetGenericArguments()); } return Activator.CreateInstance( proxyType, Ref.BindingFlags.Instance | Ref.BindingFlags.NonPublic | Ref.BindingFlags.Public, null, new object[] { obj }, null, null ); } catch (Exception) { // no-op, ignore proxy if it is implemented incorrectly } } } return null; } private static Ref.MemberInfo ResolveMember(object obj, string memberName, bool callableOnly) { Type type = obj.GetType(); const Ref.BindingFlags flags = Ref.BindingFlags.Instance | Ref.BindingFlags.Static | Ref.BindingFlags.Public | Ref.BindingFlags.NonPublic | Ref.BindingFlags.DeclaredOnly; // case-sensitive: Type currentType = type; while (currentType != null) { if (!callableOnly) { var field = currentType.GetField(memberName, flags); if (field != null) { return field; } var property = currentType.GetProperty(memberName, flags, null, null, Type.EmptyTypes, null); if (property != null) { var getter = property.GetGetMethod(nonPublic: true); if (getter != null) { return getter; } } } var method = currentType.GetMethod(memberName, flags, null, Type.EmptyTypes, null); if (method != null) { return method; } currentType = currentType.BaseType; } // case-insensitive: currentType = type; while (currentType != null) { IEnumerable<Ref.MemberInfo> members; if (callableOnly) { members = type.GetMethods(flags); } else { members = ((IEnumerable<Ref.MemberInfo>)type.GetFields(flags)).Concat(type.GetProperties(flags)); } Ref.MemberInfo candidate = null; foreach (var member in members) { if (StringComparer.OrdinalIgnoreCase.Equals(memberName, member.Name)) { if (candidate == null) { switch (member.MemberType) { case Ref.MemberTypes.Field: candidate = member; break; case Ref.MemberTypes.Method: if (((Ref.MethodInfo)member).GetParameters().Length == 0) { candidate = member; } break; case Ref.MemberTypes.Property: var getter = ((Ref.PropertyInfo)member).GetGetMethod(nonPublic: true); if (getter != null && getter.GetParameters().Length == 0) { candidate = member; } break; default: throw ExceptionUtilities.UnexpectedValue(member.MemberType); } } else { return null; } } } if (candidate != null) { return candidate; } currentType = currentType.BaseType; } return null; } private static object GetMemberValue(Ref.MemberInfo member, object obj, out Exception exception) { exception = null; try { switch (member.MemberType) { case Ref.MemberTypes.Field: var field = (Ref.FieldInfo)member; return field.GetValue(obj); case Ref.MemberTypes.Method: var method = (Ref.MethodInfo)member; return (method.ReturnType == typeof(void)) ? s_voidValue : method.Invoke(obj, SpecializedCollections.EmptyObjects); case Ref.MemberTypes.Property: var property = (Ref.PropertyInfo)member; return property.GetValue(obj, SpecializedCollections.EmptyObjects); default: throw ExceptionUtilities.UnexpectedValue(member.MemberType); } } catch (Ref.TargetInvocationException e) { exception = e.InnerException; } return null; } private static readonly object s_voidValue = new object(); #endregion #region String Builder Helpers private sealed class Builder { private readonly ObjectFormattingOptions _options; private readonly StringBuilder _sb; private readonly int _lineLengthLimit; private readonly int _lengthLimit; private readonly bool _insertEllipsis; private int _currentLimit; public Builder(int lengthLimit, ObjectFormattingOptions options, bool insertEllipsis) { Debug.Assert(lengthLimit <= options.MaxOutputLength); int lineLengthLimit = options.MaxLineLength; if (insertEllipsis) { lengthLimit = Math.Max(0, lengthLimit - options.Ellipsis.Length - 1); lineLengthLimit = Math.Max(0, lineLengthLimit - options.Ellipsis.Length - 1); } _lengthLimit = lengthLimit; _lineLengthLimit = lineLengthLimit; _currentLimit = Math.Min(lineLengthLimit, lengthLimit); _insertEllipsis = insertEllipsis; _options = options; _sb = new StringBuilder(); } public bool LimitReached { get { return _sb.Length == _lengthLimit; } } public int Remaining { get { return _lengthLimit - _sb.Length; } } // can be negative (the min value is -Ellipsis.Length - 1) private int CurrentRemaining { get { return _currentLimit - _sb.Length; } } public void AppendLine() { // remove line length limit so that we can insert a new line even // if the previous one hit maxed out the line limit: _currentLimit = _lengthLimit; Append(_options.NewLine); // recalc limit for the next line: _currentLimit = (int)Math.Min((long)_sb.Length + _lineLengthLimit, _lengthLimit); } private void AppendEllipsis() { if (_sb.Length > 0 && _sb[_sb.Length - 1] != ' ') { _sb.Append(' '); } _sb.Append(_options.Ellipsis); } public void Append(char c, int count = 1) { if (CurrentRemaining < 0) { return; } int length = Math.Min(count, CurrentRemaining); _sb.Append(c, length); if (_insertEllipsis && length < count) { AppendEllipsis(); } } public void Append(string str, int start = 0, int count = Int32.MaxValue) { if (str == null || CurrentRemaining < 0) { return; } count = Math.Min(count, str.Length - start); int length = Math.Min(count, CurrentRemaining); _sb.Append(str, start, length); if (_insertEllipsis && length < count) { AppendEllipsis(); } } public void AppendFormat(string format, params object[] args) { Append(String.Format(format, args)); } public void AppendGroupOpening() { Append('{'); } public void AppendGroupClosing(bool inline) { if (inline) { Append(" }"); } else { AppendLine(); Append('}'); AppendLine(); } } public void AppendCollectionItemSeparator(bool isFirst, bool inline) { if (isFirst) { if (inline) { Append(' '); } else { AppendLine(); } } else { if (inline) { Append(", "); } else { Append(','); AppendLine(); } } if (!inline) { Append(_options.MemberIndentation); } } internal void AppendInfiniteRecursionMarker() { AppendGroupOpening(); AppendCollectionItemSeparator(isFirst: true, inline: true); Append(_options.Ellipsis); AppendGroupClosing(inline: true); } public override string ToString() { return _sb.ToString(); } } #endregion #region Language Specific Formatting private string FormatPrimitive(object obj, bool quoteStrings, bool includeCodePoints, bool useHexadecimalNumbers) { if (ReferenceEquals(obj, s_voidValue)) { return String.Empty; } if (obj == null) { return NullLiteral; } if (obj is bool) { return FormatLiteral((bool)obj); } string str; if ((str = obj as string) != null) { return FormatLiteral(str, quoteStrings, useHexadecimalNumbers); } if (obj is char) { return FormatLiteral((char)obj, quoteStrings, includeCodePoints, useHexadecimalNumbers); } if (obj is sbyte) { return FormatLiteral((sbyte)obj, useHexadecimalNumbers); } if (obj is byte) { return FormatLiteral((byte)obj, useHexadecimalNumbers); } if (obj is short) { return FormatLiteral((short)obj, useHexadecimalNumbers); } if (obj is ushort) { return FormatLiteral((ushort)obj, useHexadecimalNumbers); } if (obj is int) { return FormatLiteral((int)obj, useHexadecimalNumbers); } if (obj is uint) { return FormatLiteral((uint)obj, useHexadecimalNumbers); } if (obj is long) { return FormatLiteral((long)obj, useHexadecimalNumbers); } if (obj is ulong) { return FormatLiteral((ulong)obj, useHexadecimalNumbers); } if (obj is double) { return FormatLiteral((double)obj); } if (obj is float) { return FormatLiteral((float)obj); } if (obj is decimal) { return FormatLiteral((decimal)obj); } if (obj.GetType().IsEnum) { return obj.ToString(); } return null; } /// <summary> /// String that describes "void" return type in the language. /// </summary> public abstract object VoidDisplayString { get; } /// <summary> /// String that describes "null" literal in the language. /// </summary> public abstract string NullLiteral { get; } public abstract string FormatLiteral(bool value); public abstract string FormatLiteral(string value, bool quote, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(char value, bool quote, bool includeCodePoints = false, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(sbyte value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(byte value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(short value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(ushort value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(int value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(uint value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(long value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(ulong value, bool useHexadecimalNumbers = false); public abstract string FormatLiteral(double value); public abstract string FormatLiteral(float value); public abstract string FormatLiteral(decimal value); // TODO (tomat): Use DebuggerDisplay.Type if specified? public abstract string FormatTypeName(Type type, ObjectFormattingOptions options); public abstract string FormatMemberName(Ref.MemberInfo member); /// <summary> /// Formats an array type name (vector or multidimensional). /// </summary> public abstract string FormatArrayTypeName(Array array, ObjectFormattingOptions options); /// <summary> /// Returns true if the member shouldn't be displayed (e.g. it's a compiler generated field). /// </summary> public virtual bool IsHiddenMember(Ref.MemberInfo member) { return false; } internal static ObjectDisplayOptions GetObjectDisplayOptions(bool useHexadecimalNumbers) { return useHexadecimalNumbers ? ObjectDisplayOptions.UseHexadecimalNumbers : ObjectDisplayOptions.None; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using SysTx = System.Transactions; namespace System.Data.Odbc { public sealed partial class OdbcConnection : DbConnection, ICloneable { private int _connectionTimeout = ADP.DefaultConnectionTimeout; private OdbcInfoMessageEventHandler _infoMessageEventHandler; private WeakReference _weakTransaction; private OdbcConnectionHandle _connectionHandle; private ConnectionState _extraState = default(ConnectionState); // extras, like Executing and Fetching, that we add to the State. public OdbcConnection(string connectionString) : this() { ConnectionString = connectionString; } private OdbcConnection(OdbcConnection connection) : this() { // Clone CopyFrom(connection); _connectionTimeout = connection._connectionTimeout; } internal OdbcConnectionHandle ConnectionHandle { get { return _connectionHandle; } set { Debug.Assert(null == _connectionHandle, "reopening a connection?"); _connectionHandle = value; } } public override string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(value); } } [ DefaultValue(ADP.DefaultConnectionTimeout), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public new int ConnectionTimeout { get { return _connectionTimeout; } set { if (value < 0) throw ODBC.NegativeArgument(); if (IsOpen) throw ODBC.CantSetPropertyOnOpenConnection(); _connectionTimeout = value; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string Database { get { if (IsOpen && !ProviderInfo.NoCurrentCatalog) { //Note: CURRENT_CATALOG may not be supported by the current driver. In which //case we ignore any error (without throwing), and just return string.empty. //As we really don't want people to have to have try/catch around simple properties return GetConnectAttrString(ODBC32.SQL_ATTR.CURRENT_CATALOG); } //Database is not available before open, and its not worth parsing the //connection string over. return string.Empty; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string DataSource { get { if (IsOpen) { // note: This will return an empty string if the driver keyword was used to connect // see ODBC3.0 Programmers Reference, SQLGetInfo // return GetInfoStringUnhandled(ODBC32.SQL_INFO.SERVER_NAME, true); } return string.Empty; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override string ServerVersion { get { return InnerConnection.ServerVersion; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override ConnectionState State { get { return InnerConnection.State; } } internal OdbcConnectionPoolGroupProviderInfo ProviderInfo { get { Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); return (OdbcConnectionPoolGroupProviderInfo)this.PoolGroup.ProviderInfo; } } internal ConnectionState InternalState { get { return (this.State | _extraState); } } internal bool IsOpen { get { return (InnerConnection is OdbcConnectionOpen); } } internal OdbcTransaction LocalTransaction { get { OdbcTransaction result = null; if (null != _weakTransaction) { result = ((OdbcTransaction)_weakTransaction.Target); } return result; } set { _weakTransaction = null; if (null != value) { _weakTransaction = new WeakReference((OdbcTransaction)value); } } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public string Driver { get { if (IsOpen) { if (ProviderInfo.DriverName == null) { ProviderInfo.DriverName = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); } return ProviderInfo.DriverName; } return ADP.StrEmpty; } } internal bool IsV3Driver { get { if (ProviderInfo.DriverVersion == null) { ProviderInfo.DriverVersion = GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_ODBC_VER); // protected against null and index out of range. Number cannot be bigger than 99 if (ProviderInfo.DriverVersion != null && ProviderInfo.DriverVersion.Length >= 2) { try { // mdac 89269: driver may return malformatted string ProviderInfo.IsV3Driver = (int.Parse(ProviderInfo.DriverVersion.Substring(0, 2), CultureInfo.InvariantCulture) >= 3); } catch (System.FormatException e) { ProviderInfo.IsV3Driver = false; ADP.TraceExceptionWithoutRethrow(e); } } else { ProviderInfo.DriverVersion = ""; } } return ProviderInfo.IsV3Driver; } } public event OdbcInfoMessageEventHandler InfoMessage { add { _infoMessageEventHandler += value; } remove { _infoMessageEventHandler -= value; } } internal char EscapeChar(string method) { CheckState(method); if (!ProviderInfo.HasEscapeChar) { string escapeCharString; escapeCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.SEARCH_PATTERN_ESCAPE); Debug.Assert((escapeCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.EscapeChar = (escapeCharString.Length == 1) ? escapeCharString[0] : QuoteChar(method)[0]; } return ProviderInfo.EscapeChar; } internal string QuoteChar(string method) { CheckState(method); if (!ProviderInfo.HasQuoteChar) { string quoteCharString; quoteCharString = GetInfoStringUnhandled(ODBC32.SQL_INFO.IDENTIFIER_QUOTE_CHAR); Debug.Assert((quoteCharString.Length <= 1), "Can't handle multichar quotes"); ProviderInfo.QuoteChar = (1 == quoteCharString.Length) ? quoteCharString : "\0"; } return ProviderInfo.QuoteChar; } public new OdbcTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } public new OdbcTransaction BeginTransaction(IsolationLevel isolevel) { return (OdbcTransaction)InnerConnection.BeginTransaction(isolevel); } private void RollbackDeadTransaction() { WeakReference weak = _weakTransaction; if ((null != weak) && !weak.IsAlive) { _weakTransaction = null; ConnectionHandle.CompleteTransaction(ODBC32.SQL_ROLLBACK); } } public override void ChangeDatabase(string value) { InnerConnection.ChangeDatabase(value); } internal void CheckState(string method) { ConnectionState state = InternalState; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(method, state); // MDAC 68323 } } object ICloneable.Clone() { OdbcConnection clone = new OdbcConnection(this); return clone; } internal bool ConnectionIsAlive(Exception innerException) { if (IsOpen) { if (!ProviderInfo.NoConnectionDead) { int isDead = GetConnectAttr(ODBC32.SQL_ATTR.CONNECTION_DEAD, ODBC32.HANDLER.IGNORE); if (ODBC32.SQL_CD_TRUE == isDead) { Close(); throw ADP.ConnectionIsDisabled(innerException); } } // else connection is still alive or attribute not supported return true; } return false; } public new OdbcCommand CreateCommand() { return new OdbcCommand(string.Empty, this); } internal OdbcStatementHandle CreateStatementHandle() { return new OdbcStatementHandle(ConnectionHandle); } public override void Close() { InnerConnection.CloseConnection(this, ConnectionFactory); OdbcConnectionHandle connectionHandle = _connectionHandle; if (null != connectionHandle) { _connectionHandle = null; // If there is a pending transaction, automatically rollback. WeakReference weak = _weakTransaction; if (null != weak) { _weakTransaction = null; IDisposable transaction = weak.Target as OdbcTransaction; if ((null != transaction) && weak.IsAlive) { transaction.Dispose(); } // else transaction will be rolled back when handle is disposed } connectionHandle.Dispose(); } } private void DisposeMe(bool disposing) { // MDAC 65459 } internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) { string value = ""; int cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); if (buffer.Length + 2 <= cbActual) { // 2 bytes for unicode null-termination character // retry with cbActual because original buffer was too small buffer = new byte[cbActual + 2]; retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); } if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)) { value = Encoding.Unicode.GetString(buffer, 0, Math.Min(cbActual, buffer.Length)); } else if (retcode == ODBC32.RetCode.ERROR) { string sqlstate = GetDiagSqlState(); if (("HYC00" == sqlstate) || ("HY092" == sqlstate) || ("IM001" == sqlstate)) { FlagUnsupportedConnectAttr(attribute); } // not throwing errors if not supported or other failure } } return value; } internal int GetConnectAttr(ODBC32.SQL_ATTR attribute, ODBC32.HANDLER handler) { int retval = -1; int cbActual = 0; byte[] buffer = new byte[4]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); if ((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)) { retval = BitConverter.ToInt32(buffer, 0); } else { if (retcode == ODBC32.RetCode.ERROR) { string sqlstate = GetDiagSqlState(); if (("HYC00" == sqlstate) || ("HY092" == sqlstate) || ("IM001" == sqlstate)) { FlagUnsupportedConnectAttr(attribute); } } if (handler == ODBC32.HANDLER.THROW) { this.HandleError(connectionHandle, retcode); } } } return retval; } private string GetDiagSqlState() { OdbcConnectionHandle connectionHandle = ConnectionHandle; string sqlstate; connectionHandle.GetDiagnosticField(out sqlstate); return sqlstate; } internal ODBC32.RetCode GetInfoInt16Unhandled(ODBC32.SQL_INFO info, out short resultValue) { byte[] buffer = new byte[2]; ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); resultValue = BitConverter.ToInt16(buffer, 0); return retcode; } internal ODBC32.RetCode GetInfoInt32Unhandled(ODBC32.SQL_INFO info, out int resultValue) { byte[] buffer = new byte[4]; ODBC32.RetCode retcode = ConnectionHandle.GetInfo1(info, buffer); resultValue = BitConverter.ToInt32(buffer, 0); return retcode; } private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) { byte[] buffer = new byte[4]; ConnectionHandle.GetInfo1(infotype, buffer); return BitConverter.ToInt32(buffer, 0); } internal string GetInfoStringUnhandled(ODBC32.SQL_INFO info) { return GetInfoStringUnhandled(info, false); } private string GetInfoStringUnhandled(ODBC32.SQL_INFO info, bool handleError) { //SQLGetInfo string value = null; short cbActual = 0; byte[] buffer = new byte[100]; OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { ODBC32.RetCode retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); if (buffer.Length < cbActual - 2) { // 2 bytes for unicode null-termination character // retry with cbActual because original buffer was too small buffer = new byte[cbActual + 2]; retcode = connectionHandle.GetInfo2(info, buffer, out cbActual); } if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO) { value = Encoding.Unicode.GetString(buffer, 0, Math.Min(cbActual, buffer.Length)); } else if (handleError) { this.HandleError(ConnectionHandle, retcode); } } else if (handleError) { value = ""; } return value; } // non-throwing HandleError internal Exception HandleErrorNoThrow(OdbcHandle hrHandle, ODBC32.RetCode retcode) { Debug.Assert(retcode != ODBC32.RetCode.INVALID_HANDLE, "retcode must never be ODBC32.RetCode.INVALID_HANDLE"); switch (retcode) { case ODBC32.RetCode.SUCCESS: break; case ODBC32.RetCode.SUCCESS_WITH_INFO: { //Optimize to only create the event objects and obtain error info if //the user is really interested in retriveing the events... if (_infoMessageEventHandler != null) { OdbcErrorCollection errors = ODBC32.GetDiagErrors(null, hrHandle, retcode); errors.SetSource(this.Driver); OnInfoMessage(new OdbcInfoMessageEventArgs(errors)); } break; } default: OdbcException e = OdbcException.CreateException(ODBC32.GetDiagErrors(null, hrHandle, retcode), retcode); if (e != null) { e.Errors.SetSource(this.Driver); } ConnectionIsAlive(e); // this will close and throw if the connection is dead return (Exception)e; } return null; } internal void HandleError(OdbcHandle hrHandle, ODBC32.RetCode retcode) { Exception e = HandleErrorNoThrow(hrHandle, retcode); switch (retcode) { case ODBC32.RetCode.SUCCESS: case ODBC32.RetCode.SUCCESS_WITH_INFO: Debug.Assert(null == e, "success exception"); break; default: Debug.Assert(null != e, "failure without exception"); throw e; } } public override void Open() { try { InnerConnection.OpenConnection(this, ConnectionFactory); } catch (DllNotFoundException e) when (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new DllNotFoundException(SR.Odbc_UnixOdbcNotFound + Environment.NewLine + e.Message); } // SQLBUDT #276132 - need to manually enlist in some cases, because // native ODBC doesn't know about SysTx transactions. if (ADP.NeedManualEnlistment()) { EnlistTransaction(SysTx.Transaction.Current); } } private void OnInfoMessage(OdbcInfoMessageEventArgs args) { if (null != _infoMessageEventHandler) { try { _infoMessageEventHandler(this, args); } catch (Exception e) { // if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } public static void ReleaseObjectPool() { OdbcEnvironment.ReleaseObjectPool(); } internal OdbcTransaction SetStateExecuting(string method, OdbcTransaction transaction) { // MDAC 69003 if (null != _weakTransaction) { // transaction may exist OdbcTransaction weak = (_weakTransaction.Target as OdbcTransaction); if (transaction != weak) { // transaction doesn't exist if (null == transaction) { // transaction exists throw ADP.TransactionRequired(method); } if (this != transaction.Connection) { // transaction can't have come from this connection throw ADP.TransactionConnectionMismatch(); } // if transaction is zombied, we don't know the original connection transaction = null; // MDAC 69264 } } else if (null != transaction) { // no transaction started if (null != transaction.Connection) { // transaction can't have come from this connection throw ADP.TransactionConnectionMismatch(); } // if transaction is zombied, we don't know the original connection transaction = null; // MDAC 69264 } ConnectionState state = InternalState; if (ConnectionState.Open != state) { NotifyWeakReference(OdbcReferenceCollection.Recover); // recover for a potentially finalized reader state = InternalState; if (ConnectionState.Open != state) { if (0 != (ConnectionState.Fetching & state)) { throw ADP.OpenReaderExists(); } throw ADP.OpenConnectionRequired(method, state); } } return transaction; } // This adds a type to the list of types that are supported by the driver // (don't need to know that for all the types) // internal void SetSupportedType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.WCHAR: { sqlcvt = ODBC32.SQL_CVT.WCHAR; break; } case ODBC32.SQL_TYPE.WVARCHAR: { sqlcvt = ODBC32.SQL_CVT.WVARCHAR; break; } case ODBC32.SQL_TYPE.WLONGVARCHAR: { sqlcvt = ODBC32.SQL_CVT.WLONGVARCHAR; break; } default: // other types are irrelevant at this time return; } ProviderInfo.TestedSQLTypes |= (int)sqlcvt; ProviderInfo.SupportedSQLTypes |= (int)sqlcvt; } internal void FlagRestrictedSqlBindType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.DECIMAL: { sqlcvt = ODBC32.SQL_CVT.DECIMAL; break; } default: // other types are irrelevant at this time return; } ProviderInfo.RestrictedSQLBindTypes |= (int)sqlcvt; } internal void FlagUnsupportedConnectAttr(ODBC32.SQL_ATTR Attribute) { switch (Attribute) { case ODBC32.SQL_ATTR.CURRENT_CATALOG: ProviderInfo.NoCurrentCatalog = true; break; case ODBC32.SQL_ATTR.CONNECTION_DEAD: ProviderInfo.NoConnectionDead = true; break; default: Debug.Assert(false, "Can't flag unknown Attribute"); break; } } internal void FlagUnsupportedStmtAttr(ODBC32.SQL_ATTR Attribute) { switch (Attribute) { case ODBC32.SQL_ATTR.QUERY_TIMEOUT: ProviderInfo.NoQueryTimeout = true; break; case (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE: ProviderInfo.NoSqlSoptSSNoBrowseTable = true; break; case (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS: ProviderInfo.NoSqlSoptSSHiddenColumns = true; break; default: Debug.Assert(false, "Can't flag unknown Attribute"); break; } } internal void FlagUnsupportedColAttr(ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId) { if (IsV3Driver) { switch (v3FieldId) { case (ODBC32.SQL_DESC)ODBC32.SQL_CA_SS.COLUMN_KEY: // SSS_WARNINGS_OFF ProviderInfo.NoSqlCASSColumnKey = true; break; // SSS_WARNINGS_ON default: Debug.Assert(false, "Can't flag unknown Attribute"); break; } } else { switch (v2FieldId) { default: Debug.Assert(false, "Can't flag unknown Attribute"); break; } } } internal bool SQLGetFunctions(ODBC32.SQL_API odbcFunction) { //SQLGetFunctions ODBC32.RetCode retcode; short fExists; Debug.Assert((short)odbcFunction != 0, "SQL_API_ALL_FUNCTIONS is not supported"); OdbcConnectionHandle connectionHandle = ConnectionHandle; if (null != connectionHandle) { retcode = connectionHandle.GetFunctions(odbcFunction, out fExists); } else { Debug.Assert(false, "GetFunctions called and ConnectionHandle is null (connection is disposed?)"); throw ODBC.ConnectionClosed(); } if (retcode != ODBC32.RetCode.SUCCESS) this.HandleError(connectionHandle, retcode); if (fExists == 0) { return false; } else { return true; } } internal bool TestTypeSupport(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CONVERT sqlconvert; ODBC32.SQL_CVT sqlcvt; // we need to convert the sqltype to sqlconvert and sqlcvt first // switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlconvert = ODBC32.SQL_CONVERT.NUMERIC; sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.WCHAR: { sqlconvert = ODBC32.SQL_CONVERT.CHAR; sqlcvt = ODBC32.SQL_CVT.WCHAR; break; } case ODBC32.SQL_TYPE.WVARCHAR: { sqlconvert = ODBC32.SQL_CONVERT.VARCHAR; sqlcvt = ODBC32.SQL_CVT.WVARCHAR; break; } case ODBC32.SQL_TYPE.WLONGVARCHAR: { sqlconvert = ODBC32.SQL_CONVERT.LONGVARCHAR; sqlcvt = ODBC32.SQL_CVT.WLONGVARCHAR; break; } default: Debug.Assert(false, "Testing that sqltype is currently not supported"); return false; } // now we can check if we have already tested that type // if not we need to do so if (0 == (ProviderInfo.TestedSQLTypes & (int)sqlcvt)) { int flags; flags = GetInfoInt32Unhandled((ODBC32.SQL_INFO)sqlconvert); flags = flags & (int)sqlcvt; ProviderInfo.TestedSQLTypes |= (int)sqlcvt; ProviderInfo.SupportedSQLTypes |= flags; } // now check if the type is supported and return the result // return (0 != (ProviderInfo.SupportedSQLTypes & (int)sqlcvt)); } internal bool TestRestrictedSqlBindType(ODBC32.SQL_TYPE sqltype) { ODBC32.SQL_CVT sqlcvt; switch (sqltype) { case ODBC32.SQL_TYPE.NUMERIC: { sqlcvt = ODBC32.SQL_CVT.NUMERIC; break; } case ODBC32.SQL_TYPE.DECIMAL: { sqlcvt = ODBC32.SQL_CVT.DECIMAL; break; } default: Debug.Assert(false, "Testing that sqltype is currently not supported"); return false; } return (0 != (ProviderInfo.RestrictedSQLBindTypes & (int)sqlcvt)); } // suppress this message - we cannot use SafeHandle here. Also, see notes in the code (VSTFDEVDIV# 560355) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel); // VSTFDEVDIV# 560355 - InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } internal OdbcTransaction Open_BeginTransaction(IsolationLevel isolevel) { CheckState(ADP.BeginTransaction); // MDAC 68323 RollbackDeadTransaction(); if ((null != _weakTransaction) && _weakTransaction.IsAlive) { // regression from Dispose/Finalize work throw ADP.ParallelTransactionsNotSupported(this); } //Use the default for unspecified. switch (isolevel) { case IsolationLevel.Unspecified: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: break; case IsolationLevel.Chaos: throw ODBC.NotSupportedIsolationLevel(isolevel); default: throw ADP.InvalidIsolationLevel(isolevel); }; //Start the transaction OdbcConnectionHandle connectionHandle = ConnectionHandle; ODBC32.RetCode retcode = connectionHandle.BeginTransaction(ref isolevel); if (retcode == ODBC32.RetCode.ERROR) { HandleError(connectionHandle, retcode); } OdbcTransaction transaction = new OdbcTransaction(this, isolevel, connectionHandle); _weakTransaction = new WeakReference(transaction); // MDAC 69188 return transaction; } internal void Open_ChangeDatabase(string value) { CheckState(ADP.ChangeDatabase); // Database name must not be null, empty or whitspace if ((null == value) || (0 == value.Trim().Length)) { // MDAC 62679 throw ADP.EmptyDatabaseName(); } if (1024 < value.Length * 2 + 2) { throw ADP.DatabaseNameTooLong(); } RollbackDeadTransaction(); //Set the database OdbcConnectionHandle connectionHandle = ConnectionHandle; ODBC32.RetCode retcode = connectionHandle.SetConnectionAttribute3(ODBC32.SQL_ATTR.CURRENT_CATALOG, value, checked((int)value.Length * 2)); if (retcode != ODBC32.RetCode.SUCCESS) { HandleError(connectionHandle, retcode); } } internal string Open_GetServerVersion() { //SQLGetInfo - SQL_DBMS_VER return GetInfoStringUnhandled(ODBC32.SQL_INFO.DBMS_VER, true); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Language.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedLanguageServiceClientTest { [xunit::FactAttribute] public void AnalyzeSentimentRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse response = client.AnalyzeSentiment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeSentimentRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeSentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse responseCallSettings = await client.AnalyzeSentimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeSentimentResponse responseCancellationToken = await client.AnalyzeSentimentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeSentiment1() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse response = client.AnalyzeSentiment(request.Document, request.EncodingType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeSentiment1Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeSentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse responseCallSettings = await client.AnalyzeSentimentAsync(request.Document, request.EncodingType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeSentimentResponse responseCancellationToken = await client.AnalyzeSentimentAsync(request.Document, request.EncodingType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeSentiment2() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse response = client.AnalyzeSentiment(request.Document); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeSentiment2Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), }; AnalyzeSentimentResponse expectedResponse = new AnalyzeSentimentResponse { DocumentSentiment = new Sentiment(), Language = "language7dae1285", Sentences = { new Sentence(), }, }; mockGrpcClient.Setup(x => x.AnalyzeSentimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeSentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSentimentResponse responseCallSettings = await client.AnalyzeSentimentAsync(request.Document, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeSentimentResponse responseCancellationToken = await client.AnalyzeSentimentAsync(request.Document, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeEntitiesRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitiesResponse expectedResponse = new AnalyzeEntitiesResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntities(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitiesResponse response = client.AnalyzeEntities(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeEntitiesRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitiesResponse expectedResponse = new AnalyzeEntitiesResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitiesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeEntitiesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitiesResponse responseCallSettings = await client.AnalyzeEntitiesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeEntitiesResponse responseCancellationToken = await client.AnalyzeEntitiesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeEntities1() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitiesResponse expectedResponse = new AnalyzeEntitiesResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntities(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitiesResponse response = client.AnalyzeEntities(request.Document, request.EncodingType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeEntities1Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitiesResponse expectedResponse = new AnalyzeEntitiesResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitiesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeEntitiesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitiesResponse responseCallSettings = await client.AnalyzeEntitiesAsync(request.Document, request.EncodingType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeEntitiesResponse responseCancellationToken = await client.AnalyzeEntitiesAsync(request.Document, request.EncodingType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeEntitySentimentRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitySentimentResponse expectedResponse = new AnalyzeEntitySentimentResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitySentiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitySentimentResponse response = client.AnalyzeEntitySentiment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeEntitySentimentRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitySentimentResponse expectedResponse = new AnalyzeEntitySentimentResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitySentimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeEntitySentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitySentimentResponse responseCallSettings = await client.AnalyzeEntitySentimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeEntitySentimentResponse responseCancellationToken = await client.AnalyzeEntitySentimentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeEntitySentiment1() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitySentimentResponse expectedResponse = new AnalyzeEntitySentimentResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitySentiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitySentimentResponse response = client.AnalyzeEntitySentiment(request.Document, request.EncodingType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeEntitySentiment1Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeEntitySentimentResponse expectedResponse = new AnalyzeEntitySentimentResponse { Entities = { new Entity(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeEntitySentimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeEntitySentimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeEntitySentimentResponse responseCallSettings = await client.AnalyzeEntitySentimentAsync(request.Document, request.EncodingType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeEntitySentimentResponse responseCancellationToken = await client.AnalyzeEntitySentimentAsync(request.Document, request.EncodingType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeSyntaxRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSyntaxResponse expectedResponse = new AnalyzeSyntaxResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeSyntax(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSyntaxResponse response = client.AnalyzeSyntax(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeSyntaxRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSyntaxResponse expectedResponse = new AnalyzeSyntaxResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeSyntaxAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeSyntaxResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSyntaxResponse responseCallSettings = await client.AnalyzeSyntaxAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeSyntaxResponse responseCancellationToken = await client.AnalyzeSyntaxAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnalyzeSyntax1() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSyntaxResponse expectedResponse = new AnalyzeSyntaxResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeSyntax(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSyntaxResponse response = client.AnalyzeSyntax(request.Document, request.EncodingType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnalyzeSyntax1Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), EncodingType = EncodingType.None, }; AnalyzeSyntaxResponse expectedResponse = new AnalyzeSyntaxResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Language = "language7dae1285", }; mockGrpcClient.Setup(x => x.AnalyzeSyntaxAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnalyzeSyntaxResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnalyzeSyntaxResponse responseCallSettings = await client.AnalyzeSyntaxAsync(request.Document, request.EncodingType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnalyzeSyntaxResponse responseCancellationToken = await client.AnalyzeSyntaxAsync(request.Document, request.EncodingType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ClassifyTextRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; ClassifyTextResponse expectedResponse = new ClassifyTextResponse { Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.ClassifyText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); ClassifyTextResponse response = client.ClassifyText(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ClassifyTextRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; ClassifyTextResponse expectedResponse = new ClassifyTextResponse { Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.ClassifyTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClassifyTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); ClassifyTextResponse responseCallSettings = await client.ClassifyTextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ClassifyTextResponse responseCancellationToken = await client.ClassifyTextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ClassifyText() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; ClassifyTextResponse expectedResponse = new ClassifyTextResponse { Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.ClassifyText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); ClassifyTextResponse response = client.ClassifyText(request.Document); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ClassifyTextAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; ClassifyTextResponse expectedResponse = new ClassifyTextResponse { Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.ClassifyTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClassifyTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); ClassifyTextResponse responseCallSettings = await client.ClassifyTextAsync(request.Document, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ClassifyTextResponse responseCancellationToken = await client.ClassifyTextAsync(request.Document, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnnotateTextRequestObject() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), EncodingType = EncodingType.None, }; AnnotateTextResponse expectedResponse = new AnnotateTextResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Entities = { new Entity(), }, DocumentSentiment = new Sentiment(), Language = "language7dae1285", Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.AnnotateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnnotateTextResponse response = client.AnnotateText(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnnotateTextRequestObjectAsync() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), EncodingType = EncodingType.None, }; AnnotateTextResponse expectedResponse = new AnnotateTextResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Entities = { new Entity(), }, DocumentSentiment = new Sentiment(), Language = "language7dae1285", Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.AnnotateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnnotateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnnotateTextResponse responseCallSettings = await client.AnnotateTextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnnotateTextResponse responseCancellationToken = await client.AnnotateTextAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void AnnotateText1() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), EncodingType = EncodingType.None, }; AnnotateTextResponse expectedResponse = new AnnotateTextResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Entities = { new Entity(), }, DocumentSentiment = new Sentiment(), Language = "language7dae1285", Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.AnnotateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnnotateTextResponse response = client.AnnotateText(request.Document, request.Features, request.EncodingType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task AnnotateText1Async() { moq::Mock<LanguageService.LanguageServiceClient> mockGrpcClient = new moq::Mock<LanguageService.LanguageServiceClient>(moq::MockBehavior.Strict); AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), EncodingType = EncodingType.None, }; AnnotateTextResponse expectedResponse = new AnnotateTextResponse { Sentences = { new Sentence(), }, Tokens = { new Token(), }, Entities = { new Entity(), }, DocumentSentiment = new Sentiment(), Language = "language7dae1285", Categories = { new ClassificationCategory(), }, }; mockGrpcClient.Setup(x => x.AnnotateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AnnotateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LanguageServiceClient client = new LanguageServiceClientImpl(mockGrpcClient.Object, null); AnnotateTextResponse responseCallSettings = await client.AnnotateTextAsync(request.Document, request.Features, request.EncodingType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AnnotateTextResponse responseCancellationToken = await client.AnnotateTextAsync(request.Document, request.Features, request.EncodingType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections.Generic; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class MNMessagesSyncDeltaMarkUnread : TBase { private List<MNMessagesSyncThreadKey> _ThreadKeys; private List<int> _Folders; private long _WatermarkTimestamp; private long _ActionTimestamp; public List<MNMessagesSyncThreadKey> ThreadKeys { get { return _ThreadKeys; } set { __isset.ThreadKeys = true; this._ThreadKeys = value; } } public List<int> Folders { get { return _Folders; } set { __isset.Folders = true; this._Folders = value; } } public long WatermarkTimestamp { get { return _WatermarkTimestamp; } set { __isset.WatermarkTimestamp = true; this._WatermarkTimestamp = value; } } public long ActionTimestamp { get { return _ActionTimestamp; } set { __isset.ActionTimestamp = true; this._ActionTimestamp = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool ThreadKeys; public bool Folders; public bool WatermarkTimestamp; public bool ActionTimestamp; } public MNMessagesSyncDeltaMarkUnread() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.List) { { ThreadKeys = new List<MNMessagesSyncThreadKey>(); TList _list47 = iprot.ReadListBegin(); for( int _i48 = 0; _i48 < _list47.Count; ++_i48) { MNMessagesSyncThreadKey _elem49; _elem49 = new MNMessagesSyncThreadKey(); _elem49.Read(iprot); ThreadKeys.Add(_elem49); } iprot.ReadListEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.List) { { Folders = new List<int>(); TList _list50 = iprot.ReadListBegin(); for( int _i51 = 0; _i51 < _list50.Count; ++_i51) { int _elem52; _elem52 = iprot.ReadI32(); Folders.Add(_elem52); } iprot.ReadListEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I64) { WatermarkTimestamp = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I64) { ActionTimestamp = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("MNMessagesSyncDeltaMarkUnread"); oprot.WriteStructBegin(struc); TField field = new TField(); if (ThreadKeys != null && __isset.ThreadKeys) { field.Name = "ThreadKeys"; field.Type = TType.List; field.ID = 1; oprot.WriteFieldBegin(field); { oprot.WriteListBegin(new TList(TType.Struct, ThreadKeys.Count)); foreach (MNMessagesSyncThreadKey _iter53 in ThreadKeys) { _iter53.Write(oprot); } oprot.WriteListEnd(); } oprot.WriteFieldEnd(); } if (Folders != null && __isset.Folders) { field.Name = "Folders"; field.Type = TType.List; field.ID = 2; oprot.WriteFieldBegin(field); { oprot.WriteListBegin(new TList(TType.I32, Folders.Count)); foreach (int _iter54 in Folders) { oprot.WriteI32(_iter54); } oprot.WriteListEnd(); } oprot.WriteFieldEnd(); } if (__isset.WatermarkTimestamp) { field.Name = "WatermarkTimestamp"; field.Type = TType.I64; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI64(WatermarkTimestamp); oprot.WriteFieldEnd(); } if (__isset.ActionTimestamp) { field.Name = "ActionTimestamp"; field.Type = TType.I64; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI64(ActionTimestamp); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("MNMessagesSyncDeltaMarkUnread("); bool __first = true; if (ThreadKeys != null && __isset.ThreadKeys) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("ThreadKeys: "); __sb.Append(ThreadKeys); } if (Folders != null && __isset.Folders) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Folders: "); __sb.Append(Folders); } if (__isset.WatermarkTimestamp) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("WatermarkTimestamp: "); __sb.Append(WatermarkTimestamp); } if (__isset.ActionTimestamp) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("ActionTimestamp: "); __sb.Append(ActionTimestamp); } __sb.Append(")"); return __sb.ToString(); } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.Models { /// <summary> /// Information about the users of the system. /// </summary> [MetaDataExtension (Description = "Information about the users of the system.")] public partial class User : AuditableEntity, IEquatable<User> { /// <summary> /// Default constructor, required by entity framework /// </summary> public User() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="User" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a User (required).</param> /// <param name="GivenName">Given name of the user. (required).</param> /// <param name="Surname">Surname of the user. (required).</param> /// <param name="Active">A flag indicating the User is active in the system. Set false to remove access to the system for the user. (required).</param> /// <param name="Initials">Initials of the user, to be presented where screen space is at a premium..</param> /// <param name="Email">The email address of the user in the system..</param> /// <param name="SmUserId">Security Manager User ID.</param> /// <param name="Guid">The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled..</param> /// <param name="SmAuthorizationDirectory">The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID..</param> /// <param name="UserRoles">UserRoles.</param> /// <param name="GroupMemberships">GroupMemberships.</param> /// <param name="District">The District that the User belongs to.</param> public User(int Id, string GivenName, string Surname, bool Active, string Initials = null, string Email = null, string SmUserId = null, string Guid = null, string SmAuthorizationDirectory = null, List<UserRole> UserRoles = null, List<GroupMembership> GroupMemberships = null, District District = null) { this.Id = Id; this.GivenName = GivenName; this.Surname = Surname; this.Active = Active; this.Initials = Initials; this.Email = Email; this.SmUserId = SmUserId; this.Guid = Guid; this.SmAuthorizationDirectory = SmAuthorizationDirectory; this.UserRoles = UserRoles; this.GroupMemberships = GroupMemberships; this.District = District; } /// <summary> /// A system-generated unique identifier for a User /// </summary> /// <value>A system-generated unique identifier for a User</value> [MetaDataExtension (Description = "A system-generated unique identifier for a User")] public int Id { get; set; } /// <summary> /// Given name of the user. /// </summary> /// <value>Given name of the user.</value> [MetaDataExtension (Description = "Given name of the user.")] [MaxLength(255)] public string GivenName { get; set; } /// <summary> /// Surname of the user. /// </summary> /// <value>Surname of the user.</value> [MetaDataExtension (Description = "Surname of the user.")] [MaxLength(50)] public string Surname { get; set; } /// <summary> /// A flag indicating the User is active in the system. Set false to remove access to the system for the user. /// </summary> /// <value>A flag indicating the User is active in the system. Set false to remove access to the system for the user.</value> [MetaDataExtension (Description = "A flag indicating the User is active in the system. Set false to remove access to the system for the user.")] public bool Active { get; set; } /// <summary> /// Initials of the user, to be presented where screen space is at a premium. /// </summary> /// <value>Initials of the user, to be presented where screen space is at a premium.</value> [MetaDataExtension (Description = "Initials of the user, to be presented where screen space is at a premium.")] [MaxLength(10)] public string Initials { get; set; } /// <summary> /// The email address of the user in the system. /// </summary> /// <value>The email address of the user in the system.</value> [MetaDataExtension (Description = "The email address of the user in the system.")] [MaxLength(255)] public string Email { get; set; } /// <summary> /// Security Manager User ID /// </summary> /// <value>Security Manager User ID</value> [MetaDataExtension (Description = "Security Manager User ID")] [MaxLength(255)] public string SmUserId { get; set; } /// <summary> /// The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled. /// </summary> /// <value>The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled.</value> [MetaDataExtension (Description = "The GUID unique to the user as provided by the authentication system. In this case, authentication is done by Siteminder and the GUID uniquely identifies the user within the user directories managed by Siteminder - e.g. IDIR and BCeID. The GUID is equivalent to the IDIR Id, but is guaranteed unique to a person, while the IDIR ID is not - IDIR IDs can be recycled.")] [MaxLength(255)] public string Guid { get; set; } /// <summary> /// The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID. /// </summary> /// <value>The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID.</value> [MetaDataExtension (Description = "The user directory service used by Siteminder to authenticate the user - usually IDIR or BCeID.")] [MaxLength(255)] public string SmAuthorizationDirectory { get; set; } /// <summary> /// Gets or Sets UserRoles /// </summary> public List<UserRole> UserRoles { get; set; } /// <summary> /// Gets or Sets GroupMemberships /// </summary> public List<GroupMembership> GroupMemberships { get; set; } /// <summary> /// The District that the User belongs to /// </summary> /// <value>The District that the User belongs to</value> [MetaDataExtension (Description = "The District that the User belongs to")] public District District { get; set; } /// <summary> /// Foreign key for District /// </summary> [ForeignKey("District")] [JsonIgnore] [MetaDataExtension (Description = "The District that the User belongs to")] public int? DistrictId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" GivenName: ").Append(GivenName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" Initials: ").Append(Initials).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" SmUserId: ").Append(SmUserId).Append("\n"); sb.Append(" Guid: ").Append(Guid).Append("\n"); sb.Append(" SmAuthorizationDirectory: ").Append(SmAuthorizationDirectory).Append("\n"); sb.Append(" UserRoles: ").Append(UserRoles).Append("\n"); sb.Append(" GroupMemberships: ").Append(GroupMemberships).Append("\n"); sb.Append(" District: ").Append(District).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((User)obj); } /// <summary> /// Returns true if User instances are equal /// </summary> /// <param name="other">Instance of User to be compared</param> /// <returns>Boolean</returns> public bool Equals(User other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.GivenName == other.GivenName || this.GivenName != null && this.GivenName.Equals(other.GivenName) ) && ( this.Surname == other.Surname || this.Surname != null && this.Surname.Equals(other.Surname) ) && ( this.Active == other.Active || this.Active.Equals(other.Active) ) && ( this.Initials == other.Initials || this.Initials != null && this.Initials.Equals(other.Initials) ) && ( this.Email == other.Email || this.Email != null && this.Email.Equals(other.Email) ) && ( this.SmUserId == other.SmUserId || this.SmUserId != null && this.SmUserId.Equals(other.SmUserId) ) && ( this.Guid == other.Guid || this.Guid != null && this.Guid.Equals(other.Guid) ) && ( this.SmAuthorizationDirectory == other.SmAuthorizationDirectory || this.SmAuthorizationDirectory != null && this.SmAuthorizationDirectory.Equals(other.SmAuthorizationDirectory) ) && ( this.UserRoles == other.UserRoles || this.UserRoles != null && this.UserRoles.SequenceEqual(other.UserRoles) ) && ( this.GroupMemberships == other.GroupMemberships || this.GroupMemberships != null && this.GroupMemberships.SequenceEqual(other.GroupMemberships) ) && ( this.District == other.District || this.District != null && this.District.Equals(other.District) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.GivenName != null) { hash = hash * 59 + this.GivenName.GetHashCode(); } if (this.Surname != null) { hash = hash * 59 + this.Surname.GetHashCode(); } hash = hash * 59 + this.Active.GetHashCode(); if (this.Initials != null) { hash = hash * 59 + this.Initials.GetHashCode(); } if (this.Email != null) { hash = hash * 59 + this.Email.GetHashCode(); } if (this.SmUserId != null) { hash = hash * 59 + this.SmUserId.GetHashCode(); } if (this.Guid != null) { hash = hash * 59 + this.Guid.GetHashCode(); } if (this.SmAuthorizationDirectory != null) { hash = hash * 59 + this.SmAuthorizationDirectory.GetHashCode(); } if (this.UserRoles != null) { hash = hash * 59 + this.UserRoles.GetHashCode(); } if (this.GroupMemberships != null) { hash = hash * 59 + this.GroupMemberships.GetHashCode(); } if (this.District != null) { hash = hash * 59 + this.District.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(User left, User right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(User left, User right) { return !Equals(left, right); } #endregion Operators } }
/* * Project: WhaTBI? (What's The Big Idea?) * Filename: Utility.cs * Description: Various utilities */ using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Xml.Serialization; namespace Pdbartlett.Whatbi { namespace Custom { public interface IGetReadOnly { Object GetReadOnly(); } public interface IGetKey { Object GetKey(); } } public class BaseException : Exception { public BaseException(string message) : base(message) {} } #if FX_V20 public static class Utility #else public class Utility #endif { public static Object GetReadOnly(Object o) { if (o == null) return null; Custom.IGetReadOnly custom = o as Custom.IGetReadOnly; if (custom != null) return custom.GetReadOnly(); ICollection coll = o as ICollection; if (coll != null) { ArrayList list = new ArrayList(coll.Count); foreach (object item in coll) list.Add(GetReadOnly(item)); return list; } ICloneable cloneable = o as ICloneable; if (cloneable != null) return cloneable.Clone(); if (o is ValueType) return o; throw new BaseException("Cannot generate read-only copy of object"); } public static Object GetKey(Object o) { Custom.IGetKey custom = o as Custom.IGetKey; if (custom != null) return custom.GetKey(); throw new BaseException("Cannot determine key for object"); } public static ITypeInfo GetTypeInfo(Type t) { return new TypeToTypeInfoAdapter(t); } public static ITypeInfo GetTypeInfo(Object o) { Custom.IGetTypeInfo custom = o as Custom.IGetTypeInfo; if (custom != null) return custom.GetTypeInfo(); return new ObjectToTypeInfoAdapter(o); } public static IPropertyInfo[] GetProperties(Object o) { ITypeInfo ti = GetTypeInfo(o); return ti.GetProperties(); } public static object ConvertTo(object o, ITypeInfo dest) { ITypeInfo src = GetTypeInfo(o); return src.ConvertTo(o, dest); } public static bool TryParseDouble(string s, out double d) { return Double.TryParse(s, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out d); } public static bool TryParseInt32(string s, out int i) { #if FX_V20 return Int32.TryParse(s, out i); #else double d; if (Double.TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out d)) { try { i = Int32.Parse(s); return true; } catch (Exception) {} } i = 0; return false; #endif } public static bool TryParseDateTime(string s, out DateTime dt) { // !!! Potential performance issue - exceptions thrown in "mainstream" case !!! try { dt = DateTime.Parse(s); return true; } catch (Exception) { dt = DateTime.Now; return false; } } public static IList MakeList(ICollection coll) { IList list = coll as IList; if (list == null) list = new ArrayList(coll); return list; } public static ArrayList MakeArrayList(ICollection coll) { ArrayList list = coll as ArrayList; if (list == null) list = new ArrayList(coll); return list; } } #if FX_V20 public static class XmlUtility #else public class XmlUtility #endif { public static void SerializeObjectToFile(object data, string fileName) { SerializeObjectToFile(data, data.GetType(), null, fileName); } public static void SerializeObjectToFile(object data, Type type, string fileName) { SerializeObjectToFile(data, type, null, fileName); } public static void SerializeObjectToFile(object data, Type type, Type[] extraTypes, string fileName) { using (TextWriter writer = new StreamWriter(fileName)) { SerializeObject(data, type, extraTypes, writer); } } public static void SerializeObject(object data, Type type, Type[] extraTypes, TextWriter writer) { GetXmlSerializer(type, extraTypes).Serialize(writer, data); } public static object DeserializeObjectFromFile(Type type, string fileName) { return DeserializeObjectFromFile(type, null, fileName); } public static object DeserializeObjectFromFile(Type type, Type[] extraTypes, string fileName) { using (TextReader reader = new StreamReader(fileName)) { return DeserializeObject(type, extraTypes, reader); } } public static object DeserializeObject(Type type, Type[] extraTypes, TextReader reader) { return GetXmlSerializer(type, extraTypes).Deserialize(reader); } private static XmlSerializer GetXmlSerializer(Type type, Type[] extraTypes) { if (extraTypes == null) return new XmlSerializer(type); return new XmlSerializer(type, extraTypes); } } }
using System; using System.Drawing; using TweetLib.Browser.Base; using TweetLib.Browser.Contexts; using TweetLib.Browser.Events; using TweetLib.Browser.Interfaces; using TweetLib.Browser.Request; using TweetLib.Core.Features.Notifications; using TweetLib.Core.Features.Plugins; using TweetLib.Core.Features.Plugins.Enums; using TweetLib.Core.Features.Plugins.Events; using TweetLib.Core.Features.Twitter; using TweetLib.Core.Resources; using TweetLib.Core.Systems.Updates; using TweetLib.Utils.Static; using Version = TweetDuck.Version; namespace TweetLib.Core.Features.TweetDeck { public sealed class TweetDeckBrowser : BaseBrowser<TweetDeckBrowser> { public static readonly Color BackgroundColor = Color.FromArgb(28, 99, 153); private const string NamespaceTweetDeck = "tweetdeck"; private const string BackgroundColorOverride = "setTimeout(function f(){let h=document.head;if(!h){setTimeout(f,5);return;}let e=document.createElement('style');e.innerHTML='body,body::before{background:#1c6399!important;margin:0}';h.appendChild(e);},1)"; public TweetDeckFunctions Functions { get; } public FileDownloadManager FileDownloadManager => new (browserComponent); private readonly ISoundNotificationHandler soundNotificationHandler; private readonly PluginManager pluginManager; private bool isBrowserReady; private bool ignoreUpdateCheckError; private string? prevSoundNotificationPath = null; public TweetDeckBrowser(IBrowserComponent browserComponent, ITweetDeckInterface tweetDeckInterface, TweetDeckExtraContext extraContext, ISoundNotificationHandler soundNotificationHandler, PluginManager pluginManager, UpdateChecker? updateChecker = null) : base(browserComponent, CreateSetupObject) { this.Functions = new TweetDeckFunctions(this.browserComponent); this.soundNotificationHandler = soundNotificationHandler; this.pluginManager = pluginManager; this.pluginManager.Register(PluginEnvironment.Browser, this.browserComponent); this.pluginManager.Reloaded += pluginManager_Reloaded; this.pluginManager.Executed += pluginManager_Executed; this.pluginManager.Reload(); this.browserComponent.BrowserLoaded += browserComponent_BrowserLoaded; this.browserComponent.PageLoadStart += browserComponent_PageLoadStart; this.browserComponent.PageLoadEnd += browserComponent_PageLoadEnd; this.browserComponent.AttachBridgeObject("$TD", new TweetDeckBridgeObject(tweetDeckInterface, this, extraContext)); if (updateChecker != null) { updateChecker.CheckFinished += updateChecker_CheckFinished; this.browserComponent.AttachBridgeObject("$TDU", updateChecker.InteractionManager.BridgeObject); } App.UserConfiguration.MuteToggled += UserConfiguration_GeneralEventHandler; App.UserConfiguration.OptionsDialogClosed += UserConfiguration_GeneralEventHandler; App.UserConfiguration.SoundNotificationChanged += UserConfiguration_SoundNotificationChanged; } public override void Dispose() { base.Dispose(); this.browserComponent.BrowserLoaded -= browserComponent_BrowserLoaded; this.browserComponent.PageLoadStart -= browserComponent_PageLoadStart; this.browserComponent.PageLoadEnd -= browserComponent_PageLoadEnd; App.UserConfiguration.MuteToggled -= UserConfiguration_GeneralEventHandler; App.UserConfiguration.OptionsDialogClosed -= UserConfiguration_GeneralEventHandler; App.UserConfiguration.SoundNotificationChanged -= UserConfiguration_SoundNotificationChanged; } private void browserComponent_BrowserLoaded(object sender, BrowserLoadedEventArgs e) { e.AddDictionaryWords("tweetdeck", "TweetDeck", "tweetduck", "TweetDuck", "TD"); isBrowserReady = true; } private void browserComponent_PageLoadStart(object sender, PageLoadEventArgs e) { string url = e.Url; if (TwitterUrls.IsTweetDeck(url) || (TwitterUrls.IsTwitter(url) && !TwitterUrls.IsTwitterLogin2Factor(url))) { browserComponent.RunScript("gen:backgroundcolor", BackgroundColorOverride); } } private void browserComponent_PageLoadEnd(object sender, PageLoadEventArgs e) { string url = e.Url; if (TwitterUrls.IsTweetDeck(url)) { NotificationBrowser.SetNotificationLayout(null, null); UpdatePropertyObject(); browserComponent.RunBootstrap(NamespaceTweetDeck); pluginManager.Execute(PluginEnvironment.Browser, browserComponent); if (App.UserConfiguration.FirstRun) { browserComponent.RunBootstrap("introduction"); } } else if (TwitterUrls.IsTwitter(url)) { browserComponent.RunBootstrap("login"); } browserComponent.RunBootstrap("update"); } private void pluginManager_Reloaded(object sender, PluginErrorEventArgs e) { if (e.HasErrors) { App.MessageDialogs.Error("Error Loading Plugins", "The following plugins will not be available until the issues are resolved:\n\n" + string.Join("\n\n", e.Errors)); } if (isBrowserReady) { ReloadToTweetDeck(); } } private void pluginManager_Executed(object sender, PluginErrorEventArgs e) { if (e.HasErrors) { App.MessageDialogs.Error("Error Executing Plugins", "Failed to execute the following plugins:\n\n" + string.Join("\n\n", e.Errors)); } } private void updateChecker_CheckFinished(object sender, UpdateCheckEventArgs e) { var updateChecker = (UpdateChecker) sender; e.Result.Handle(update => { string tag = update.VersionTag; if (tag != Version.Tag && tag != App.UserConfiguration.DismissedUpdate) { update.BeginSilentDownload(); Functions.ShowUpdateNotification(tag, update.ReleaseNotes); } else { updateChecker.StartTimer(); } }, ex => { if (!ignoreUpdateCheckError) { App.ErrorHandler.HandleException("Update Check Error", "An error occurred while checking for updates.", true, ex); updateChecker.StartTimer(); } }); ignoreUpdateCheckError = true; } private void UserConfiguration_GeneralEventHandler(object sender, EventArgs e) { UpdatePropertyObject(); } private void UserConfiguration_SoundNotificationChanged(object? sender, EventArgs e) { const string soundUrl = "https://ton.twimg.com/tduck/updatesnd"; bool hasCustomSound = App.UserConfiguration.IsCustomSoundNotificationSet; string newNotificationPath = App.UserConfiguration.NotificationSoundPath; if (prevSoundNotificationPath != newNotificationPath) { prevSoundNotificationPath = newNotificationPath; soundNotificationHandler.Unregister(soundUrl); if (hasCustomSound) { soundNotificationHandler.Register(soundUrl, newNotificationPath); } } Functions.SetSoundNotificationData(hasCustomSound, App.UserConfiguration.NotificationSoundVolume); } internal void OnModulesLoaded(string moduleNamespace) { if (moduleNamespace == NamespaceTweetDeck) { Functions.ReinjectCustomCSS(App.UserConfiguration.CustomBrowserCSS); UserConfiguration_SoundNotificationChanged(null, EventArgs.Empty); } } private void UpdatePropertyObject() { browserComponent.RunScript("gen:propertyobj", PropertyObjectScript.Generate(App.UserConfiguration, PropertyObjectScript.Environment.Browser)); } public void ReloadToTweetDeck() { ignoreUpdateCheckError = false; browserComponent.RunScript("gen:reload", $"if(window.TDGF_reload)window.TDGF_reload();else window.location.href='{TwitterUrls.TweetDeck}'"); } private static BrowserSetup CreateSetupObject(TweetDeckBrowser browser) { return BaseBrowser.CreateSetupObject(browser.browserComponent, new BrowserSetup { ContextMenuHandler = new ContextMenu(browser), ResourceRequestHandler = new ResourceRequestHandler() }); } private sealed class ContextMenu : BaseContextMenu { private readonly TweetDeckBrowser owner; public ContextMenu(TweetDeckBrowser owner) : base(owner.browserComponent) { this.owner = owner; } public override void Show(IContextMenuBuilder menu, Context context) { if (context.Selection is { Editable: true } ) { menu.AddAction("Apply ROT13", owner.Functions.ApplyROT13); menu.AddSeparator(); } base.Show(menu, context); if (context.Selection == null && context.Tweet is {} tweet) { AddOpenAction(menu, "Open tweet in browser", tweet.Url); AddCopyAction(menu, "Copy tweet address", tweet.Url); menu.AddAction("Screenshot tweet to clipboard", () => owner.Functions.TriggerTweetScreenshot(tweet.ColumnId, tweet.ChirpId)); menu.AddSeparator(); if (!string.IsNullOrEmpty(tweet.QuoteUrl)) { AddOpenAction(menu, "Open quoted tweet in browser", tweet.QuoteUrl!); AddCopyAction(menu, "Copy quoted tweet address", tweet.QuoteUrl!); menu.AddSeparator(); } } } protected override void AddSearchSelectionItems(IContextMenuBuilder menu, string selectedText) { base.AddSearchSelectionItems(menu, selectedText); if (TwitterUrls.IsTweetDeck(owner.browserComponent.Url)) { menu.AddAction("Search in a column", () => { owner.Functions.AddSearchColumn(selectedText); DeselectAll(); }); } } } private sealed class ResourceRequestHandler : BaseResourceRequestHandler { private const string UrlLoadingSpinner = "/backgrounds/spinner_blue"; private const string UrlVendorResource = "/dist/vendor"; private const string UrlVersionCheck = "/web/dist/version.json"; public override RequestHandleResult? Handle(string url, ResourceType resourceType) { switch (resourceType) { case ResourceType.MainFrame when url.EndsWithOrdinal("://twitter.com/"): return new RequestHandleResult.Redirect(TwitterUrls.TweetDeck); // redirect plain twitter.com requests, fixes bugs with login 2FA case ResourceType.Image when url.Contains(UrlLoadingSpinner): return new RequestHandleResult.Redirect("td://resources/images/spinner.apng"); case ResourceType.Script when url.Contains(UrlVendorResource): return new RequestHandleResult.Process(VendorScriptProcessor.Instance); case ResourceType.Script when url.Contains("analytics."): return RequestHandleResult.Cancel; case ResourceType.Xhr when url.Contains(UrlVersionCheck): return RequestHandleResult.Cancel; case ResourceType.Xhr when url.Contains("://api.twitter.com/") && url.Contains("include_entities=1") && !url.Contains("&include_ext_has_nft_avatar=1"): return new RequestHandleResult.Redirect(url.Replace("include_entities=1", "include_entities=1&include_ext_has_nft_avatar=1")); default: return base.Handle(url, resourceType); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using DemoGame.DbObjs; using log4net; using NetGore; using NetGore.Audio; using NetGore.Content; using NetGore.Features.ActionDisplays; using NetGore.Features.GameTime; using NetGore.Features.Groups; using NetGore.Features.Guilds; using NetGore.Features.NPCChat; using NetGore.Features.Quests; using NetGore.Features.Shops; using NetGore.Graphics.GUI; using NetGore.IO; using NetGore.Network; using NetGore.Stats; using NetGore.World; using SFML.Graphics; // ReSharper disable UnusedMember.Local // ReSharper disable UnusedParameter.Local namespace DemoGame.Client { /// <summary> /// Holds all the methods used to process received packets. /// </summary> public partial class ClientPacketHandler : IGetTime { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly IQuestDescriptionCollection _questDescriptions = QuestDescriptionCollection.Create(ContentPaths.Build); readonly AccountCharacterInfos _accountCharacterInfos = new AccountCharacterInfos(); readonly IDynamicEntityFactory _dynamicEntityFactory; readonly INetworkSender _networkSender; readonly ObjGrabber _objGrabber; readonly ClientPeerTradeInfoHandler _peerTradeInfoHandler; readonly IScreenManager _screenManager; GameplayScreen _gameplayScreenCache; /// <summary> /// Initializes a new instance of the <see cref="ClientPacketHandler"/> class. /// </summary> /// <param name="networkSender">The socket sender.</param> /// <param name="screenManager">The <see cref="IScreenManager"/>.</param> /// <param name="dynamicEntityFactory">The <see cref="IDynamicEntityFactory"/> used to serialize /// <see cref="DynamicEntity"/>s.</param> /// <exception cref="ArgumentNullException"><paramref name="dynamicEntityFactory" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="screenManager" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="networkSender" /> is <c>null</c>.</exception> public ClientPacketHandler(INetworkSender networkSender, IScreenManager screenManager, IDynamicEntityFactory dynamicEntityFactory) { if (dynamicEntityFactory == null) throw new ArgumentNullException("dynamicEntityFactory"); if (screenManager == null) throw new ArgumentNullException("screenManager"); if (networkSender == null) throw new ArgumentNullException("networkSender"); _networkSender = networkSender; _dynamicEntityFactory = dynamicEntityFactory; _screenManager = screenManager; _peerTradeInfoHandler = new ClientPeerTradeInfoHandler(networkSender); _peerTradeInfoHandler.GameMessageCallback += PeerTradeInfoHandler_GameMessageCallback; _objGrabber = new ObjGrabber(this); } /// <summary> /// Notifies listeners when a message has been received about creating an account. /// </summary> public event TypedEventHandler<IIPSocket, CreateAccountEventArgs> ReceivedCreateAccount; /// <summary> /// Notifies listeners when a message has been received about creating an account character. /// </summary> public event TypedEventHandler<IIPSocket, CreateAccountEventArgs> ReceivedCreateAccountCharacter; /// <summary> /// Notifies listeners when a successful login request has been made. /// </summary> public event TypedEventHandler<ClientPacketHandler, ClientPacketHandlerEventArgs> ReceivedLoginSuccessful; /// <summary> /// Notifies listeners when an unsuccessful login request has been made. /// </summary> public event TypedEventHandler<ClientPacketHandler, ClientPacketHandlerEventArgs<string>> ReceivedLoginUnsuccessful; public AccountCharacterInfos AccountCharacterInfos { get { return _accountCharacterInfos; } } /// <summary> /// Gets the <see cref="GameplayScreen"/>. /// </summary> public GameplayScreen GameplayScreen { get { if (_gameplayScreenCache == null) _gameplayScreenCache = _screenManager.GetScreen<GameplayScreen>(); return _gameplayScreenCache; } } public UserGroupInformation GroupInfo { get { return GameplayScreen.UserInfo.GroupInfo; } } public UserGuildInformation GuildInfo { get { return GameplayScreen.UserInfo.GuildInfo; } } /// <summary> /// Gets the <see cref="Map"/> used by the <see cref="World"/>. /// </summary> public Map Map { get { return GameplayScreen.World.Map; } } public INetworkSender NetworkSender { get { return _networkSender; } } /// <summary> /// Gets the <see cref="ClientPeerTradeInfoHandler"/> instance. /// </summary> public ClientPeerTradeInfoHandler PeerTradeInfoHandler { get { return _peerTradeInfoHandler; } } public UserQuestInformation QuestInfo { get { return GameplayScreen.UserInfo.QuestInfo; } } /// <summary> /// Gets the <see cref="IScreenManager"/>. /// </summary> public IScreenManager ScreenManager { get { return _screenManager; } } public ISoundManager SoundManager { get { return GameplayScreen.SoundManager; } } /// <summary> /// Gets the user's <see cref="Character"/>. /// </summary> public Character User { get { return GameplayScreen.UserChar; } } public UserInfo UserInfo { get { return GameplayScreen.UserInfo; } } /// <summary> /// Gets the world used by the game (Parent.World) /// </summary> public World World { get { return GameplayScreen.World; } } static IEnumerable<StyledText> CreateChatText(string name, string message) { var left = new StyledText(name + ": ", Color.Red); var right = new StyledText(message, Color.Black); return new List<StyledText> { left, right }; } static void LogFailPlaySound(SoundID soundID) { const string errmsg = "Failed to play sound with ID `{0}`."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, soundID); Debug.Fail(string.Format(errmsg, soundID)); } /// <summary> /// Handles the <see cref="ClientPeerTradeInfoHandler.GameMessageCallback"/> event from the <see cref="ClientPeerTradeInfoHandler"/>. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="ClientPeerTradeInfoHandlerEventArgs"/> instance containing the event data.</param> void PeerTradeInfoHandler_GameMessageCallback(ClientPeerTradeInfoHandler sender, ClientPeerTradeInfoHandlerEventArgs e) { // Parse the GameMessage var msg = GameMessageCollection.CurrentLanguage.GetMessage(e.GameMessage, e.Args); // Display if (!string.IsNullOrEmpty(msg)) GameplayScreen.AppendToChatOutput(msg); } [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "accepted")] [MessageHandler((uint)ServerPacketID.AcceptOrTurnInQuestReply)] void RecvAcceptOrTurnInQuestReply(IIPSocket conn, BitStream r) { var questID = r.ReadQuestID(); var successful = r.ReadBool(); #pragma warning disable 168 var accepted = r.ReadBool(); #pragma warning restore 168 if (successful) { // Remove the quest from the available quests list var aqf = GameplayScreen.AvailableQuestsForm; if (aqf.IsVisible) { aqf.AvailableQuests = aqf.AvailableQuests.Where(x => x.QuestID != questID).ToArray(); } } } [MessageHandler((uint)ServerPacketID.AddStatusEffect)] void RecvAddStatusEffect(IIPSocket conn, BitStream r) { var statusEffectType = r.ReadEnum<StatusEffectType>(); var power = r.ReadUShort(); var secsLeft = r.ReadUShort(); var param = new string[] {User.Name, statusEffectType.ToString(), power.ToString()}; var message = GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.CombatStatusEffectGained, param); GameplayScreen.StatusEffectsForm.AddStatusEffect(statusEffectType, power, secsLeft); GameplayScreen.AppendToChatOutput(message); } [MessageHandler((uint)ServerPacketID.CharAttack)] void RecvCharAttack(IIPSocket conn, BitStream r) { // Read the values var attackerID = r.ReadMapEntityIndex(); MapEntityIndex? attackedID; if (r.ReadBool()) attackedID = r.ReadMapEntityIndex(); else attackedID = null; ActionDisplayID? actionDisplayIDNullable; if (r.ReadBool()) actionDisplayIDNullable = r.ReadActionDisplayID(); else actionDisplayIDNullable = null; // Get the object references using the IDs provided var attacker = _objGrabber.GetDynamicEntity<Character>(attackerID); if (attacker == null) return; DynamicEntity attacked = attackedID.HasValue ? Map.GetDynamicEntity(attackedID.Value) : null; // Use the default ActionDisplayID if we were provided with a null value ActionDisplayID actionDisplayID = !actionDisplayIDNullable.HasValue ? GameData.DefaultActionDisplayID : actionDisplayIDNullable.Value; // Get the ActionDisplay to use and, if valid, execute it var actionDisplay = ActionDisplayScripts.ActionDisplays[actionDisplayID]; if (actionDisplay != null) actionDisplay.Execute(Map, attacker, attacked); } [MessageHandler((uint)ServerPacketID.CharDamage)] void RecvCharDamage(IIPSocket conn, BitStream r) { var mapCharIndex = r.ReadMapEntityIndex(); var damage = r.ReadInt(); var chr = _objGrabber.GetDynamicEntity<Character>(mapCharIndex); if (chr == null) return; GameplayScreen.DamageTextPool.Create(damage, chr, GetTime()); } [MessageHandler((uint)ServerPacketID.Chat)] void RecvChat(IIPSocket conn, BitStream r) { var text = r.ReadString(GameData.MaxServerSayLength); GameplayScreen.AppendToChatOutput(text); } [MessageHandler((uint)ServerPacketID.ChatSay)] void RecvChatSay(IIPSocket conn, BitStream r) { var name = r.ReadString(GameData.MaxServerSayNameLength); var mapEntityIndex = r.ReadMapEntityIndex(); var text = r.ReadString(GameData.MaxServerSayLength); var chatText = CreateChatText(name, text); GameplayScreen.AppendToChatOutput(chatText); var entity = Map.GetDynamicEntity(mapEntityIndex); if (entity == null) return; GameplayScreen.AddChatBubble(entity, text); } [MessageHandler((uint)ServerPacketID.CreateAccount)] void RecvCreateAccount(IIPSocket conn, BitStream r) { var successful = r.ReadBool(); var errorMessage = string.Empty; if (!successful) { var failureGameMessage = r.ReadEnum<GameMessage>(); errorMessage = GameMessageCollection.CurrentLanguage.GetMessage(failureGameMessage); } if (ReceivedCreateAccount != null) ReceivedCreateAccount.Raise(conn, new CreateAccountEventArgs(successful, errorMessage)); } [MessageHandler((uint)ServerPacketID.CreateAccountCharacter)] void RecvCreateAccountCharacter(IIPSocket conn, BitStream r) { var successful = r.ReadBool(); var errorMessage = successful ? string.Empty : r.ReadString(); if (ReceivedCreateAccountCharacter != null) ReceivedCreateAccountCharacter.Raise(conn, new CreateAccountEventArgs(successful, errorMessage)); } [MessageHandler((uint)ServerPacketID.CreateDynamicEntity)] void RecvCreateDynamicEntity(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var dynamicEntity = _dynamicEntityFactory.Read(r); Map.AddDynamicEntity(dynamicEntity, mapEntityIndex); var character = dynamicEntity as Character; if (character != null) { // HACK: Having to call this .Initialize() and pass these parameters seems hacky character.Initialize(Map, GameplayScreen.SkeletonManager); } if (log.IsInfoEnabled) log.InfoFormat("Created DynamicEntity with index `{0}` of type `{1}`", dynamicEntity.MapEntityIndex, dynamicEntity.GetType()); } [MessageHandler((uint)ServerPacketID.SynchronizeDynamicEntity)] void RecvSynchronizeDynamicEntity(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); DynamicEntity e = Map.GetDynamicEntity(mapEntityIndex); e.Deserialize(r); } [MessageHandler((uint)ServerPacketID.Emote)] void RecvEmote(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var emoticon = r.ReadEnum<Emoticon>(); var entity = Map.GetDynamicEntity(mapEntityIndex); if (entity == null) return; EmoticonDisplayManager.Instance.Add(entity, emoticon, GetTime()); } [MessageHandler((uint)ServerPacketID.EndChatDialog)] void RecvEndChatDialog(IIPSocket conn, BitStream r) { GameplayScreen.ChatDialogForm.EndDialog(); } [MessageHandler((uint)ServerPacketID.GroupInfo)] void RecvGroupInfo(IIPSocket conn, BitStream r) { GroupInfo.Read(r); } [MessageHandler((uint)ServerPacketID.GuildInfo)] void RecvGuildInfo(IIPSocket conn, BitStream r) { GuildInfo.Read(r); } [MessageHandler((uint)ServerPacketID.HasQuestFinishRequirementsReply)] void RecvHasQuestFinishRequirementsReply(IIPSocket conn, BitStream r) { var questID = r.ReadQuestID(); var hasRequirements = r.ReadBool(); UserInfo.HasFinishQuestRequirements.SetRequirementsStatus(questID, hasRequirements); } [MessageHandler((uint)ServerPacketID.HasQuestStartRequirementsReply)] void RecvHasQuestStartRequirementsReply(IIPSocket conn, BitStream r) { var questID = r.ReadQuestID(); var hasRequirements = r.ReadBool(); UserInfo.HasStartQuestRequirements.SetRequirementsStatus(questID, hasRequirements); } [MessageHandler((uint)ServerPacketID.LoginSuccessful)] void RecvLoginSuccessful(IIPSocket conn, BitStream r) { if (ReceivedLoginSuccessful != null) ReceivedLoginSuccessful.Raise(this, new ClientPacketHandlerEventArgs(conn)); } [MessageHandler((uint)ServerPacketID.LoginUnsuccessful)] void RecvLoginUnsuccessful(IIPSocket conn, BitStream r) { var message = r.ReadGameMessage(GameMessageCollection.CurrentLanguage); if (ReceivedLoginUnsuccessful != null) ReceivedLoginUnsuccessful.Raise(this, new ClientPacketHandlerEventArgs<string>(conn, message)); } [MessageHandler((uint)ServerPacketID.NotifyExpCash)] void RecvNotifyExpCash(IIPSocket conn, BitStream r) { var exp = r.ReadInt(); var cash = r.ReadInt(); var param = new string[] {exp.ToString(),cash.ToString()}; var message = GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.CombatRecieveReward, param); GameplayScreen.InfoBox.Add(message); } [MessageHandler((uint)ServerPacketID.NotifyGetItem)] void RecvNotifyGetItem(IIPSocket conn, BitStream r) { var name = r.ReadString(); var amount = r.ReadByte(); string msg; if (amount > 1) msg = string.Format("You got {0} {1}s", amount, name); else msg = string.Format("You got a {0}", name); GameplayScreen.InfoBox.Add(msg); } [MessageHandler((uint)ServerPacketID.NotifyLevel)] void RecvNotifyLevel(IIPSocket conn, BitStream r) { var mapCharIndex = r.ReadMapEntityIndex(); var chr = _objGrabber.GetDynamicEntity<Character>(mapCharIndex); if (chr == null) return; var message = GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.CombatSelfLevelUp, UserInfo.Level.ToString()); if (chr == World.UserChar) GameplayScreen.InfoBox.Add(message); } [MessageHandler((uint)ServerPacketID.PeerTradeEvent)] void RecvPeerTradeEvent(IIPSocket conn, BitStream r) { PeerTradeInfoHandler.Read(r); } [MessageHandler((uint)ServerPacketID.PlaySound)] void RecvPlaySound(IIPSocket conn, BitStream r) { var soundID = r.ReadSoundID(); if (!SoundManager.Play(soundID)) LogFailPlaySound(soundID); } [MessageHandler((uint)ServerPacketID.PlaySoundAt)] void RecvPlaySoundAt(IIPSocket conn, BitStream r) { var soundID = r.ReadSoundID(); var position = r.ReadVector2(); if (!SoundManager.Play(soundID, position)) LogFailPlaySound(soundID); } [MessageHandler((uint)ServerPacketID.PlaySoundAtEntity)] void RecvPlaySoundAtEntity(IIPSocket conn, BitStream r) { var soundID = r.ReadSoundID(); var index = r.ReadMapEntityIndex(); var entity = Map.GetDynamicEntity(index); if (entity == null) return; if (!SoundManager.Play(soundID, entity)) LogFailPlaySound(soundID); } [MessageHandler((uint)ServerPacketID.QuestInfo)] void RecvQuestInfo(IIPSocket conn, BitStream r) { QuestInfo.Read(r); } [MessageHandler((uint)ServerPacketID.RemoveDynamicEntity)] void RecvRemoveDynamicEntity(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var dynamicEntity = Map.GetDynamicEntity(mapEntityIndex); if (dynamicEntity == null) return; Map.RemoveEntity(dynamicEntity); if (log.IsInfoEnabled) log.InfoFormat("Removed DynamicEntity with index `{0}`", mapEntityIndex); dynamicEntity.Dispose(); } [MessageHandler((uint)ServerPacketID.RemoveStatusEffect)] void RecvRemoveStatusEffect(IIPSocket conn, BitStream r) { var statusEffectType = r.ReadEnum<StatusEffectType>(); var message = GameMessageCollection.CurrentLanguage.GetMessage(GameMessage.CombatStatusEffectWoreOff, statusEffectType.ToString()); GameplayScreen.StatusEffectsForm.RemoveStatusEffect(statusEffectType); GameplayScreen.AppendToChatOutput(message); } [MessageHandler((uint)ServerPacketID.SendAccountCharacters)] void RecvSendAccountCharacters(IIPSocket conn, BitStream r) { var count = r.ReadByte(); var charInfos = new AccountCharacterInfo[count]; for (var i = 0; i < count; i++) { var charInfo = r.ReadAccountCharacterInfo(); charInfos[charInfo.Index] = charInfo; } _accountCharacterInfos.SetInfos(charInfos); } [MessageHandler((uint)ServerPacketID.SendEquipmentItemInfo)] void RecvSendEquipmentItemInfo(IIPSocket conn, BitStream r) { var slot = r.ReadEnum<EquipmentSlot>(); GameplayScreen.EquipmentInfoRequester.ReceiveInfo(slot, r); } [MessageHandler((uint)ServerPacketID.SendInventoryItemInfo)] void RecvSendInventoryItemInfo(IIPSocket conn, BitStream r) { var slot = r.ReadInventorySlot(); GameplayScreen.InventoryInfoRequester.ReceiveInfo(slot, r); } [MessageHandler((uint)ServerPacketID.SendMessage)] void RecvSendMessage(IIPSocket conn, BitStream r) { var message = r.ReadGameMessage(GameMessageCollection.CurrentLanguage); if (string.IsNullOrEmpty(message)) { const string errmsg = "Received empty or null GameMessage."; if (log.IsErrorEnabled) log.Error(errmsg); return; } GameplayScreen.AppendToChatOutput(message, Color.Black); } [MessageHandler((uint)ServerPacketID.SetCash)] void RecvSetCash(IIPSocket conn, BitStream r) { var cash = r.ReadInt(); UserInfo.Cash = cash; } [MessageHandler((uint)ServerPacketID.SetCharacterHPPercent)] void RecvSetCharacterHPPercent(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var percent = r.ReadByte(); var character = _objGrabber.GetDynamicEntity<Character>(mapEntityIndex); if (character == null) return; character.HPPercent = percent; } [MessageHandler((uint)ServerPacketID.SetCharacterMPPercent)] void RecvSetCharacterMPPercent(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var percent = r.ReadByte(); var character = _objGrabber.GetDynamicEntity<Character>(mapEntityIndex); if (character == null) return; character.MPPercent = percent; } [MessageHandler((uint)ServerPacketID.SetCharacterPaperDoll)] void RecvSetCharacterPaperDoll(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var count = r.ReadByte(); var layers = new string[count]; for (var i = 0; i < layers.Length; i++) { layers[i] = r.ReadString(); } var character = _objGrabber.GetDynamicEntity<Character>(mapEntityIndex); if (character == null) return; character.CharacterSprite.SetPaperDollLayers(layers); } [MessageHandler((uint)ServerPacketID.SetChatDialogPage)] void RecvSetChatDialogPage(IIPSocket conn, BitStream r) { var pageID = r.ReadNPCChatDialogItemID(); var skipCount = r.ReadByte(); var responsesToSkip = new byte[skipCount]; for (var i = 0; i < skipCount; i++) { responsesToSkip[i] = r.ReadByte(); } GameplayScreen.ChatDialogForm.SetPageIndex(pageID, responsesToSkip); } [MessageHandler((uint)ServerPacketID.SetClickWarpMode)] void RecvSetClickWarpMode(IIPSocket conn, BitStream r) { bool enabled = r.ReadBool(); GameplayScreen.AppendToChatOutput("Click warp mode: " + (enabled ? "Enabled" : "Disabled"), Color.Green); GameplayScreen.ClickWarpMode = enabled; } [MessageHandler((uint)ServerPacketID.SetExp)] void RecvSetExp(IIPSocket conn, BitStream r) { var exp = r.ReadInt(); UserInfo.Exp = exp; } [MessageHandler((uint)ServerPacketID.SetGameTime)] void RecvSetGameTime(IIPSocket conn, BitStream r) { var serverTimeBinary = r.ReadLong(); var serverTime = DateTime.FromBinary(serverTimeBinary); GameDateTime.SetServerTimeOffset(serverTime); } [MessageHandler((uint)ServerPacketID.SetHP)] void RecvSetHP(IIPSocket conn, BitStream r) { var value = r.ReadSPValueType(); UserInfo.HP = value; if (User == null) return; User.HPPercent = UserInfo.HPPercent; } [MessageHandler((uint)ServerPacketID.SetInventorySlot)] void RecvSetInventorySlot(IIPSocket conn, BitStream r) { var slot = r.ReadInventorySlot(); var hasGraphic = r.ReadBool(); var graphic = hasGraphic ? r.ReadGrhIndex() : GrhIndex.Invalid; var amount = r.ReadByte(); UserInfo.Inventory.Update(slot, graphic, amount, GetTime()); } [MessageHandler((uint)ServerPacketID.SetLevel)] void RecvSetLevel(IIPSocket conn, BitStream r) { var level = r.ReadShort(); UserInfo.Level = level; } [MessageHandler((uint)ServerPacketID.SetMP)] void RecvSetMP(IIPSocket conn, BitStream r) { var value = r.ReadSPValueType(); UserInfo.MP = value; if (User == null) return; User.MPPercent = UserInfo.MPPercent; } [MessageHandler((uint)ServerPacketID.SetMap)] void RecvSetMap(IIPSocket conn, BitStream r) { var mapID = r.ReadMapID(); // Create the new map var newMap = new Map(mapID, World.Camera, World); newMap.Load(ContentPaths.Build, false, _dynamicEntityFactory); // Clear quest requirements caches UserInfo.HasStartQuestRequirements.Clear(); // Change maps World.Map = newMap; // Unload all map content from the previous map and from the new map loading GameplayScreen.ScreenManager.Content.Unload(ContentLevel.Map); // Change the screens, if needed GameplayScreen.ScreenManager.SetScreen<GameplayScreen>(); } [MessageHandler((uint)ServerPacketID.SetProvidedQuests)] void RecvSetProvidedQuests(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); var count = r.ReadByte(); var questIDs = new QuestID[count]; for (var i = 0; i < count; i++) { questIDs[i] = r.ReadQuestID(); } var character = _objGrabber.GetDynamicEntity<Character>(mapEntityIndex); if (character != null) character.ProvidedQuests = questIDs; } [MessageHandler((uint)ServerPacketID.SetStatPoints)] void RecvSetStatPoints(IIPSocket conn, BitStream r) { var statPoints = r.ReadInt(); UserInfo.StatPoints = statPoints; } [MessageHandler((uint)ServerPacketID.SetUserChar)] void RecvSetUserChar(IIPSocket conn, BitStream r) { var mapCharIndex = r.ReadMapEntityIndex(); World.UserCharIndex = mapCharIndex; } [MessageHandler((uint)ServerPacketID.SkillSetGroupCooldown)] void RecvSkillSetGroupCooldown(IIPSocket conn, BitStream r) { var skillGroup = r.ReadByte(); var cooldownTime = r.ReadUShort(); GameplayScreen.SkillCooldownManager.SetCooldown(skillGroup, cooldownTime, GetTime()); } [MessageHandler((uint)ServerPacketID.SkillSetKnown)] void RecvSkillSetKnown(IIPSocket conn, BitStream r) { var skillType = r.ReadEnum<SkillType>(); var isKnown = r.ReadBool(); if (!EnumHelper<SkillType>.IsDefined(skillType)) { const string errmsg = "Invalid SkillType received: `{0}`"; if (log.IsWarnEnabled) log.WarnFormat(errmsg, skillType); Debug.Fail(string.Format(errmsg, skillType)); return; } // Set the skill's known state UserInfo.KnownSkills.SetSkill(skillType, isKnown); } [MessageHandler((uint)ServerPacketID.SkillSetKnownAll)] void RecvSkillSetKnownAll(IIPSocket conn, BitStream r) { var count = r.ReadByte(); var knownSkills = new List<SkillType>(count); // Read the known skills list for (var i = 0; i < count; i++) { var value = r.ReadEnum<SkillType>(); knownSkills.Add(value); } Debug.Assert(knownSkills.Count == count); Debug.Assert(knownSkills.All(EnumHelper<SkillType>.IsDefined), "One or more known skills were unknown..."); // Set the known skills UserInfo.KnownSkills.SetValues(knownSkills); } [MessageHandler((uint)ServerPacketID.CreateActionDisplayAtEntity)] void RecvCreateActionDisplayAtEntity(IIPSocket conn, BitStream r) { ActionDisplayID actionDisplayId = r.ReadActionDisplayID(); MapEntityIndex sourceEntityIndex = r.ReadMapEntityIndex(); bool hasTarget = r.ReadBool(); MapEntityIndex? targetEntityIndex = hasTarget ? r.ReadMapEntityIndex() : (MapEntityIndex?)null; // Get the entities var sourceEntity = _objGrabber.GetDynamicEntity<Character>(sourceEntityIndex); if (sourceEntity == null) return; var targetEntity = targetEntityIndex.HasValue ? _objGrabber.GetDynamicEntity<Character>(targetEntityIndex.Value) : null; // Get the action display var ad = ActionDisplayScripts.ActionDisplays[actionDisplayId]; if (ad == null) return; // Create ad.Execute(Map, sourceEntity, targetEntity); } [MessageHandler((uint)ServerPacketID.SkillStartCasting_ToMap)] void RecvSkillStartCasting_ToMap(IIPSocket conn, BitStream r) { var casterEntityIndex = r.ReadMapEntityIndex(); var skillType = r.ReadEnum<SkillType>(); // Get the SkillInfo for the skill being used var skillInfo = _objGrabber.GetSkillInfo(skillType); if (skillInfo == null) return; // Get the entity var casterEntity = _objGrabber.GetDynamicEntity<Character>(casterEntityIndex); if (casterEntity == null) return; // If an ActionDisplay is available for this skill, display it if (skillInfo.StartCastingActionDisplay.HasValue) { var ad = ActionDisplayScripts.ActionDisplays[skillInfo.StartCastingActionDisplay.Value]; if (ad != null) { casterEntity.IsCastingSkill = true; ad.Execute(Map, casterEntity, null); } } } [MessageHandler((uint)ServerPacketID.SkillStartCasting_ToUser)] void RecvSkillStartCasting_ToUser(IIPSocket conn, BitStream r) { var skillType = r.ReadEnum<SkillType>(); var castTime = r.ReadUShort(); GameplayScreen.SkillCastProgressBar.StartCasting(skillType, castTime); } [MessageHandler((uint)ServerPacketID.SkillStopCasting_ToMap)] void RecvSkillStopCasting_ToMap(IIPSocket conn, BitStream r) { var casterEntityIndex = r.ReadMapEntityIndex(); // Get the entity var casterEntity = _objGrabber.GetDynamicEntity<Character>(casterEntityIndex); if (casterEntity == null) return; // Set the entity as not casting casterEntity.IsCastingSkill = false; } [MessageHandler((uint)ServerPacketID.SkillStopCasting_ToUser)] void RecvSkillStopCasting_ToUser(IIPSocket conn, BitStream r) { GameplayScreen.SkillCastProgressBar.StopCasting(); } [MessageHandler((uint)ServerPacketID.SkillUse)] void RecvSkillUse(IIPSocket conn, BitStream r) { var casterEntityIndex = r.ReadMapEntityIndex(); var hasTarget = r.ReadBool(); MapEntityIndex? targetEntityIndex = null; if (hasTarget) targetEntityIndex = r.ReadMapEntityIndex(); var skillType = r.ReadEnum<SkillType>(); var casterEntity = _objGrabber.GetDynamicEntity<CharacterEntity>(casterEntityIndex); CharacterEntity targetEntity = null; if (targetEntityIndex.HasValue) targetEntity = _objGrabber.GetDynamicEntity<CharacterEntity>(targetEntityIndex.Value); if (casterEntity == null) return; // Get the SkillInfo for the skill being used var skillInfo = _objGrabber.GetSkillInfo(skillType); if (skillInfo == null) return; // If an ActionDisplay is available for this skill, display it if (skillInfo.CastActionDisplay.HasValue) { var ad = ActionDisplayScripts.ActionDisplays[skillInfo.CastActionDisplay.Value]; if (ad != null) ad.Execute(Map, casterEntity, targetEntity); } } [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "npcIndex")] [MessageHandler((uint)ServerPacketID.StartChatDialog)] void RecvStartChatDialog(IIPSocket conn, BitStream r) { #pragma warning disable 168 var npcIndex = r.ReadMapEntityIndex(); #pragma warning restore 168 var dialogIndex = r.ReadNPCChatDialogID(); var dialog = ClientNPCChatManager.Instance[dialogIndex]; GameplayScreen.ChatDialogForm.StartDialog(dialog); } [MessageHandler((uint)ServerPacketID.StartQuestChatDialog)] void RecvStartQuestChatDialog(IIPSocket conn, BitStream r) { var npcIndex = r.ReadMapEntityIndex(); // Available quests var numAvailableQuests = r.ReadByte(); var availableQuests = new QuestID[numAvailableQuests]; for (var i = 0; i < availableQuests.Length; i++) { availableQuests[i] = r.ReadQuestID(); } // Quests that can be turned in var numTurnInQuests = r.ReadByte(); var turnInQuests = new QuestID[numTurnInQuests]; for (var i = 0; i < turnInQuests.Length; i++) { turnInQuests[i] = r.ReadQuestID(); } // For the quests that are available, make sure we set their status to not being able to be turned in (just in case) foreach (var id in availableQuests) { UserInfo.HasFinishQuestRequirements.SetRequirementsStatus(id, false); } // For the quests that were marked as being able to turn in, set their status to being able to be finished foreach (var id in turnInQuests) { UserInfo.HasFinishQuestRequirements.SetRequirementsStatus(id, true); } // Grab the descriptions for both the available quests and quests we can turn in var qds = availableQuests.Concat(turnInQuests).Distinct().Select(x => _questDescriptions.GetOrDefault(x)).ToArray(); // Display the form GameplayScreen.AvailableQuestsForm.Display(qds, npcIndex); } [MessageHandler((uint)ServerPacketID.StartShopping)] void RecvStartShopping(IIPSocket conn, BitStream r) { var shopOwnerIndex = r.ReadMapEntityIndex(); var canBuy = r.ReadBool(); var name = r.ReadString(); var itemCount = r.ReadByte(); var items = new IItemTemplateTable[itemCount]; for (var i = 0; i < itemCount; i++) { var value = new ItemTemplateTable(); value.ReadState(r); items[i] = value; } var shopOwner = Map.GetDynamicEntity(shopOwnerIndex); var shopInfo = new ShopInfo<IItemTemplateTable>(shopOwner, name, canBuy, items); GameplayScreen.ShopForm.DisplayShop(shopInfo); } [MessageHandler((uint)ServerPacketID.StopShopping)] void RecvStopShopping(IIPSocket conn, BitStream r) { GameplayScreen.ShopForm.HideShop(); } [MessageHandler((uint)ServerPacketID.UpdateEquipmentSlot)] void RecvUpdateEquipmentSlot(IIPSocket conn, BitStream r) { var slot = r.ReadEnum<EquipmentSlot>(); var hasValue = r.ReadBool(); if (hasValue) { var graphic = r.ReadGrhIndex(); UserInfo.Equipped.SetSlot(slot, graphic); } else UserInfo.Equipped.ClearSlot(slot); } [MessageHandler((uint)ServerPacketID.UpdateStat)] void RecvUpdateStat(IIPSocket conn, BitStream r) { var isBaseStat = r.ReadBool(); var stat = r.ReadStat<StatType>(); var coll = isBaseStat ? UserInfo.BaseStats : UserInfo.ModStats; coll[stat.StatType] = stat.Value; } [MessageHandler((uint)ServerPacketID.UpdateVelocityAndPosition)] void RecvUpdateVelocityAndPosition(IIPSocket conn, BitStream r) { var mapEntityIndex = r.ReadMapEntityIndex(); DynamicEntity dynamicEntity = null; // Grab the DynamicEntity // The map can be null if the spatial updates come very early (which isn't uncommon) if (Map != null) dynamicEntity = _objGrabber.GetDynamicEntity<DynamicEntity>(mapEntityIndex); // Deserialize if (dynamicEntity != null) { // Read the value into the DynamicEntity dynamicEntity.DeserializePositionAndVelocity(r); } else { // DynamicEntity was null, so just flush the values from the reader DynamicEntity.FlushPositionAndVelocity(r); } } [MessageHandler((uint)ServerPacketID.UseEntity)] void RecvUseEntity(IIPSocket conn, BitStream r) { var usedEntityIndex = r.ReadMapEntityIndex(); var usedByIndex = r.ReadMapEntityIndex(); // Grab the used DynamicEntity var usedEntity = _objGrabber.GetDynamicEntity<IUsableEntity>(usedEntityIndex); if (usedEntity == null) return; // Grab the one who used this DynamicEntity (we can still use it, we'll just pass null) var usedBy = Map.GetDynamicEntity(usedByIndex); if (usedBy == null) return; // Use it usedEntity.Use(usedBy); } [MessageHandler((uint)ServerPacketID.ReceiveFriends)] void RecvReceiveFriends(IIPSocket conn, BitStream r) { List<String> _onlineFriends = new List<String>(); _onlineFriends = r.ReadString().Split(',').ToList<string>(); string[] FriendsMap = r.ReadString().Split(','); string[] FriendsList = r.ReadString().Split(','); _onlineFriends.RemoveAll(x => x == ""); int i = 0; FriendsForm._myFriends = new List<Friends>(); foreach (string friend in _onlineFriends) { FriendsForm._myFriends.Add(new Friends { Name = friend, Map = FriendsMap[i], Online = true }); } foreach (string _friend in FriendsList) { FriendsForm._myFriends.Add(new Friends { Name = _friend, Online = false }); i++; } FriendsForm._myFriends.RemoveDuplicates((x, y) => x.Name == y.Name); FriendsForm._myFriends.RemoveAll((x) => x.Name == ""); FriendsForm.SortList(); } [MessageHandler((uint)ServerPacketID.ReceivePrivateMessage)] void RecvReceivePrivateMessage(IIPSocket conn, BitStream r) { string Message = r.ReadString(); string PrivateMessage = Message; // Display the private message GameplayScreen.AppendToChatOutput(Message, Color.BlueViolet); } [MessageHandler((uint)ServerPacketID.ReceiveOnlineUsers)] void RecvReceiveOnlineUsers(IIPSocket conn, BitStream r) { List<String> online = r.ReadString().Split(';').ToList(); online.RemoveAll(x => x.IsEmpty()); foreach (string user in online) OnlineUsersForm.Online.Add(user); OnlineUsersForm.Online.RemoveDuplicates((x, y) => x == y); OnlineUsersForm.Online.RemoveAll(x => x.IsEmpty()); OnlineUsersForm.UpdateUsersList(); } #region IGetTime Members /// <summary> /// Gets the current time. /// </summary> /// <returns>Current time.</returns> public TickCount GetTime() { return GameplayScreen.GetTime(); } #endregion } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax.Grpc; using Google.Cloud.ClientTesting; using Google.Protobuf; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.PubSub.V1.Snippets { [SnippetOutputCollector] [Collection(nameof(PubsubSnippetFixture))] public class SubscriberServiceApiClientSnippets { private readonly PubsubSnippetFixture _fixture; public SubscriberServiceApiClientSnippets(PubsubSnippetFixture fixture) { _fixture = fixture; } [Fact] public void Overview() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); // Sample: Overview // First create a topic. PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); // Subscribe to the topic. SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60); // Publish a message to the topic. PubsubMessage message = new PubsubMessage { // The data is any arbitrary ByteString. Here, we're using text. Data = ByteString.CopyFromUtf8("Hello, Pubsub"), // The attributes provide metadata in a string-to-string dictionary. Attributes = { { "description", "Simple text message" } } }; publisher.Publish(topicName, new[] { message }); // Pull messages from the subscription. We're returning immediately, whether or not there // are messages; in other cases you'll want to allow the call to wait until a message arrives. PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 10); foreach (ReceivedMessage received in response.ReceivedMessages) { PubsubMessage msg = received.Message; Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}"); Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'"); } // Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified // when we created the subscription) we'll receive the messages again when we next pull. subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId)); // Tidy up by deleting the subscription and the topic. subscriber.DeleteSubscription(subscriptionName); publisher.DeleteTopic(topicName); // End sample Assert.Equal(1, response.ReceivedMessages.Count); Assert.Equal("Hello, Pubsub", response.ReceivedMessages[0].Message.Data.ToStringUtf8()); Assert.Equal("Simple text message", response.ReceivedMessages[0].Message.Attributes["description"]); } [Fact] public async Task SimpleOverview() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); // Sample: SimpleOverview // First create a topic. PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync(); TopicName topicName = new TopicName(projectId, topicId); publisherService.CreateTopic(topicName); // Subscribe to the topic. SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60); // Publish a message to the topic using PublisherClient. PublisherClient publisher = await PublisherClient.CreateAsync(topicName); // PublishAsync() has various overloads. Here we're using the string overload. string messageId = await publisher.PublishAsync("Hello, Pubsub"); // PublisherClient instance should be shutdown after use. // The TimeSpan specifies for how long to attempt to publish locally queued messages. await publisher.ShutdownAsync(TimeSpan.FromSeconds(15)); // Pull messages from the subscription using SimpleSubscriber. SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName); List<PubsubMessage> receivedMessages = new List<PubsubMessage>(); // Start the subscriber listening for messages. await subscriber.StartAsync((msg, cancellationToken) => { receivedMessages.Add(msg); Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}"); Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'"); // Stop this subscriber after one message is received. // This is non-blocking, and the returned Task may be awaited. subscriber.StopAsync(TimeSpan.FromSeconds(15)); // Return Reply.Ack to indicate this message has been handled. return Task.FromResult(SubscriberClient.Reply.Ack); }); // Tidy up by deleting the subscription and the topic. subscriberService.DeleteSubscription(subscriptionName); publisherService.DeleteTopic(topicName); // End sample Assert.Equal(1, receivedMessages.Count); Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8()); } [Fact] public void ListSubscriptions() { string projectId = _fixture.ProjectId; // Snippet: ListSubscriptions(*,*,*,*) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); ProjectName projectName = new ProjectName(projectId); foreach (Subscription subscription in client.ListSubscriptions(projectName)) { Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}"); } // End snippet } [Fact] public async Task ListSubscriptionsAsync() { string projectId = _fixture.ProjectId; // Snippet: ListSubscriptionsAsync(*,*,*,*) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); ProjectName projectName = new ProjectName(projectId); IAsyncEnumerable<Subscription> subscriptions = client.ListSubscriptionsAsync(projectName); await subscriptions.ForEachAsync(subscription => { Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}"); }); // End snippet } [Fact] public void CreateSubscription() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId)); // Snippet: CreateSubscription(*,*,*,*,*) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); TopicName topicName = new TopicName(projectId, topicId); Subscription subscription = client.CreateSubscription( subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30); Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}"); // End snippet } [Fact] public async Task CreateSubscriptionAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId)); // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CallSettings) // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CancellationToken) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); TopicName topicName = new TopicName(projectId, topicId); Subscription subscription = await client.CreateSubscriptionAsync( subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30); Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}"); // End snippet } [Fact] public void Pull() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") }; SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60); publisher.Publish(topicName, new[] { newMessage }); // Snippet: Pull(*,*,*,*) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); PullResponse pullResponse = client.Pull(subscriptionName, returnImmediately: false, maxMessages: 100); foreach (ReceivedMessage message in pullResponse.ReceivedMessages) { // Messages can contain any data. We'll assume that we know this // topic publishes UTF-8-encoded text. Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}"); } // Acknowledge the messages after pulling them, so we don't pull them // a second time later. The ackDeadlineSeconds parameter specified when // the subscription is created determines how quickly you need to acknowledge // successfully-pulled messages before they will be redelivered. var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId); client.Acknowledge(subscriptionName, ackIds); // End snippet } [Fact] public async Task PullAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") }; SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60); publisher.Publish(topicName, new[] { newMessage }); // Snippet: PullAsync(SubscriptionName,*,*,CallSettings) // Additional: PullAsync(SubscriptionName,*,*,CancellationToken) SubscriberServiceApiClient client = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); PullResponse pullResponse = await client.PullAsync(subscriptionName, returnImmediately: false, maxMessages: 100); foreach (ReceivedMessage message in pullResponse.ReceivedMessages) { // Messages can contain any data. We'll assume that we know this // topic publishes UTF-8-encoded text. Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}"); } // Acknowledge the messages after pulling them, so we don't pull them // a second time later. The ackDeadlineSeconds parameter specified when // the subscription is created determines how quickly you need to acknowledge // successfully-pulled messages before they will be redelivered. var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId); await client.AcknowledgeAsync(subscriptionName, ackIds); // End snippet } [Fact] public async Task StreamingPull() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); // Snippet: StreamingPull(*, *) PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); subscriber.CreateSubscription(subscriptionName, topicName, null, 60); // If we don't see all the messages we expect in 10 seconds, we'll cancel the call. CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token); SubscriberServiceApiClient.StreamingPullStream stream = subscriber.StreamingPull(callSettings); // The first request must include the subscription name and the stream ack deadline await stream.WriteAsync(new StreamingPullRequest { SubscriptionAsSubscriptionName = subscriptionName, StreamAckDeadlineSeconds = 20 }); Task pullingTask = Task.Run(async () => { int messagesSeen = 0; IAsyncEnumerator<StreamingPullResponse> responseStream = stream.ResponseStream; // Handle responses as we see them. while (await responseStream.MoveNext()) { StreamingPullResponse response = responseStream.Current; Console.WriteLine("Received streaming response"); foreach (ReceivedMessage message in response.ReceivedMessages) { // Messages can contain any data. We'll assume that we know this // topic publishes UTF-8-encoded text. Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}"); } // Acknowledge the messages we've just seen await stream.WriteAsync(new StreamingPullRequest { AckIds = { response.ReceivedMessages.Select(rm => rm.AckId) } }); // If we've seen all the messages we expect, we can complete the streaming call, // and our next MoveNext call will return false. messagesSeen += response.ReceivedMessages.Count; if (messagesSeen == 3) { await stream.WriteCompleteAsync(); } } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 1") } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 2") } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 3") } }); await pullingTask; // End snippet } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.CloudFormation { /// <summary> /// Constants used for properties of type Capability. /// </summary> public class Capability : ConstantClass { /// <summary> /// Constant CAPABILITY_IAM for Capability /// </summary> public static readonly Capability CAPABILITY_IAM = new Capability("CAPABILITY_IAM"); /// <summary> /// Default Constructor /// </summary> public Capability(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static Capability FindValue(string value) { return FindValue<Capability>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator Capability(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type OnFailure. /// </summary> public class OnFailure : ConstantClass { /// <summary> /// Constant DELETE for OnFailure /// </summary> public static readonly OnFailure DELETE = new OnFailure("DELETE"); /// <summary> /// Constant DO_NOTHING for OnFailure /// </summary> public static readonly OnFailure DO_NOTHING = new OnFailure("DO_NOTHING"); /// <summary> /// Constant ROLLBACK for OnFailure /// </summary> public static readonly OnFailure ROLLBACK = new OnFailure("ROLLBACK"); /// <summary> /// Default Constructor /// </summary> public OnFailure(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static OnFailure FindValue(string value) { return FindValue<OnFailure>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator OnFailure(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ResourceSignalStatus. /// </summary> public class ResourceSignalStatus : ConstantClass { /// <summary> /// Constant FAILURE for ResourceSignalStatus /// </summary> public static readonly ResourceSignalStatus FAILURE = new ResourceSignalStatus("FAILURE"); /// <summary> /// Constant SUCCESS for ResourceSignalStatus /// </summary> public static readonly ResourceSignalStatus SUCCESS = new ResourceSignalStatus("SUCCESS"); /// <summary> /// Default Constructor /// </summary> public ResourceSignalStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ResourceSignalStatus FindValue(string value) { return FindValue<ResourceSignalStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ResourceSignalStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ResourceStatus. /// </summary> public class ResourceStatus : ConstantClass { /// <summary> /// Constant CREATE_COMPLETE for ResourceStatus /// </summary> public static readonly ResourceStatus CREATE_COMPLETE = new ResourceStatus("CREATE_COMPLETE"); /// <summary> /// Constant CREATE_FAILED for ResourceStatus /// </summary> public static readonly ResourceStatus CREATE_FAILED = new ResourceStatus("CREATE_FAILED"); /// <summary> /// Constant CREATE_IN_PROGRESS for ResourceStatus /// </summary> public static readonly ResourceStatus CREATE_IN_PROGRESS = new ResourceStatus("CREATE_IN_PROGRESS"); /// <summary> /// Constant DELETE_COMPLETE for ResourceStatus /// </summary> public static readonly ResourceStatus DELETE_COMPLETE = new ResourceStatus("DELETE_COMPLETE"); /// <summary> /// Constant DELETE_FAILED for ResourceStatus /// </summary> public static readonly ResourceStatus DELETE_FAILED = new ResourceStatus("DELETE_FAILED"); /// <summary> /// Constant DELETE_IN_PROGRESS for ResourceStatus /// </summary> public static readonly ResourceStatus DELETE_IN_PROGRESS = new ResourceStatus("DELETE_IN_PROGRESS"); /// <summary> /// Constant DELETE_SKIPPED for ResourceStatus /// </summary> public static readonly ResourceStatus DELETE_SKIPPED = new ResourceStatus("DELETE_SKIPPED"); /// <summary> /// Constant UPDATE_COMPLETE for ResourceStatus /// </summary> public static readonly ResourceStatus UPDATE_COMPLETE = new ResourceStatus("UPDATE_COMPLETE"); /// <summary> /// Constant UPDATE_FAILED for ResourceStatus /// </summary> public static readonly ResourceStatus UPDATE_FAILED = new ResourceStatus("UPDATE_FAILED"); /// <summary> /// Constant UPDATE_IN_PROGRESS for ResourceStatus /// </summary> public static readonly ResourceStatus UPDATE_IN_PROGRESS = new ResourceStatus("UPDATE_IN_PROGRESS"); /// <summary> /// Default Constructor /// </summary> public ResourceStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ResourceStatus FindValue(string value) { return FindValue<ResourceStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ResourceStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type StackStatus. /// </summary> public class StackStatus : ConstantClass { /// <summary> /// Constant CREATE_COMPLETE for StackStatus /// </summary> public static readonly StackStatus CREATE_COMPLETE = new StackStatus("CREATE_COMPLETE"); /// <summary> /// Constant CREATE_FAILED for StackStatus /// </summary> public static readonly StackStatus CREATE_FAILED = new StackStatus("CREATE_FAILED"); /// <summary> /// Constant CREATE_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus CREATE_IN_PROGRESS = new StackStatus("CREATE_IN_PROGRESS"); /// <summary> /// Constant DELETE_COMPLETE for StackStatus /// </summary> public static readonly StackStatus DELETE_COMPLETE = new StackStatus("DELETE_COMPLETE"); /// <summary> /// Constant DELETE_FAILED for StackStatus /// </summary> public static readonly StackStatus DELETE_FAILED = new StackStatus("DELETE_FAILED"); /// <summary> /// Constant DELETE_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus DELETE_IN_PROGRESS = new StackStatus("DELETE_IN_PROGRESS"); /// <summary> /// Constant ROLLBACK_COMPLETE for StackStatus /// </summary> public static readonly StackStatus ROLLBACK_COMPLETE = new StackStatus("ROLLBACK_COMPLETE"); /// <summary> /// Constant ROLLBACK_FAILED for StackStatus /// </summary> public static readonly StackStatus ROLLBACK_FAILED = new StackStatus("ROLLBACK_FAILED"); /// <summary> /// Constant ROLLBACK_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus ROLLBACK_IN_PROGRESS = new StackStatus("ROLLBACK_IN_PROGRESS"); /// <summary> /// Constant UPDATE_COMPLETE for StackStatus /// </summary> public static readonly StackStatus UPDATE_COMPLETE = new StackStatus("UPDATE_COMPLETE"); /// <summary> /// Constant UPDATE_COMPLETE_CLEANUP_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus UPDATE_COMPLETE_CLEANUP_IN_PROGRESS = new StackStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"); /// <summary> /// Constant UPDATE_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus UPDATE_IN_PROGRESS = new StackStatus("UPDATE_IN_PROGRESS"); /// <summary> /// Constant UPDATE_ROLLBACK_COMPLETE for StackStatus /// </summary> public static readonly StackStatus UPDATE_ROLLBACK_COMPLETE = new StackStatus("UPDATE_ROLLBACK_COMPLETE"); /// <summary> /// Constant UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS = new StackStatus("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"); /// <summary> /// Constant UPDATE_ROLLBACK_FAILED for StackStatus /// </summary> public static readonly StackStatus UPDATE_ROLLBACK_FAILED = new StackStatus("UPDATE_ROLLBACK_FAILED"); /// <summary> /// Constant UPDATE_ROLLBACK_IN_PROGRESS for StackStatus /// </summary> public static readonly StackStatus UPDATE_ROLLBACK_IN_PROGRESS = new StackStatus("UPDATE_ROLLBACK_IN_PROGRESS"); /// <summary> /// Default Constructor /// </summary> public StackStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static StackStatus FindValue(string value) { return FindValue<StackStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator StackStatus(string value) { return FindValue(value); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Configuration; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.BuildEngine.Shared; using Microsoft.Win32; namespace Microsoft.Build.UnitTests { /// <summary> /// Unit test for ToolsetRegistryReader class /// </summary> [TestFixture] public class ToolsetRegistryReader_Tests { // The registry key that is passed as the baseKey parameter to the ToolsetRegistryReader class private RegistryKey testRegistryKey = null; // Subkey "4.0" private RegistryKey currentVersionRegistryKey = null; // Subkey "ToolsVersions" private RegistryKey toolsVersionsRegistryKey = null; // Path to the registry key under HKCU // Note that this is a test registry key created solely for unit testing. private const string testRegistryPath = @"msbuildUnitTests"; /// <summary> /// Reset the testRegistryKey /// </summary> [SetUp] public void Setup() { DeleteTestRegistryKey(); testRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath); currentVersionRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath + "\\" + Constants.AssemblyVersion); toolsVersionsRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath + "\\ToolsVersions"); } [TearDown] public void TearDown() { DeleteTestRegistryKey(); } /// <summary> /// Helper class to delete the testRegistryKey tree. /// </summary> private void DeleteTestRegistryKey() { if (Registry.CurrentUser.OpenSubKey(testRegistryPath) != null) { Registry.CurrentUser.DeleteSubKeyTree(testRegistryPath); } } /// <summary> /// If the base key has been deleted, then we just don't get any information (no exception) /// </summary> [Test] public void ReadRegistry_DeletedKey() { DeleteTestRegistryKey(); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(0, values.Count); } /// <summary> /// Tests the tools version 4.0 is written to the the registry at install time /// </summary> [Test] public void DefaultValuesInRegistryCreatedBySetup() { ToolsetReader reader = new ToolsetRegistryReader(); //we don't use the test registry key because we want to verify the install ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); // Check the values in the data Assertion.Assert("Tools version 4.0 should be defined by default", values.Contains("4.0")); Assertion.AssertEquals("Default tools version should be 2.0", "2.0", defaultToolsVersion); if (FrameworkLocationHelper.PathToDotNetFrameworkV35 != null) { Assertion.Assert("Tools version 2.0 should be defined by default if .NET FX 3.5 exists on the machine.", values.Contains("2.0")); Assertion.Assert("Tools version 3.5 should be defined by default if .NET FX 3.5 exists on the machine.", values.Contains("3.5")); } } /// <summary> /// Tests we handle no default toolset specified in the registry /// </summary> [Test] public void DefaultValueInRegistryDoesNotExist() { ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath, "3.5" /* fail to find subkey 3.5 */)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); // Should not throw string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(null, defaultToolsVersion); } /// <summary> /// The base key exists but contains no subkey or values: this is okay /// </summary> [Test] public void ReadRegistry_NoSubkeyNoValues() { ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(0, values.Count); Assertion.AssertEquals(null, defaultToolsVersion); } /// <summary> /// Here we validate that MSBuild does not fail when there are unrecognized values underneath /// the ToolsVersion key. /// </summary> [Test] public void ReadRegistry_NoSubkeysOnlyValues() { toolsVersionsRegistryKey.SetValue("Name1", "Value1"); toolsVersionsRegistryKey.SetValue("Name2", "Value2"); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(0, values.Count); Assertion.AssertEquals(null, defaultToolsVersion); } /// <summary> /// Basekey has only 1 subkey /// </summary> [Test] public void ReadRegistry_OnlyOneSubkey() { RegistryKey key1 = toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(null, defaultToolsVersion); Assertion.AssertEquals(1, values.Count); Assertion.AssertEquals(0, values["tv1"].BuildProperties.Count); Assertion.Assert(0 == String.Compare("c:\\xxx", values["tv1"].ToolsPath, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Basic case /// </summary> [Test] public void ReadRegistry_Basic() { RegistryKey key1 = toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); key1.SetValue("name1", "value1"); RegistryKey key2 = toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("name2", "value2"); key2.SetValue("msbuildtoolspath", "c:\\yyy"); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(2, values.Count); Assertion.AssertEquals(1, values["tv1"].BuildProperties.Count); Assertion.Assert(0 == String.Compare("c:\\xxx", values["tv1"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assertion.Assert(0 == String.Compare("value1", values["tv1"].BuildProperties["name1"].Value, StringComparison.OrdinalIgnoreCase)); Assertion.AssertEquals(1, values["tv2"].BuildProperties.Count); Assertion.Assert(0 == String.Compare("c:\\yyy", values["tv2"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assertion.Assert(0 == String.Compare("value2", values["tv2"].BuildProperties["name2"].Value, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// baseKey contains some non-String data /// </summary> [Test] [ExpectedException(typeof(InvalidToolsetDefinitionException))] public void ReadRegistry_NonStringData() { RegistryKey key1 = toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); key1.SetValue("name1", "value1"); RegistryKey key2 = toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("msbuildtoolspath", "c:\\xxx"); key2.SetValue("name2", new String[] { "value2a", "value2b" }, RegistryValueKind.MultiString); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); } /// <summary> /// Registry has the following structure /// [HKCU]\basekey\ /// Key1 /// SubKey1 /// Key2 /// SubKey2 /// </summary> [Test] public void ReadRegistry_IgnoreSubKeysExceptTopMostSubKeys() { RegistryKey key1 = toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); key1.SetValue("name1", "value1"); RegistryKey subKey1 = key1.CreateSubKey("SubKey1"); subKey1.SetValue("name1a", "value1a"); subKey1.SetValue("name2a", "value2a"); RegistryKey key2 = toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("msbuildtoolspath", "c:\\yyy"); key2.SetValue("name2", "value2"); RegistryKey subKey2 = key2.CreateSubKey("SubKey2"); subKey2.SetValue("name3a", "value3a"); subKey2.SetValue("name2a", "value2a"); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(2, values.Count); Assertion.AssertEquals(1, values["tv1"].BuildProperties.Count); Assertion.Assert(0 == String.Compare("c:\\xxx", values["tv1"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assertion.Assert(0 == String.Compare("value1", values["tv1"].BuildProperties["name1"].Value, StringComparison.OrdinalIgnoreCase)); Assertion.AssertEquals(1, values["tv2"].BuildProperties.Count); Assertion.Assert(0 == String.Compare("c:\\yyy", values["tv2"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assertion.Assert(0 == String.Compare("value2", values["tv2"].BuildProperties["name2"].Value, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Regular case of getting default tools version /// </summary> [Test] public void GetDefaultToolsVersionFromRegistry_Basic() { currentVersionRegistryKey.SetValue("DefaultToolsVersion", "tv1"); RegistryKey key1 = toolsVersionsRegistryKey.CreateSubKey("tv1"); // Need matching tools version key1.SetValue("msbuildtoolspath", "c:\\xxx"); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals("tv1", defaultToolsVersion); } /// <summary> /// Default value is not set /// </summary> [Test] public void GetDefaultToolsVersionFromRegistry_DefaultValueNotSet() { ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); Assertion.AssertEquals(null, defaultToolsVersion); } /// <summary> /// "DefaultToolsVersion" has non-String data /// </summary> [Test] [ExpectedException(typeof(InvalidToolsetDefinitionException))] public void GetDefaultToolsVersionFromRegistry_NonStringData() { currentVersionRegistryKey.SetValue("DefaultToolsVersion", new String[] { "2.0.xxxx.a", "2.0.xxxx.b" }, RegistryValueKind.MultiString); ToolsetReader reader = new ToolsetRegistryReader(new MockRegistryKey(testRegistryPath)); ToolsetCollection values = new ToolsetCollection(new Engine(ToolsetDefinitionLocations.None)); string defaultToolsVersion = reader.ReadToolsets(values, new BuildPropertyGroup(), new BuildPropertyGroup(), false); } } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using Microsoft.Win32.SafeHandles; using System; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Security.AccessControl; using System.Security.Principal; namespace Thrift.Transport.Server { // ReSharper disable once InconsistentNaming public class TNamedPipeServerTransport : TServerTransport { /// <summary> /// This is the address of the Pipe on the localhost. /// </summary> private readonly string _pipeAddress; private bool _asyncMode = true; private volatile bool _isPending = true; private NamedPipeServerStream _stream = null; public TNamedPipeServerTransport(string pipeAddress) { _pipeAddress = pipeAddress; } public override void Listen() { // nothing to do here } public override void Close() { if (_stream != null) { try { if (_stream.IsConnected) _stream.Disconnect(); _stream.Dispose(); } finally { _stream = null; _isPending = false; } } } public override bool IsClientPending() { return _isPending; } private void EnsurePipeInstance() { if (_stream == null) { const PipeDirection direction = PipeDirection.InOut; const int maxconn = NamedPipeServerStream.MaxAllowedServerInstances; const PipeTransmissionMode mode = PipeTransmissionMode.Byte; const int inbuf = 4096; const int outbuf = 4096; var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; // TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes: // - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative() // - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative() // EITHER WAY, // - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings try { var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf); if( (handle != null) && (!handle.IsInvalid)) _stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle); else _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf/*, pipesec*/); } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (_asyncMode) { options &= (~PipeOptions.Asynchronous); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); _asyncMode = false; } else { throw; } } } } #region CreatePipeNative workaround [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; internal IntPtr lpSecurityDescriptor = IntPtr.Zero; internal int bInheritHandle = 0; } private const string Kernel32 = "kernel32.dll"; [DllImport(Kernel32, SetLastError = true)] internal static extern IntPtr CreateNamedPipe( string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, SECURITY_ATTRIBUTES pipeSecurityDescriptor ); // Workaround: create the pipe via API call // we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs // and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us // References: // - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190) // - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work // - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC // - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) return null; // Windows only var pinningHandle = new GCHandle(); try { // owner gets full access, everyone else read/write var pipesec = new PipeSecurity(); using (var currentIdentity = WindowsIdentity.GetCurrent()) { var sidOwner = currentIdentity.Owner; var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null); pipesec.SetOwner(sidOwner); pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow)); pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow)); } // create a security descriptor and assign it to the security attribs var secAttrs = new SECURITY_ATTRIBUTES(); byte[] sdBytes = pipesec.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned); unsafe { fixed (byte* pSD = sdBytes) { secAttrs.lpSecurityDescriptor = (IntPtr)pSD; } } // a bunch of constants we will need shortly const int PIPE_ACCESS_DUPLEX = 0x00000003; const int FILE_FLAG_OVERLAPPED = 0x40000000; const int WRITE_DAC = 0x00040000; const int PIPE_TYPE_BYTE = 0x00000000; const int PIPE_READMODE_BYTE = 0x00000000; const int PIPE_UNLIMITED_INSTANCES = 255; // create the pipe via API call var rawHandle = CreateNamedPipe( @"\\.\pipe\" + name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf, 5 * 1000, secAttrs ); // make a SafePipeHandle() from it var handle = new SafePipeHandle(rawHandle, true); if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); // return it (to be packaged) return handle; } finally { if (pinningHandle.IsAllocated) pinningHandle.Free(); } } #endregion protected override async Task<TTransport> AcceptImplementationAsync(CancellationToken cancellationToken) { try { EnsurePipeInstance(); await _stream.WaitForConnectionAsync(cancellationToken); var trans = new ServerTransport(_stream); _stream = null; // pass ownership to ServerTransport //_isPending = false; return trans; } catch (TTransportException) { Close(); throw; } catch (Exception e) { Close(); throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); } } private class ServerTransport : TTransport { private readonly NamedPipeServerStream _stream; public ServerTransport(NamedPipeServerStream stream) { _stream = stream; } public override bool IsOpen => _stream != null && _stream.IsConnected; public override async Task OpenAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override void Close() { _stream?.Dispose(); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (_stream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } return await _stream.ReadAsync(buffer, offset, length, cancellationToken); } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (_stream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } await _stream.WriteAsync(buffer, offset, length, cancellationToken); } public override async Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } protected override void Dispose(bool disposing) { _stream?.Dispose(); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A lodging business, such as a motel, hotel, or inn. /// </summary> public class LodgingBusiness_Core : TypeCore, ILocalBusiness { public LodgingBusiness_Core() { this._TypeId = 157; this._Id = "LodgingBusiness"; this._Schema_Org_Url = "http://schema.org/LodgingBusiness"; string label = ""; GetLabel(out label, "LodgingBusiness", typeof(LodgingBusiness_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[]{36,131,132,154}; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using k8s.Tests.Logging; using k8s.Tests.Mock.Server; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using k8s.Autorest; using System; using System.IO; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace k8s.Tests { /// <summary> /// The base class for Kubernetes WebSocket test suites. /// </summary> public abstract class WebSocketTestBase : IDisposable { /// <summary> /// The next server port to use. /// </summary> private static int nextPort = 13255; private bool disposedValue; private readonly ITestOutputHelper testOutput; /// <summary> /// Initializes a new instance of the <see cref="WebSocketTestBase"/> class. /// Create a new <see cref="WebSocketTestBase"/>. /// </summary> /// <param name="testOutput"> /// Output for the current test. /// </param> protected WebSocketTestBase(ITestOutputHelper testOutput) { this.testOutput = testOutput; int port = Interlocked.Increment(ref nextPort); // Useful to diagnose test timeouts. TestCancellation.Register( () => testOutput.WriteLine("Test-level cancellation token has been canceled.")); ServerBaseAddress = new Uri($"http://localhost:{port}"); WebSocketBaseAddress = new Uri($"ws://localhost:{port}"); Host = WebHost.CreateDefaultBuilder() .UseStartup<Startup>() .ConfigureServices(ConfigureTestServerServices) .ConfigureLogging(ConfigureTestServerLogging) .UseUrls(ServerBaseAddress.AbsoluteUri) .Build(); } /// <summary> /// The test server's base address (http://). /// </summary> protected Uri ServerBaseAddress { get; } /// <summary> /// The test server's base WebSockets address (ws://). /// </summary> protected Uri WebSocketBaseAddress { get; } /// <summary> /// The test server's web host. /// </summary> protected IWebHost Host { get; } /// <summary> /// Test adapter for accepting web sockets. /// </summary> protected WebSocketTestAdapter WebSocketTestAdapter { get; } = new WebSocketTestAdapter(); /// <summary> /// The source for cancellation tokens used by the test. /// </summary> protected CancellationTokenSource CancellationSource { get; } = new CancellationTokenSource(); /// <summary> /// A <see cref="CancellationToken"/> that can be used to cancel asynchronous operations. /// </summary> /// <seealso cref="CancellationSource"/> protected CancellationToken TestCancellation => CancellationSource.Token; /// <summary> /// Configure services for the test server. /// </summary> /// <param name="services"> /// The service collection to configure. /// </param> protected virtual void ConfigureTestServerServices(IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } // Inject WebSocketTestData. services.AddSingleton(WebSocketTestAdapter); } /// <summary> /// Configure logging for the test server. /// </summary> /// <param name="services"> /// The logger factory to configure. /// </param> protected virtual void ConfigureTestServerLogging(ILoggingBuilder logging) { if (logging == null) { throw new ArgumentNullException(nameof(logging)); } logging.ClearProviders(); // Don't log to console. logging.AddTestOutput(testOutput, LogLevel.Information); } /// <summary> /// Create a Kubernetes client that uses the test server. /// </summary> /// <param name="credentials"> /// Optional <see cref="ServiceClientCredentials"/> to use for authentication (defaults to anonymous, i.e. no credentials). /// </param> /// <returns> /// The configured client. /// </returns> protected virtual Kubernetes CreateTestClient(ServiceClientCredentials credentials = null) { return new Kubernetes(new KubernetesClientConfiguration() { Host = ServerBaseAddress.ToString(), }); } /// <summary> /// Asynchronously disconnect client and server WebSockets using the standard handshake. /// </summary> /// <param name="clientSocket"> /// The client-side <see cref="WebSocket"/>. /// </param> /// <param name="serverSocket"> /// The server-side <see cref="WebSocket"/>. /// </param> /// <param name="closeStatus"> /// An optional <see cref="WebSocketCloseStatus"/> value indicating the reason for disconnection. /// /// Defaults to <see cref="WebSocketCloseStatus.NormalClosure"/>. /// </param> /// <param name="closeStatusDescription"> /// An optional textual description of the reason for disconnection. /// /// Defaults to "Normal Closure". /// </param> /// <returns> /// A <see cref="Task"/> representing the asynchronous operation. /// </returns> protected async Task Disconnect(WebSocket clientSocket, WebSocket serverSocket, WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure, string closeStatusDescription = "Normal Closure") { if (clientSocket == null) { throw new ArgumentNullException(nameof(clientSocket)); } if (serverSocket == null) { throw new ArgumentNullException(nameof(serverSocket)); } testOutput.WriteLine("Disconnecting..."); // Asynchronously perform the server's half of the handshake (the call to clientSocket.CloseAsync will block until it receives the server-side response). ArraySegment<byte> receiveBuffer = new byte[1024]; Task closeServerSocket = serverSocket.ReceiveAsync(receiveBuffer, TestCancellation) .ContinueWith(async received => { if (received.IsFaulted) { testOutput.WriteLine( "Server socket operation to receive Close message failed: {0}", received.Exception.Flatten().InnerExceptions[0]); } else if (received.IsCanceled) { testOutput.WriteLine("Server socket operation to receive Close message was canceled."); } else { testOutput.WriteLine( $"Received {received.Result.MessageType} message from server socket (expecting {WebSocketMessageType.Close})."); if (received.Result.MessageType == WebSocketMessageType.Close) { testOutput.WriteLine( $"Closing server socket (with status {received.Result.CloseStatus})..."); await serverSocket.CloseAsync( received.Result.CloseStatus.Value, received.Result.CloseStatusDescription, TestCancellation).ConfigureAwait(false); testOutput.WriteLine("Server socket closed."); } Assert.Equal(WebSocketMessageType.Close, received.Result.MessageType); } }); testOutput.WriteLine("Closing client socket..."); await clientSocket.CloseAsync(closeStatus, closeStatusDescription, TestCancellation).ConfigureAwait(false); testOutput.WriteLine("Client socket closed."); await closeServerSocket.ConfigureAwait(false); testOutput.WriteLine("Disconnected."); Assert.Equal(closeStatus, clientSocket.CloseStatus); Assert.Equal(clientSocket.CloseStatus, serverSocket.CloseStatus); Assert.Equal(closeStatusDescription, clientSocket.CloseStatusDescription); Assert.Equal(clientSocket.CloseStatusDescription, serverSocket.CloseStatusDescription); } /// <summary> /// Send text to a multiplexed substream over the specified WebSocket. /// </summary> /// <param name="webSocket"> /// The target <see cref="WebSocket"/>. /// </param> /// <param name="streamIndex"> /// The 0-based index of the target substream. /// </param> /// <param name="text"> /// The text to send. /// </param> /// <returns> /// The number of bytes sent to the WebSocket. /// </returns> protected async Task<int> SendMultiplexed(WebSocket webSocket, byte streamIndex, string text) { if (webSocket == null) { throw new ArgumentNullException(nameof(webSocket)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } byte[] payload = Encoding.ASCII.GetBytes(text); byte[] sendBuffer = new byte[payload.Length + 1]; sendBuffer[0] = streamIndex; Array.Copy(payload, 0, sendBuffer, 1, payload.Length); await webSocket.SendAsync(sendBuffer, WebSocketMessageType.Binary, true, TestCancellation).ConfigureAwait(false); return sendBuffer.Length; } /// <summary> /// Receive text from a multiplexed substream over the specified WebSocket. /// </summary> /// <param name="webSocket"> /// The target <see cref="WebSocket"/>. /// </param> /// <param name="text"> /// The text to send. /// </param> /// <returns> /// A tuple containing the received text, 0-based substream index, and total bytes received. /// </returns> protected async Task<(string text, byte streamIndex, int totalBytes)> ReceiveTextMultiplexed( WebSocket webSocket) { if (webSocket == null) { throw new ArgumentNullException(nameof(webSocket)); } byte[] receivedData; using (MemoryStream buffer = new MemoryStream()) { byte[] receiveBuffer = new byte[1024]; WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(receiveBuffer, TestCancellation).ConfigureAwait(false); if (receiveResult.MessageType != WebSocketMessageType.Binary) { throw new IOException( $"Received unexpected WebSocket message of type '{receiveResult.MessageType}'."); } buffer.Write(receiveBuffer, 0, receiveResult.Count); while (!receiveResult.EndOfMessage) { receiveResult = await webSocket.ReceiveAsync(receiveBuffer, TestCancellation).ConfigureAwait(false); buffer.Write(receiveBuffer, 0, receiveResult.Count); } buffer.Flush(); receivedData = buffer.ToArray(); } return ( text: Encoding.ASCII.GetString(receivedData, 1, receivedData.Length - 1), streamIndex: receivedData[0], totalBytes: receivedData.Length); } /// <summary> /// A <see cref="ServiceClientCredentials"/> implementation representing no credentials (i.e. anonymous). /// </summary> protected class AnonymousClientCredentials : ServiceClientCredentials { /// <summary> /// The singleton instance of <see cref="AnonymousClientCredentials"/>. /// </summary> public static readonly AnonymousClientCredentials Instance = new AnonymousClientCredentials(); /// <summary> /// Initializes a new instance of the <see cref="AnonymousClientCredentials"/> class. /// Create new <see cref="AnonymousClientCredentials"/>. /// </summary> private AnonymousClientCredentials() { } } /// <summary> /// Event Id constants used in WebSocket tests. /// </summary> protected static class EventIds { /// <summary> /// An error occurred while closing the server-side socket. /// </summary> private static readonly EventId ErrorClosingServerSocket = new EventId(1000, nameof(ErrorClosingServerSocket)); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { CancellationSource.Dispose(); Host.Dispose(); } disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~WebSocketTestBase() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(true); GC.SuppressFinalize(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ProducerConsumerQueues.cs // // // Specialized producer/consumer queues. // // // ************<IMPORTANT NOTE>************* // // There are two exact copies of this file: // src\ndp\clr\src\bcl\system\threading\tasks\producerConsumerQueue.cs // src\ndp\fx\src\dataflow\system\threading\tasks\dataflow\internal\producerConsumerQueue.cs // Keep both of them consistent by changing the other file when you change this one, also avoid: // 1- To reference interneal types in mscorlib // 2- To reference any dataflow specific types // This should be fixed post Dev11 when this class becomes public. // // ************</IMPORTANT NOTE>************* // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace System.Threading.Tasks { /// <summary>Represents a producer/consumer queue used internally by dataflow blocks.</summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> internal interface IProducerConsumerQueue<T> : IEnumerable<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> void Enqueue(T item); /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> bool TryDequeue(out T result); /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>This method may or may not be thread-safe.</remarks> bool IsEmpty { get; } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>In many implementations, this method will not be thread-safe.</remarks> int Count { get; } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <param name="syncObj">The sync object used to lock</param> /// <returns>The collection count</returns> int GetCountSafe(object syncObj); } /// <summary> /// Provides a producer/consumer queue safe to be used by any number of producers and consumers concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] internal sealed class MultiProducerMultiConsumerQueue<T> : LowLevelConcurrentQueue<T>, IProducerConsumerQueue<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> void IProducerConsumerQueue<T>.Enqueue(T item) { base.Enqueue(item); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> bool IProducerConsumerQueue<T>.TryDequeue(out T result) { return base.TryDequeue(out result); } /// <summary>Gets whether the collection is currently empty.</summary> bool IProducerConsumerQueue<T>.IsEmpty { get { return base.IsEmpty; } } /// <summary>Gets the number of items in the collection.</summary> int IProducerConsumerQueue<T>.Count { get { return base.Count; } } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <remarks>ConcurrentQueue.Count is thread safe, no need to acquire the lock.</remarks> int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { return base.Count; } } /// <summary> /// Provides a producer/consumer queue safe to be used by only one producer and one consumer concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T> { // Design: // // SingleProducerSingleConsumerQueue (SPSCQueue) is a concurrent queue designed to be used // by one producer thread and one consumer thread. SPSCQueue does not work correctly when used by // multiple producer threads concurrently or multiple consumer threads concurrently. // // SPSCQueue is based on segments that behave like circular buffers. Each circular buffer is represented // as an array with two indexes: m_first and m_last. m_first is the index of the array slot for the consumer // to read next, and m_last is the slot for the producer to write next. The circular buffer is empty when // (m_first == m_last), and full when ((m_last+1) % m_array.Length == m_first). // // Since m_first is only ever modified by the consumer thread and m_last by the producer, the two indices can // be updated without interlocked operations. As long as the queue size fits inside a single circular buffer, // enqueues and dequeues simply advance the corresponding indices around the circular buffer. If an enqueue finds // that there is no room in the existing buffer, however, a new circular buffer is allocated that is twice as big // as the old buffer. From then on, the producer will insert values into the new buffer. The consumer will first // empty out the old buffer and only then follow the producer into the new (larger) buffer. // // As described above, the enqueue operation on the fast path only modifies the m_first field of the current segment. // However, it also needs to read m_last in order to verify that there is room in the current segment. Similarly, the // dequeue operation on the fast path only needs to modify m_last, but also needs to read m_first to verify that the // queue is non-empty. This results in true cache line sharing between the producer and the consumer. // // The cache line sharing issue can be mitigating by having a possibly stale copy of m_first that is owned by the producer, // and a possibly stale copy of m_last that is owned by the consumer. So, the consumer state is described using // (m_first, m_lastCopy) and the producer state using (m_firstCopy, m_last). The consumer state is separated from // the producer state by padding, which allows fast-path enqueues and dequeues from hitting shared cache lines. // m_lastCopy is the consumer's copy of m_last. Whenever the consumer can tell that there is room in the buffer // simply by observing m_lastCopy, the consumer thread does not need to read m_last and thus encounter a cache miss. Only // when the buffer appears to be empty will the consumer refresh m_lastCopy from m_last. m_firstCopy is used by the producer // in the same way to avoid reading m_first on the hot path. /// <summary>The initial size to use for segments (in number of elements).</summary> private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2 /// <summary>The maximum size to use for segments (in number of elements).</summary> private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as Int32.MaxValue / 2 /// <summary>The head of the linked list of segments.</summary> private volatile Segment m_head; /// <summary>The tail of the linked list of segments.</summary> private volatile Segment m_tail; /// <summary>Initializes the queue.</summary> internal SingleProducerSingleConsumerQueue() { // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> public void Enqueue(T item) { Segment segment = m_tail; var array = segment.m_array; int last = segment.m_state.m_last; // local copy to avoid multiple volatile reads // Fast path: there's obviously room in the current segment int tail2 = (last + 1) & (array.Length - 1); if (tail2 != segment.m_state.m_firstCopy) { array[last] = item; segment.m_state.m_last = tail2; } // Slow path: there may not be room in the current segment. else EnqueueSlow(item, ref segment); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <param name="segment">The segment in which to first attempt to store the item.</param> private void EnqueueSlow(T item, ref Segment segment) { Contract.Requires(segment != null, "Expected a non-null segment."); if (segment.m_state.m_firstCopy != segment.m_state.m_first) { segment.m_state.m_firstCopy = segment.m_state.m_first; Enqueue(item); // will only recur once for this enqueue operation return; } int newSegmentSize = m_tail.m_array.Length << 1; // double size Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE; var newSegment = new Segment(newSegmentSize); newSegment.m_array[0] = item; newSegment.m_state.m_last = 1; newSegment.m_state.m_lastCopy = 1; try { } finally { // Finally block to protect against corruption due to a thread abort // between setting m_next and setting m_tail. Volatile.Write(ref m_tail.m_next, newSegment); // ensure segment not published until item is fully stored m_tail = newSegment; } } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> public bool TryDequeue(out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } // Slow path: there may not be data available in the current segment else return TryDequeueSlow(ref segment, ref array, out result); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="array">The array from which the item was dequeued.</param> /// <param name="segment">The segment from which the item was dequeued.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> private bool TryDequeueSlow(ref Segment segment, ref T[] array, out T result) { Contract.Requires(segment != null, "Expected a non-null segment."); Contract.Requires(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeue(out result); // will only recur once for this dequeue operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy return true; } /// <summary>Attempts to peek at an item in the queue.</summary> /// <param name="result">The peeked item.</param> /// <returns>true if an item could be peeked; otherwise, false.</returns> public bool TryPeek(out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; return true; } // Slow path: there may not be data available in the current segment else return TryPeekSlow(ref segment, ref array, out result); } /// <summary>Attempts to peek at an item in the queue.</summary> /// <param name="array">The array from which the item is peeked.</param> /// <param name="segment">The segment from which the item is peeked.</param> /// <param name="result">The peeked item.</param> /// <returns>true if an item could be peeked; otherwise, false.</returns> private bool TryPeekSlow(ref Segment segment, ref T[] array, out T result) { Contract.Requires(segment != null, "Expected a non-null segment."); Contract.Requires(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryPeek(out result); // will only recur once for this peek operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; return true; } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> public bool TryDequeueIf(Predicate<T> predicate, out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } else { result = default(T); return false; } } // Slow path: there may not be data available in the current segment else return TryDequeueIfSlow(predicate, ref segment, ref array, out result); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param> /// <param name="array">The array from which the item was dequeued.</param> /// <param name="segment">The segment from which the item was dequeued.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> private bool TryDequeueIfSlow(Predicate<T> predicate, ref Segment segment, ref T[] array, out T result) { Contract.Requires(segment != null, "Expected a non-null segment."); Contract.Requires(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeueIf(predicate, out result); // will only recur once for this dequeue operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy return true; } else { result = default(T); return false; } } public void Clear() { T ignored; while (TryDequeue(out ignored)) ; } /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks> public bool IsEmpty { // This implementation is optimized for calls from the consumer. get { var head = m_head; if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered if (head.m_state.m_first != head.m_state.m_last) return false; return head.m_next == null; } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> public IEnumerator<T> GetEnumerator() { for (Segment segment = m_head; segment != null; segment = segment.m_next) { for (int pt = segment.m_state.m_first; pt != segment.m_state.m_last; pt = (pt + 1) & (segment.m_array.Length - 1)) { yield return segment.m_array[pt]; } } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not meant to be used concurrently.</remarks> public int Count { get { int count = 0; for (Segment segment = m_head; segment != null; segment = segment.m_next) { int arraySize = segment.m_array.Length; int first, last; while (true) // Count is not meant to be used concurrently, but this helps to avoid issues if it is { first = segment.m_state.m_first; last = segment.m_state.m_last; if (first == segment.m_state.m_first) break; } count += (last - first) & (arraySize - 1); } return count; } } /// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary> /// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks> int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { Contract.Assert(syncObj != null, "The syncObj parameter is null."); lock (syncObj) { return Count; } } /// <summary>A segment in the queue containing one or more items.</summary> [StructLayout(LayoutKind.Sequential)] private sealed class Segment { /// <summary>The next segment in the linked list of segments.</summary> internal Segment m_next; /// <summary>The data stored in this segment.</summary> internal readonly T[] m_array; /// <summary>Details about the segment.</summary> internal SegmentState m_state; // separated out to enable StructLayout attribute to take effect /// <summary>Initializes the segment.</summary> /// <param name="size">The size to use for this segment.</param> internal Segment(int size) { Contract.Requires((size & (size - 1)) == 0, "Size must be a power of 2"); m_array = new T[size]; } } /// <summary>Stores information about a segment.</summary> [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing private struct SegmentState { /// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary> internal PaddingFor32 m_pad0; /// <summary>The index of the current head in the segment.</summary> internal volatile int m_first; /// <summary>A copy of the current tail index.</summary> internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first /// <summary>Padding to reduce false sharing between the first and last.</summary> internal PaddingFor32 m_pad1; /// <summary>A copy of the current head index.</summary> internal int m_firstCopy; // not voliatle as only read and written by the consumer thread /// <summary>The index of the current tail in the segment.</summary> internal volatile int m_last; /// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary> internal PaddingFor32 m_pad2; } /// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary> private sealed class SingleProducerSingleConsumerQueue_DebugView { /// <summary>The queue being visualized.</summary> private readonly SingleProducerSingleConsumerQueue<T> m_queue; /// <summary>Initializes the debug view.</summary> /// <param name="enumerable">The queue being debugged.</param> public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { Contract.Requires(queue != null, "Expected a non-null queue."); m_queue = queue; } /// <summary>Gets the contents of the list.</summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { List<T> list = new List<T>(); foreach (T item in m_queue) list.Add(item); return list.ToArray(); } } } } /// <summary>A placeholder class for common padding constants and eventually routines.</summary> static class PaddingHelpers { /// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary> internal const int CACHE_LINE_SIZE = 128; } /// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary> [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines struct PaddingFor32 { } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.AudioBeam // public sealed partial class AudioBeam : Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal AudioBeam(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_AudioBeam_AddRefObject(ref _pNative); } ~AudioBeam() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_AudioBeam_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_AudioBeam_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<AudioBeam>(_pNative); Windows_Kinect_AudioBeam_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern Windows.Kinect.AudioBeamMode Windows_Kinect_AudioBeam_get_AudioBeamMode(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_AudioBeam_put_AudioBeamMode(RootSystem.IntPtr pNative, Windows.Kinect.AudioBeamMode audioBeamMode); public Windows.Kinect.AudioBeamMode AudioBeamMode { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } return Windows_Kinect_AudioBeam_get_AudioBeamMode(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } Windows_Kinect_AudioBeam_put_AudioBeamMode(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_AudioBeam_get_AudioSource(RootSystem.IntPtr pNative); public Windows.Kinect.AudioSource AudioSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } RootSystem.IntPtr objectPointer = Windows_Kinect_AudioBeam_get_AudioSource(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.AudioSource>(objectPointer, n => new Windows.Kinect.AudioSource(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern float Windows_Kinect_AudioBeam_get_BeamAngle(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_AudioBeam_put_BeamAngle(RootSystem.IntPtr pNative, float beamAngle); public float BeamAngle { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } return Windows_Kinect_AudioBeam_get_BeamAngle(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } Windows_Kinect_AudioBeam_put_BeamAngle(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern float Windows_Kinect_AudioBeam_get_BeamAngleConfidence(RootSystem.IntPtr pNative); public float BeamAngleConfidence { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } return Windows_Kinect_AudioBeam_get_BeamAngleConfidence(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern long Windows_Kinect_AudioBeam_get_RelativeTime(RootSystem.IntPtr pNative); public RootSystem.TimeSpan RelativeTime { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("AudioBeam"); } return RootSystem.TimeSpan.FromMilliseconds(Windows_Kinect_AudioBeam_get_RelativeTime(_pNative)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<AudioBeam>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_AudioBeam_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_AudioBeam_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_AudioBeam_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods private void __EventCleanup() { { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_AudioBeam_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Ports.Tests { public class ReadLine_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random bytes to receive for parity testing private const int numRndBytesPairty = 8; //The number of characters to read at a time for parity testing private const int numBytesReadPairty = 2; //The number of random bytes to receive for BytesToRead testing private const int numRndBytesToRead = 16; //The number of new lines to insert into the string not including the one at the end //For BytesToRead testing private const int DEFAULT_NUMBER_NEW_LINES = 2; private const byte DEFAULT_NEW_LINE = (byte)'\n'; private const int NUM_TRYS = 5; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadLine()); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); Thread t = new Thread(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadLine(); } catch (TimeoutException) { } //Wait for the thread to finish while (t.IsAlive) Thread.Sleep(50); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.WriteLine(""); } } [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1)); } [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndBytesPairty]; char[] expectedChars = new char[numRndBytesPairty]; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com2.Write(com1.NewLine); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + com1.NewLine.Length); string strRead = com1.ReadLine(); char[] actualChars = strRead.ToCharArray(); Assert.Equal(expectedChars, actualChars); if (1 < com1.BytesToRead) { Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); } com1.DiscardInBuffer(); bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_1_Buffer_Size() { VerifyBytesToRead(1); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_Equal_Buffer_Size() { VerifyBytesToRead(numRndBytesToRead); } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; Assert.Throws<TimeoutException>(() => com.ReadLine()); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadLine()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadLine()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte char[] expectedChars = new char[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte byte expectedByte; //Genrate random characters without an parity error for (int i = 0; i < numRndBytesPairty; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedByte = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedByte = bytesToWrite[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedByte = (byte)parityReplace; } //Create an parity error by setting the highest order bit to true bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); expectedChars[parityErrorIndex] = (char)expectedByte; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); bytesToWrite[numRndBytesPairty] = DEFAULT_NEW_LINE; expectedChars[numRndBytesPairty] = (char)DEFAULT_NEW_LINE; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } private void VerifyBytesToRead(int numBytesRead) { VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); } private void VerifyBytesToRead(int numBytesRead, int numNewLines) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte ASCIIEncoding encoding = new ASCIIEncoding(); //Genrate random characters for (int i = 0; i < numBytesRead; i++) { byte randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); for (int i = 0; i < numNewLines; i++) { int newLineIndex; newLineIndex = rndGen.Next(0, numBytesRead); bytesToWrite[newLineIndex] = (byte)'\n'; expectedChars[newLineIndex] = (char)'\n'; } Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); com1.Open(); com2.Open(); bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] actualChars = new char[expectedChars.Length]; int totalBytesRead; int totalCharsRead; int bytesToRead; int lastIndexOfNewLine = -1; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; totalCharsRead = 0; bytesToRead = com1.BytesToRead; while (true) { string rcvString; try { rcvString = com1.ReadLine(); } catch (TimeoutException) { break; } //While their are more characters to be read char[] rcvBuffer = rcvString.ToCharArray(); int charsRead = rcvBuffer.Length; int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); int indexOfNewLine = Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); if (indexOfNewLine - (lastIndexOfNewLine + 1) != charsRead) { //If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead); } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); actualChars[totalCharsRead + charsRead] = (char)DEFAULT_NEW_LINE; //Add the NewLine char into actualChars totalBytesRead += bytesRead + 1; //Plus 1 because we read the NewLine char totalCharsRead += charsRead + 1; //Plus 1 because we read the NewLine char lastIndexOfNewLine = indexOfNewLine; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; } //End while there are more characters to read //Compare the chars that were written with the ones we expected to read Assert.Equal(expectedChars, actualChars); } #endregion } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Microsoft.Research.Naiad.Dataflow { /// <summary> /// Represents an output of a vertex, to which zero or more <see cref="SendChannel{TRecord,TTime}"/> (receivers) /// can be added. /// </summary> /// <typeparam name="TRecord">The type of records produced by this output.</typeparam> /// <typeparam name="TTime">The type of timestamp on the records produced by this output.</typeparam> public interface VertexOutput<TRecord, TTime> where TTime : Time<TTime> { /// <summary> /// The vertex hosting the output. /// </summary> Dataflow.Vertex Vertex { get; } /// <summary> /// Adds the given receiver to those that will be informed of every messages sent on this output. /// </summary> /// <param name="receiver">A receiver of messages.</param> void AddReceiver(SendChannel<TRecord, TTime> receiver); } /// <summary> /// Defines the input of a vertex, which must process messages and manage re-entrancy for the runtime. /// </summary> /// <typeparam name="TRecord">The type of records accepted by thie input.</typeparam> /// <typeparam name="TTime">The type of timestamp on the records accepted by this input.</typeparam> public interface VertexInput<TRecord, TTime> where TTime : Time<TTime> { /// <summary> /// Reports and sets the status of logging; infrequently supported. /// </summary> bool LoggingEnabled { get; set; } /// <summary> /// Indicates whether the destination vertex can be currently re-entered. Decremented and incremented by Naiad. /// </summary> int AvailableEntrancy { get; set; } /// <summary> /// The vertex hosting the input. /// </summary> Dataflow.Vertex Vertex { get; } /// <summary> /// Ensures that before returning all messages are sent and all progress traffic has been presented to the worker. /// </summary> void Flush(); /// <summary> /// Callback for a message containing several records. /// </summary> /// <param name="message">the message</param> /// <param name="from">the source of the message</param> void OnReceive(Message<TRecord, TTime> message, ReturnAddress from); /// <summary> /// Callback for a serialized message. /// </summary> /// <param name="message">the serialized message</param> /// <param name="from">the source of the serialized message</param> void SerializedMessageReceived(SerializedMessage message, ReturnAddress from); } #region StageInput and friends /// <summary> /// Represents an input to a dataflow stage. /// </summary> /// <typeparam name="TRecord">record type</typeparam> /// <typeparam name="TTime">time type</typeparam> public class StageInput<TRecord, TTime> where TTime : Time<TTime> { internal readonly Stage ForStage; internal readonly Expression<Func<TRecord, int>> PartitionedBy; private readonly Dictionary<int, VertexInput<TRecord, TTime>> endpointMap; internal void Register(VertexInput<TRecord, TTime> endpoint) { this.endpointMap[endpoint.Vertex.VertexId] = endpoint; } internal VertexInput<TRecord, TTime> GetPin(int index) { if (endpointMap.ContainsKey(index)) return endpointMap[index]; else throw new Exception("Error in StageInput.GetPin()"); } /// <summary> /// Returns a string representation of this stage input. /// </summary> /// <returns>A string representation of this stage input.</returns> public override string ToString() { return String.Format("StageInput[{0}]", this.ForStage); } internal StageInput(Stage stage, Expression<Func<TRecord, int>> partitionedBy) { this.PartitionedBy = partitionedBy; this.ForStage = stage; this.endpointMap = new Dictionary<int, VertexInput<TRecord, TTime>>(); } internal StageInput(Stage stage) : this(stage, null) { } } #if false public class RecvFiberSpillBank<S, T> : VertexInput<S, T>, ICheckpointable where T : Time<T> { private int channelId; public int ChannelId { get { return this.channelId; } set { this.channelId = value; } } public bool LoggingEnabled { get { return false; } set { throw new NotImplementedException("Logging for RecvFiberSpillBank"); } } public int AvailableEntrancy { get { return this.Vertex.Entrancy; } set { this.Vertex.Entrancy = value; } } private SpillFile<Pair<S, T>> spillFile; private readonly Vertex<T> vertex; public IEnumerable<Pair<S, T>> GetRecords() { Pair<S, T> record; while (this.spillFile.TryGetNextElement(out record)) yield return record; } public RecvFiberSpillBank(Vertex<T> vertex) : this(vertex, 1 << 20) { } public RecvFiberSpillBank(Vertex<T> vertex, int bufferSize) { this.vertex = vertex; this.spillFile = new SpillFile<Pair<S, T>>(System.IO.Path.GetRandomFileName(), bufferSize, new AutoSerializedMessageEncoder<S, T>(1, 1, DummyBufferPool<byte>.Pool, vertex.Stage.InternalGraphManager.Controller.Configuration.SendPageSize, vertex.CodeGenerator), new AutoSerializedMessageDecoder<S, T>(vertex.CodeGenerator), vertex.Stage.InternalGraphManager.Controller.Configuration.SendPageSize, vertex.CodeGenerator.GetSerializer<MessageHeader>()); } public Microsoft.Research.Naiad.Dataflow.Vertex Vertex { get { return this.vertex; } } public void Flush() { this.spillFile.Flush(); } public void RecordReceived(Pair<S, T> record, RemotePostbox sender) { this.spillFile.Write(record); this.vertex.NotifyAt(record.v2); } public void MessageReceived(Message<S, T> message, RemotePostbox sender) { for (int i = 0; i < message.length; ++i) this.RecordReceived(message.payload[i].PairWith(message.time), sender); } private AutoSerializedMessageDecoder<S, T> decoder = null; public void SerializedMessageReceived(SerializedMessage serializedMessage, RemotePostbox sender) { if (this.decoder == null) this.decoder = new AutoSerializedMessageDecoder<S, T>(this.Vertex.CodeGenerator); foreach (Message<S, T> message in this.decoder.AsTypedMessages(serializedMessage)) { this.MessageReceived(message, sender); message.Release(); } } public override string ToString() { return string.Format("<{0}L>", this.vertex.Stage.StageId); } public void Restore(NaiadReader reader) { throw new NotImplementedException(); } public void Checkpoint(NaiadWriter writer) { throw new NotImplementedException(); } public virtual bool Stateful { get { return true; } } } #endif internal abstract class Receiver<S, T> : VertexInput<S, T> where T : Time<T> { private int channelId; public int ChannelId { get { return this.channelId; } set { this.channelId = value; } } private bool loggingEnabled = false; public bool LoggingEnabled { get { return this.loggingEnabled; } set { this.loggingEnabled = value; } } public int AvailableEntrancy { get { return this.Vertex.Entrancy; } set { this.Vertex.Entrancy = value; } } protected Vertex vertex; public Vertex Vertex { get { return this.vertex; } } public void Flush() { System.Diagnostics.Debug.Assert(this.AvailableEntrancy >= -1); this.vertex.Flush(); } public abstract void OnReceive(Message<S, T> message, ReturnAddress from); private AutoSerializedMessageDecoder<S, T> decoder = null; public void SerializedMessageReceived(SerializedMessage serializedMessage, ReturnAddress from) { System.Diagnostics.Debug.Assert(this.AvailableEntrancy >= -1); if (this.decoder == null) this.decoder = new AutoSerializedMessageDecoder<S, T>(this.Vertex.SerializationFormat); if (this.loggingEnabled) this.LogMessage(serializedMessage); Message<S, T> msg = new Message<S, T>(); msg.Allocate(AllocationReason.Deserializer); // N.B. At present, AsTypedMessages reuses and yields the same given msg for each batch // of deserialized messages. As a result, the message passed to OnReceive MUST NOT // be queued, because its payload will be overwritten by the next batch of messages. foreach (Message<S, T> message in this.decoder.AsTypedMessages(serializedMessage, msg)) { this.OnReceive(message, from); } msg.Release(AllocationReason.Deserializer); } protected void LogMessage(Message<S, T> message) { var encoder = new AutoSerializedMessageEncoder<S, T>(this.Vertex.VertexId, this.channelId, DummyBufferPool<byte>.Pool, this.Vertex.Stage.InternalComputation.Controller.Configuration.SendPageSize, this.Vertex.SerializationFormat); encoder.CompletedMessage += (o, a) => { ArraySegment<byte> messageSegment = a.Segment.ToArraySegment(); this.Vertex.LoggingOutput.Write(messageSegment.Array, messageSegment.Offset, messageSegment.Count); }; // XXX : Needs to be fixed up... for (int i = 0; i < message.length; ++i) encoder.Write(message.payload[i].PairWith(message.time)); encoder.Flush(); } protected void LogMessage(SerializedMessage message) { byte[] messageHeaderBuffer = new byte[MessageHeader.SizeOf]; MessageHeader.WriteHeaderToBuffer(messageHeaderBuffer, 0, message.Header); this.Vertex.LoggingOutput.Write(messageHeaderBuffer, 0, messageHeaderBuffer.Length); this.Vertex.LoggingOutput.Write(message.Body.Buffer, message.Body.CurrentPos, message.Body.End - message.Body.CurrentPos); } public Receiver(Vertex vertex) { this.vertex = vertex; } } internal class ActionReceiver<S, T> : Receiver<S, T> where T : Time<T> { private readonly Action<Message<S, T>, ReturnAddress> MessageCallback; public override void OnReceive(Message<S, T> message, ReturnAddress from) { if (this.LoggingEnabled) this.LogMessage(message); this.MessageCallback(message, from); } public ActionReceiver(Vertex vertex, Action<Message<S, T>, ReturnAddress> messagecallback) : base(vertex) { this.MessageCallback = messagecallback; } public ActionReceiver(Vertex vertex, Action<Message<S, T>> messagecallback) : base(vertex) { this.MessageCallback = (m, u) => messagecallback(m); } public ActionReceiver(Vertex vertex, Action<S, T> recordcallback) : base(vertex) { this.MessageCallback = ((m, u) => { for (int i = 0; i < m.length; i++) recordcallback(m.payload[i], m.time); }); } } internal class ActionSubscriber<S, T> : VertexOutput<S, T> where T : Time<T> { private readonly Action<SendChannel<S, T>> onListener; private Vertex<T> vertex; public Vertex Vertex { get { return this.vertex; } } public void AddReceiver(SendChannel<S, T> receiver) { this.onListener(receiver); } public ActionSubscriber(Vertex<T> vertex, Action<SendChannel<S, T>> action) { this.vertex = vertex; this.onListener = action; } } #endregion #region StageOutput and friends internal class StageOutput<R, T> where T : Time<T> { internal readonly Dataflow.Stage ForStage; internal readonly Dataflow.TimeContext<T> Context; private readonly Dictionary<int, VertexOutput<R, T>> endpointMap; private readonly Expression<Func<R, int>> partitionedBy; public Expression<Func<R, int>> PartitionedBy { get { return partitionedBy; } } internal void Register(VertexOutput<R, T> endpoint) { this.endpointMap[endpoint.Vertex.VertexId] = endpoint; } public VertexOutput<R, T> GetFiber(int index) { return endpointMap[index]; } public void AttachBundleToSender(Cable<R, T> bundle) { foreach (var pair in endpointMap) { pair.Value.AddReceiver(bundle.GetSendChannel(pair.Key)); } } public override string ToString() { return String.Format("SendPort[{0}]", this.ForStage); } internal StageOutput(Stage stage, Dataflow.ITimeContext<T> context) : this(stage, context, null) { } internal StageOutput(Stage stage, Dataflow.ITimeContext<T> context, Expression<Func<R, int>> partitionedBy) { this.ForStage = stage; this.Context = new TimeContext<T>(context); endpointMap = new Dictionary<int, VertexOutput<R, T>>(); this.partitionedBy = partitionedBy; } } #endregion }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindRepository { /// <summary> /// Strongly-typed collection for the Region class. /// </summary> [Serializable] public partial class RegionCollection : RepositoryList<Region, RegionCollection> { public RegionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RegionCollection</returns> public RegionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Region o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Region table. /// </summary> [Serializable] public partial class Region : RepositoryRecord<Region>, IRecordBase { #region .ctors and Default Settings public Region() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Region(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Region", TableType.Table, DataService.GetInstance("NorthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarRegionID = new TableSchema.TableColumn(schema); colvarRegionID.ColumnName = "RegionID"; colvarRegionID.DataType = DbType.Int32; colvarRegionID.MaxLength = 0; colvarRegionID.AutoIncrement = true; colvarRegionID.IsNullable = false; colvarRegionID.IsPrimaryKey = true; colvarRegionID.IsForeignKey = false; colvarRegionID.IsReadOnly = false; colvarRegionID.DefaultSetting = @""; colvarRegionID.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegionID); TableSchema.TableColumn colvarRegionDescription = new TableSchema.TableColumn(schema); colvarRegionDescription.ColumnName = "RegionDescription"; colvarRegionDescription.DataType = DbType.String; colvarRegionDescription.MaxLength = 50; colvarRegionDescription.AutoIncrement = false; colvarRegionDescription.IsNullable = false; colvarRegionDescription.IsPrimaryKey = false; colvarRegionDescription.IsForeignKey = false; colvarRegionDescription.IsReadOnly = false; colvarRegionDescription.DefaultSetting = @""; colvarRegionDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegionDescription); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindRepository"].AddSchema("Region",schema); } } #endregion #region Props [XmlAttribute("RegionID")] [Bindable(true)] public int RegionID { get { return GetColumnValue<int>(Columns.RegionID); } set { SetColumnValue(Columns.RegionID, value); } } [XmlAttribute("RegionDescription")] [Bindable(true)] public string RegionDescription { get { return GetColumnValue<string>(Columns.RegionDescription); } set { SetColumnValue(Columns.RegionDescription, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region Typed Columns public static TableSchema.TableColumn RegionIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn RegionDescriptionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string RegionID = @"RegionID"; public static string RegionDescription = @"RegionDescription"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; namespace XLinqTests { public class AddNodeAfter : AddNodeBeforeAfterBase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+AddNodeAfter // Test Case #region Public Methods and Operators public override void AddChildren() { AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - connected") { Params = new object[] { true, 4 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - not connected") { Params = new object[] { false, 1 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - not connected") { Params = new object[] { false, 4 }, Priority = 1 } }); AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - connected") { Params = new object[] { true, 1 }, Priority = 1 } }); AddChild(new TestVariation(InvalidNodeTypes) { Attribute = new VariationAttribute("Invalid node types - single object") { Priority = 2 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (multiple)") { Params = new object[] { false, 3 }, Priority = 1 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (single)") { Params = new object[] { true, 1 }, Priority = 0 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (single)") { Params = new object[] { false, 1 }, Priority = 0 } }); AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (multiple)") { Params = new object[] { true, 3 }, Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument1) { Attribute = new VariationAttribute("XDocument invalid add - double DTD") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument2) { Attribute = new VariationAttribute("XDocument invalid add - DTD after element") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument4) { Attribute = new VariationAttribute("XDocument invalid add - multiple root elements") { Priority = 1 } }); AddChild(new TestVariation(InvalidAddIntoXDocument5) { Attribute = new VariationAttribute("XDocument invalid add - CData, attribute, text (no whitespace)") { Priority = 1 } }); AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("Working on the text nodes 1.") { Priority = 1 } }); AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("Working on the text nodes 2.") { Priority = 1 } }); } // - order // - parent, document property // - query // - value // - assigning/cloning nodes (connected, not connected) // ---- // add valid: // - first, in the middle, last // - elem, text/XText (concatenation), PI, Comment - for XE // - elem (just root), PI, Comment, XDecl/XDocType (order!) // - on other node types //[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - not connected", Params = new object[] { false, 4 })] //[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - connected", Params = new object[] { true, 4 })] //[Variation(Priority = 1, Desc = "Adding single object into XElement - not connected", Params = new object[] { false, 1 })] //[Variation(Priority = 1, Desc = "Adding single object into XElement - connected", Params = new object[] { true, 1 })] public void AddingMultipleNodesIntoElement() { AddingMultipleNodesIntoElement(delegate(XNode n, object[] content) { n.AddAfterSelf(content); }, CalculateExpectedValuesAddAfter); } public IEnumerable<ExpectedValue> CalculateExpectedValuesAddAfter(XContainer orig, int startPos, IEnumerable<object> newNodes) { int counter = 0; for (XNode node = orig.FirstNode; node != null; node = node.NextNode, counter++) { yield return new ExpectedValue(!(node is XText), node); // Don't build on the text node identity if (counter == startPos) { foreach (object o in newNodes) { yield return new ExpectedValue(o is XNode && (o as XNode).Parent == null && (o as XNode).Document == null, o); } } } } //[Variation(Priority = 2, Desc = "Invalid node types - single object")] // XDocument constraints: // - only one DTD, DTD is first (before elem) // - only one root element // - no CDATA, // - no Attribute // - no text (except whitespace) //[Variation(Priority = 1, Desc = "XDocument invalid add - double DTD")] public void InvalidAddIntoXDocument1() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XDocumentType("root", null, null, null), new XElement("A")); var o = new XDocumentType("D", null, null, null); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.FirstNode.AddAfterSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - DTD after element")] public void InvalidAddIntoXDocument2() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XElement("A")); var o = new XDocumentType("D", null, null, null); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.FirstNode.AddAfterSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - multiple root elements")] public void InvalidAddIntoXDocument4() { runWithEvents = (bool)Params[0]; try { var doc = new XDocument(new XElement("A")); var o = new XElement("C"); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.FirstNode.AddAfterSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (InvalidOperationException) { } } //[Variation(Priority = 1, Desc = "XDocument invalid add - CData, attribute, text (no whitespace)")] public void InvalidAddIntoXDocument5() { runWithEvents = (bool)Params[0]; foreach (object o in new object[] { new XCData("CD"), new XAttribute("a1", "avalue"), "text1", new XText("text2"), new XDocument() }) { try { var doc = new XDocument(new XElement("A")); if (runWithEvents) { eHelper = new EventsHelper(doc); } doc.FirstNode.AddAfterSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Exception expected"); } catch (ArgumentException) { } } } public void InvalidNodeTypes() { runWithEvents = (bool)Params[0]; var root = new XElement("root", new XAttribute("a", "b"), new XElement("here"), "tests"); var rootCopy = new XElement(root); XElement elem = root.Element("here"); object[] nodes = { new XAttribute("xx", "yy"), new XDocument(), new XDocumentType("root", null, null, null) }; if (runWithEvents) { eHelper = new EventsHelper(elem); } foreach (object o in nodes) { try { elem.AddAfterSelf(o); if (runWithEvents) { eHelper.Verify(XObjectChange.Add, o); } TestLog.Compare(false, "Should fail!"); } catch (Exception) { TestLog.Compare(XNode.DeepEquals(root, rootCopy), "root.Equals(rootCopy)"); } } } //[Variation(Priority = 0, Desc = "XDocument valid add - connected (single)", Params = new object[] { true, 1 })] //[Variation(Priority = 0, Desc = "XDocument valid add - not connected (single)", Params = new object[] { false, 1 })] //[Variation(Priority = 1, Desc = "XDocument valid add - connected (multiple)", Params = new object[] { true, 3 })] //[Variation(Priority = 1, Desc = "XDocument valid add - not connected (multiple)", Params = new object[] { false, 3 })] public void ValidAddIntoXDocument() { ValidAddIntoXDocument(delegate(XNode n, object[] content) { n.AddAfterSelf(content); }, CalculateExpectedValuesAddAfter); } //[Variation(Priority = 1, Desc = "Working on the text nodes 1.")] public void WorkOnTextNodes1() { runWithEvents = (bool)Params[0]; var elem = new XElement("A", new XElement("B"), "text0", new XElement("C")); XNode n = elem.FirstNode.NextNode; if (runWithEvents) { eHelper = new EventsHelper(elem); } n.AddAfterSelf("text1"); n.AddAfterSelf("text2"); if (runWithEvents) { eHelper.Verify(new[] { XObjectChange.Value, XObjectChange.Value }); } TestLog.Compare(elem.Nodes().Count(), 3, "elem.Nodes().Count(), 3"); TestLog.Compare((n as XText).Value, "text0text1text2", "(n as XText).Value, text0text1text2"); } //[Variation(Priority = 1, Desc = "Working on the text nodes 2.")] public void WorkOnTextNodes2() { runWithEvents = (bool)Params[0]; var elem = new XElement("A", new XElement("B"), "text0", new XElement("C")); XNode n = elem.FirstNode.NextNode; if (runWithEvents) { eHelper = new EventsHelper(elem); } n.AddAfterSelf("text1", "text2"); if (runWithEvents) { eHelper.Verify(XObjectChange.Value); } TestLog.Compare(elem.Nodes().Count(), 3, "elem.Nodes().Count(), 3"); TestLog.Compare((n as XText).Value, "text0text1text2", "(n as XText).Value, text0text1text2"); } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal.NetworkSenders; using NLog.Layouts; /// <summary> /// Sends log messages over the network. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will be very slow. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// <p> /// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a> /// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private Dictionary<string, LinkedListNode<NetworkSender>> currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>(); private LinkedList<NetworkSender> openNetworkSenders = new LinkedList<NetworkSender>(); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NetworkTarget() { this.SenderFactory = NetworkSenderFactory.Default; this.Encoding = Encoding.UTF8; this.OnOverflow = NetworkTargetOverflowAction.Split; this.KeepConnection = true; this.MaxMessageSize = 65000; this.ConnectionCacheSize = 5; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li> /// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li> /// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(true)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(false)] public bool NewLine { get; set; } /// <summary> /// Gets or sets the maximum message size in bytes. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(65000)] public int MaxMessageSize { get; set; } /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(5)] public int ConnectionCacheSize { get; set; } /// <summary> /// Gets or sets the maximum current connections. 0 = no maximum. /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(0)] public int MaxConnections { get; set; } /// <summary> /// Gets or sets the action that should be taken if the will be more connections than <see cref="MaxConnections"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; } /// <summary> /// Gets or sets the maximum queue size. /// </summary> [DefaultValue(0)] public int MaxQueueSize { get; set; } /// <summary> /// Gets or sets the action that should be taken if the message is larger than /// maxMessageSize. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue("utf-8")] public Encoding Encoding { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount = 0; AsyncContinuation continuation = ex => { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } }; lock (this.openNetworkSenders) { remainingCount = this.openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in this.openNetworkSenders) { openSender.FlushAsync(continuation); } } } } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { base.CloseTarget(); lock (this.openNetworkSenders) { foreach (var openSender in this.openNetworkSenders) { openSender.Close(ex => { }); } this.openNetworkSenders.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = this.Address.Render(logEvent.LogEvent); byte[] bytes = this.GetBytesToWrite(logEvent.LogEvent); if (this.KeepConnection) { var senderNode = this.GetCachedNetworkSender(address); this.ChunkedSend( senderNode.Value, bytes, ex => { if (ex != null) { InternalLogger.Error(ex, "Error when sending."); this.ReleaseCachedConnection(senderNode); } logEvent.Continuation(ex); }); } else { NetworkSender sender; LinkedListNode<NetworkSender> linkedListNode; lock (this.openNetworkSenders) { //handle too many connections var tooManyConnections = this.openNetworkSenders.Count >= MaxConnections; if (tooManyConnections && MaxConnections > 0) { switch (this.OnConnectionOverflow) { case NetworkTargetConnectionsOverflowAction.DiscardMessage: InternalLogger.Warn("Discarding message otherwise to many connections."); logEvent.Continuation(null); return; case NetworkTargetConnectionsOverflowAction.AllowNewConnnection: InternalLogger.Debug("Too may connections, but this is allowed"); break; case NetworkTargetConnectionsOverflowAction.Block: while (this.openNetworkSenders.Count >= this.MaxConnections) { InternalLogger.Debug("Blocking networktarget otherwhise too many connections."); System.Threading.Monitor.Wait(this.openNetworkSenders); InternalLogger.Trace("Entered critical section."); } InternalLogger.Trace("Limit ok."); break; } } sender = this.SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); linkedListNode = this.openNetworkSenders.AddLast(sender); } this.ChunkedSend( sender, bytes, ex => { lock (this.openNetworkSenders) { TryRemove(this.openNetworkSenders, linkedListNode); if (this.OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block) { System.Threading.Monitor.PulseAll(this.openNetworkSenders); } } if (ex != null) { InternalLogger.Error(ex, "Error when sending."); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } } /// <summary> /// Try to remove. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="node"></param> /// <returns>removed something?</returns> private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node) { if (node == null || list != node.List) { return false; } list.Remove(node); return true; } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { string text; if (this.NewLine) { text = this.Layout.Render(logEvent) + "\r\n"; } else { text = this.Layout.Render(logEvent); } return this.Encoding.GetBytes(text); } private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address) { lock (this.currentSenderCache) { LinkedListNode<NetworkSender> senderNode; // already have address if (this.currentSenderCache.TryGetValue(address, out senderNode)) { senderNode.Value.CheckSocket(); return senderNode; } if (this.currentSenderCache.Count >= this.ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; LinkedListNode<NetworkSender> leastRecentlyUsed = null; foreach (var pair in this.currentSenderCache) { var networkSender = pair.Value.Value; if (networkSender.LastSendTime < minAccessTime) { minAccessTime = networkSender.LastSendTime; leastRecentlyUsed = pair.Value; } } if (leastRecentlyUsed != null) { this.ReleaseCachedConnection(leastRecentlyUsed); } } var sender = this.SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); lock (this.openNetworkSenders) { senderNode = this.openNetworkSenders.AddLast(sender); } this.currentSenderCache.Add(address, senderNode); return senderNode; } } private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode) { lock (this.currentSenderCache) { var networkSender = senderNode.Value; lock (this.openNetworkSenders) { if(TryRemove(this.openNetworkSenders,senderNode)) { // only remove it once networkSender.Close(ex => { }); } } LinkedListNode<NetworkSender> sender2; // make sure the current sender for this address is the one we want to remove if (this.currentSenderCache.TryGetValue(networkSender.Address, out sender2)) { if (ReferenceEquals(senderNode, sender2)) { this.currentSenderCache.Remove(networkSender.Address); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")] private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int tosend = buffer.Length; int pos = 0; AsyncContinuation sendNextChunk = null; sendNextChunk = ex => { if (ex != null) { continuation(ex); return; } if (tosend <= 0) { continuation(null); return; } int chunksize = tosend; if (chunksize > this.MaxMessageSize) { if (this.OnOverflow == NetworkTargetOverflowAction.Discard) { continuation(null); return; } if (this.OnOverflow == NetworkTargetOverflowAction.Error) { continuation(new OverflowException("Attempted to send a message larger than MaxMessageSize (" + this.MaxMessageSize + "). Actual size was: " + buffer.Length + ". Adjust OnOverflow and MaxMessageSize parameters accordingly.")); return; } chunksize = this.MaxMessageSize; } int pos0 = pos; tosend -= chunksize; pos += chunksize; sender.Send(buffer, pos0, chunksize, sendNextChunk); }; sendNextChunk(null); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using Nop.Core.Domain.Customers; using Nop.Services.Localization; namespace Nop.Services.Customers { /// <summary> /// Customer attribute parser /// </summary> public partial class CustomerAttributeParser : ICustomerAttributeParser { private readonly ICustomerAttributeService _customerAttributeService; private readonly ILocalizationService _localizationService; public CustomerAttributeParser(ICustomerAttributeService customerAttributeService, ILocalizationService localizationService) { this._customerAttributeService = customerAttributeService; this._localizationService = localizationService; } /// <summary> /// Gets selected customer attribute identifiers /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected customer attribute identifiers</returns> protected virtual IList<int> ParseCustomerAttributeIds(string attributesXml) { var ids = new List<int>(); if (String.IsNullOrEmpty(attributesXml)) return ids; try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/CustomerAttribute")) { if (node.Attributes != null && node.Attributes["ID"] != null) { string str1 = node.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { ids.Add(id); } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return ids; } /// <summary> /// Gets selected customer attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Selected customer attributes</returns> public virtual IList<CustomerAttribute> ParseCustomerAttributes(string attributesXml) { var result = new List<CustomerAttribute>(); var ids = ParseCustomerAttributeIds(attributesXml); foreach (int id in ids) { var attribute = _customerAttributeService.GetCustomerAttributeById(id); if (attribute != null) { result.Add(attribute); } } return result; } /// <summary> /// Get customer attribute values /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Customer attribute values</returns> public virtual IList<CustomerAttributeValue> ParseCustomerAttributeValues(string attributesXml) { var values = new List<CustomerAttributeValue>(); var attributes = ParseCustomerAttributes(attributesXml); foreach (var attribute in attributes) { if (!attribute.ShouldHaveValues()) continue; var valuesStr = ParseValues(attributesXml, attribute.Id); foreach (string valueStr in valuesStr) { if (!String.IsNullOrEmpty(valueStr)) { int id; if (int.TryParse(valueStr, out id)) { var value = _customerAttributeService.GetCustomerAttributeValueById(id); if (value != null) values.Add(value); } } } } return values; } /// <summary> /// Gets selected customer attribute value /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customerAttributeId">Customer attribute identifier</param> /// <returns>Customer attribute value</returns> public virtual IList<string> ParseValues(string attributesXml, int customerAttributeId) { var selectedCustomerAttributeValues = new List<string>(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(attributesXml); var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CustomerAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == customerAttributeId) { var nodeList2 = node1.SelectNodes(@"CustomerAttributeValue/Value"); foreach (XmlNode node2 in nodeList2) { string value = node2.InnerText.Trim(); selectedCustomerAttributeValues.Add(value); } } } } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return selectedCustomerAttributeValues; } /// <summary> /// Adds an attribute /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="ca">Customer attribute</param> /// <param name="value">Value</param> /// <returns>Attributes</returns> public virtual string AddCustomerAttribute(string attributesXml, CustomerAttribute ca, string value) { string result = string.Empty; try { var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement attributeElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/CustomerAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id; if (int.TryParse(str1, out id)) { if (id == ca.Id) { attributeElement = (XmlElement)node1; break; } } } } //create new one if not found if (attributeElement == null) { attributeElement = xmlDoc.CreateElement("CustomerAttribute"); attributeElement.SetAttribute("ID", ca.Id.ToString()); rootElement.AppendChild(attributeElement); } var attributeValueElement = xmlDoc.CreateElement("CustomerAttributeValue"); attributeElement.AppendChild(attributeValueElement); var attributeValueValueElement = xmlDoc.CreateElement("Value"); attributeValueValueElement.InnerText = value; attributeValueElement.AppendChild(attributeValueValueElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return result; } /// <summary> /// Validates customer attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <returns>Warnings</returns> public virtual IList<string> GetAttributeWarnings(string attributesXml) { var warnings = new List<string>(); //ensure it's our attributes var attributes1 = ParseCustomerAttributes(attributesXml); //validate required customer attributes (whether they're chosen/selected/entered) var attributes2 = _customerAttributeService.GetAllCustomerAttributes(); foreach (var a2 in attributes2) { if (a2.IsRequired) { bool found = false; //selected customer attributes foreach (var a1 in attributes1) { if (a1.Id == a2.Id) { var valuesStr = ParseValues(attributesXml, a1.Id); foreach (string str1 in valuesStr) { if (!String.IsNullOrEmpty(str1.Trim())) { found = true; break; } } } } //if not found if (!found) { var notFoundWarning = string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetLocalized(a => a.Name)); warnings.Add(notFoundWarning); } } } return warnings; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; [module: Aspekt.Foundation.Test.ModuleLevelAspect()] namespace Aspekt.Foundation.Test { [TestClass] public class FoundationTest { [MockAspect("CallMe")] private void CallMe() { Thread.Sleep(500); } [MockAspect("TestIntFn")] private int TestIntFn() { return 1 + 1; } [MockAspect("CallMeMaybe")] private void CallMeMaybe(string value) { } [MockAspect("CallMeException")] private void CallMeException() { throw new Exception("Blah"); } [TestMethod] public void TestEntryExit() { MockAspect.Reset(); CallMe(); Assert.AreEqual(1, MockAspect.Entries, "OnEntry"); Assert.AreEqual(1, MockAspect.Exits, "OnExit"); } [TestMethod] public void TestEntryExitRetValFn() { MockAspect.Reset(); TestIntFn(); Assert.AreEqual(1, MockAspect.Entries, "OnEntry"); Assert.AreEqual(1, MockAspect.Exits, "OnExit"); } [TestMethod] public void TestMethodArguments() { var called = false; MockAspect.Reset(); MockAspect.OnEntryAction = (MethodArguments a) => { Assert.AreEqual(1, a.Arguments.Count); Assert.AreEqual("SomeValue", a.Arguments[0].Value); Assert.AreEqual("value", a.Arguments[0].Name); Assert.AreEqual(typeof(string), a.Arguments[0].Type); called = true; }; CallMeMaybe("SomeValue"); Assert.IsTrue(called); } [TestMethod] public void TestMethodException() { var called = false; MockAspect.Reset(); MockAspect.OnExceptionAction = (args, e) => { called = true; Assert.AreEqual(e.Message, "Blah"); }; try { CallMeException(); } catch (Exception e) // because the exception will rethrow after { Assert.AreEqual(e.Message, "Blah"); Assert.IsTrue(called); return; // } Assert.Fail(); } [TestMethod] public void TestInstanceEqual() { MockAspect.Reset(); var dc = new DummyClass(); var called = false; MockAspect.OnEntryAction = (args) => { called = true; Assert.AreSame(args.Instance, dc, "object reference mismatch"); }; dc.Call(); Assert.IsTrue(called); // Assert that dc == Property } /// <summary> /// This method, will have module decoration. So I will set up the callbacks in the /// test method. Then call this. /// </summary> /// <returns></returns> public int UseThisMethodToTestModule() { return 3 + 3; } /// <summary> /// This method intentionally has no decoration. So that I can test the module / assembly level aspects. /// </summary> public void ThrowAnException() { throw new Exception("thrown"); } /// <summary> /// These methods pose an interesting problem. Because unless I move the module level /// aspect to a different module, these methods will get instrumented with the module /// level aspect. /// </summary> [TestMethod] public void TestModuleLevelAspect() { var entry = 0; var exit = 0; var exception = 0; ModuleLevelAspect.OnMethodEntry = (e) => { entry++; }; ModuleLevelAspect.OnMethodExit = (e) => { exit++; }; ModuleLevelAspect.OnMethodException = (e, ex) => { exception++; }; UseThisMethodToTestModule(); Assert.AreEqual(1, entry, "Entry"); Assert.AreEqual(1, exit, "Exit"); Assert.AreEqual(0, exception, "Exception"); } [TestMethod] public void TestModuleLevelAspectException() { var entry = 0; var exit = 0; var exception = 0; ModuleLevelAspect.OnMethodEntry = (e) => { entry++; }; ModuleLevelAspect.OnMethodExit = (e) => { exit++; }; ModuleLevelAspect.OnMethodException = (e, ex) => { exception++; }; try { ThrowAnException(); } catch { // gulp. } Assert.AreEqual(1, entry, "Entry"); Assert.AreEqual(0, exit, "Exit"); Assert.AreEqual(1, exception, "Exception"); } /// <summary> /// Remember that because the .ctor is a method as well, we need to account for it getting called. /// </summary> [TestMethod] public void TestClassLevelAspect() { var entry = 0; var exit = 0; var exception = 0; ClassLevelAspect.OnMethodEntry = (e) => { entry++; }; ClassLevelAspect.OnMethodExit = (e) => { exit++; }; ClassLevelAspect.OnMethodException = (e, ex) => { exception++; }; var interest = new ClassUnderTest(); interest.TestMethod1(); Assert.AreEqual(2, entry, "Entry"); Assert.AreEqual(2, exit, "Exit"); Assert.AreEqual(0, exception, "Exception"); } [TestMethod] public void TestClassLevelAspectException() { var entry = 0; var exit = 0; var exception = 0; ClassLevelAspect.OnMethodEntry = (e) => { entry++; }; ClassLevelAspect.OnMethodExit = (e) => { exit++; }; ClassLevelAspect.OnMethodException = (e, ex) => { exception++; }; var interest = new ClassUnderTest(); try { interest.GenerateException(); } catch { // gulp. } Assert.AreEqual(2, entry, "Entry"); Assert.AreEqual(1, exit, "Exit"); Assert.AreEqual(1, exception, "Exception"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Lucene.Net.Search { using Lucene.Net.Support; using ArrayUtil = Lucene.Net.Util.ArrayUtil; using AtomicReader = Lucene.Net.Index.AtomicReader; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Bits = Lucene.Net.Util.Bits; using BytesRef = Lucene.Net.Util.BytesRef; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// MultiPhraseQuery is a generalized version of PhraseQuery, with an added /// method <seealso cref="#add(Term[])"/>. /// To use this class, to search for the phrase "Microsoft app*" first use /// add(Term) on the term "Microsoft", then find all terms that have "app" as /// prefix using IndexReader.terms(Term), and use MultiPhraseQuery.add(Term[] /// terms) to add them to the query. /// /// </summary> public class MultiPhraseQuery : Query { private string Field; private List<Term[]> termArrays = new List<Term[]>(); private readonly List<int> positions = new List<int>(); private int slop = 0; /// <summary> /// Sets the phrase slop for this query. </summary> /// <seealso cref= PhraseQuery#setSlop(int) </seealso> public virtual int Slop { set { if (value < 0) { throw new System.ArgumentException("slop value cannot be negative"); } slop = value; } get { return slop; } } /// <summary> /// Add a single term at the next position in the phrase. </summary> /// <seealso cref= PhraseQuery#add(Term) </seealso> public virtual void Add(Term term) { Add(new Term[] { term }); } /// <summary> /// Add multiple terms at the next position in the phrase. Any of the terms /// may match. /// </summary> /// <seealso cref= PhraseQuery#add(Term) </seealso> public virtual void Add(Term[] terms) { int position = 0; if (positions.Count > 0) { position = (int)positions[positions.Count - 1] + 1; } Add(terms, position); } /// <summary> /// Allows to specify the relative position of terms within the phrase. /// </summary> /// <seealso cref= PhraseQuery#add(Term, int) </seealso> public virtual void Add(Term[] terms, int position) { if (termArrays.Count == 0) { Field = terms[0].Field; } for (var i = 0; i < terms.Length; i++) { if (!terms[i].Field.Equals(Field)) { throw new System.ArgumentException("All phrase terms must be in the same field (" + Field + "): " + terms[i]); } } termArrays.Add(terms); positions.Add(Convert.ToInt32(position)); } /// <summary> /// Returns a List of the terms in the multiphrase. /// Do not modify the List or its contents. /// </summary> public virtual IList<Term[]> TermArrays { get { return termArrays.AsReadOnly();// Collections.unmodifiableList(TermArrays_Renamed); } } /// <summary> /// Returns the relative positions of terms in this phrase. /// </summary> public virtual int[] Positions { get { var result = new int[positions.Count]; for (int i = 0; i < positions.Count; i++) { result[i] = (int)positions[i]; } return result; } } // inherit javadoc public override void ExtractTerms(ISet<Term> terms) { foreach (Term[] arr in termArrays) { foreach (Term term in arr) { terms.Add(term); } } } private class MultiPhraseWeight : Weight { private readonly MultiPhraseQuery OuterInstance; private readonly Similarity Similarity; private readonly Similarity.SimWeight Stats; private readonly IDictionary<Term, TermContext> TermContexts = new Dictionary<Term, TermContext>(); public MultiPhraseWeight(MultiPhraseQuery outerInstance, IndexSearcher searcher) { this.OuterInstance = outerInstance; this.Similarity = searcher.Similarity; IndexReaderContext context = searcher.TopReaderContext; // compute idf var allTermStats = new List<TermStatistics>(); foreach (Term[] terms in outerInstance.termArrays) { foreach (Term term in terms) { TermContext termContext; TermContexts.TryGetValue(term, out termContext); if (termContext == null) { termContext = TermContext.Build(context, term); TermContexts[term] = termContext; } allTermStats.Add(searcher.TermStatistics(term, termContext)); } } Stats = Similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.Field), allTermStats.ToArray()); } public override Query Query { get { return OuterInstance; } } public override float ValueForNormalization { get { return Stats.ValueForNormalization; } } public override void Normalize(float queryNorm, float topLevelBoost) { Stats.Normalize(queryNorm, topLevelBoost); } public override Scorer Scorer(AtomicReaderContext context, Bits acceptDocs) { Debug.Assert(OuterInstance.termArrays.Count > 0); AtomicReader reader = (context.AtomicReader); Bits liveDocs = acceptDocs; PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[OuterInstance.termArrays.Count]; Terms fieldTerms = reader.Terms(OuterInstance.Field); if (fieldTerms == null) { return null; } // Reuse single TermsEnum below: TermsEnum termsEnum = fieldTerms.Iterator(null); for (int pos = 0; pos < postingsFreqs.Length; pos++) { Term[] terms = OuterInstance.termArrays[pos]; DocsAndPositionsEnum postingsEnum; int docFreq; if (terms.Length > 1) { postingsEnum = new UnionDocsAndPositionsEnum(liveDocs, context, terms, TermContexts, termsEnum); // coarse -- this overcounts since a given doc can // have more than one term: docFreq = 0; for (int termIdx = 0; termIdx < terms.Length; termIdx++) { Term term = terms[termIdx]; TermState termState = TermContexts[term].Get(context.Ord); if (termState == null) { // Term not in reader continue; } termsEnum.SeekExact(term.Bytes, termState); docFreq += termsEnum.DocFreq(); } if (docFreq == 0) { // None of the terms are in this reader return null; } } else { Term term = terms[0]; TermState termState = TermContexts[term].Get(context.Ord); if (termState == null) { // Term not in reader return null; } termsEnum.SeekExact(term.Bytes, termState); postingsEnum = termsEnum.DocsAndPositions(liveDocs, null, DocsEnum.FLAG_NONE); if (postingsEnum == null) { // term does exist, but has no positions Debug.Assert(termsEnum.Docs(liveDocs, null, DocsEnum.FLAG_NONE) != null, "termstate found but no term exists in reader"); throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } docFreq = termsEnum.DocFreq(); } postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, docFreq, (int)OuterInstance.positions[pos], terms); } // sort by increasing docFreq order if (OuterInstance.slop == 0) { ArrayUtil.TimSort(postingsFreqs); } if (OuterInstance.slop == 0) { ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, Similarity.DoSimScorer(Stats, context)); if (s.NoDocs) { return null; } else { return s; } } else { return new SloppyPhraseScorer(this, postingsFreqs, OuterInstance.slop, Similarity.DoSimScorer(Stats, context)); } } public override Explanation Explain(AtomicReaderContext context, int doc) { Scorer scorer = Scorer(context, (context.AtomicReader).LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = OuterInstance.slop == 0 ? scorer.Freq() : ((SloppyPhraseScorer)scorer).SloppyFreq(); SimScorer docScorer = Similarity.DoSimScorer(Stats, context); ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + ") [" + Similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq)); result.AddDetail(scoreExplanation); result.Value = scoreExplanation.Value; result.Match = true; return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } public override Query Rewrite(IndexReader reader) { if (termArrays.Count == 0) { BooleanQuery bq = new BooleanQuery(); bq.Boost = Boost; return bq; } // optimize one-term case else if (termArrays.Count == 1) { Term[] terms = termArrays[0]; BooleanQuery boq = new BooleanQuery(true); for (int i = 0; i < terms.Length; i++) { boq.Add(new TermQuery(terms[i]), BooleanClause.Occur.SHOULD); } boq.Boost = Boost; return boq; } else { return this; } } public override Weight CreateWeight(IndexSearcher searcher) { return new MultiPhraseWeight(this, searcher); } /// <summary> /// Prints a user-readable version of this query. </summary> public override sealed string ToString(string f) { StringBuilder buffer = new StringBuilder(); if (Field == null || !Field.Equals(f)) { buffer.Append(Field); buffer.Append(":"); } buffer.Append("\""); int k = 0; IEnumerator<Term[]> i = termArrays.GetEnumerator(); int? lastPos = -1; bool first = true; while (i.MoveNext()) { Term[] terms = i.Current; int? position = positions[k]; if (first) { first = false; } else { buffer.Append(" "); for (int j = 1; j < (position - lastPos); j++) { buffer.Append("? "); } } if (terms.Length > 1) { buffer.Append("("); for (int j = 0; j < terms.Length; j++) { buffer.Append(terms[j].Text()); if (j < terms.Length - 1) { buffer.Append(" "); } } buffer.Append(")"); } else { buffer.Append(terms[0].Text()); } lastPos = position; ++k; } buffer.Append("\""); if (slop != 0) { buffer.Append("~"); buffer.Append(slop); } buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns true if <code>o</code> is equal to this. </summary> public override bool Equals(object o) { if (!(o is MultiPhraseQuery)) { return false; } MultiPhraseQuery other = (MultiPhraseQuery)o; return this.Boost == other.Boost && this.slop == other.slop && TermArraysEquals(this.termArrays, other.termArrays) && this.positions.SequenceEqual(other.positions); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { //If this doesn't work hash all elements of positions. This was used to reduce time overhead return Number.FloatToIntBits(Boost) ^ slop ^ TermArraysHashCode() ^ ((positions.Count == 0) ? 0 : HashHelpers.CombineHashCodes(positions.First().GetHashCode(), positions.Last().GetHashCode(), positions.Count) ^ 0x4AC65113); } // Breakout calculation of the termArrays hashcode private int TermArraysHashCode() { int hashCode = 1; foreach (Term[] termArray in termArrays) { hashCode = 31 * hashCode + (termArray == null ? 0 : Arrays.GetHashCode(termArray)); } return hashCode; } // Breakout calculation of the termArrays equals private bool TermArraysEquals(IList<Term[]> termArrays1, IList<Term[]> termArrays2) { if (termArrays1.Count != termArrays2.Count) { return false; } IEnumerator<Term[]> iterator1 = termArrays1.GetEnumerator(); IEnumerator<Term[]> iterator2 = termArrays2.GetEnumerator(); while (iterator1.MoveNext()) { Term[] termArray1 = iterator1.Current; iterator2.MoveNext(); Term[] termArray2 = iterator2.Current; if (!(termArray1 == null ? termArray2 == null : Arrays.Equals(termArray1, termArray2))) { return false; } } return true; } } /// <summary> /// Takes the logical union of multiple DocsEnum iterators. /// </summary> // TODO: if ever we allow subclassing of the *PhraseScorer internal class UnionDocsAndPositionsEnum : DocsAndPositionsEnum { private sealed class DocsQueue : Util.PriorityQueue<DocsAndPositionsEnum> { internal DocsQueue(ICollection<DocsAndPositionsEnum> docsEnums) : base(docsEnums.Count) { IEnumerator<DocsAndPositionsEnum> i = docsEnums.GetEnumerator(); while (i.MoveNext()) { DocsAndPositionsEnum postings = i.Current; if (postings.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { Add(postings); } } } public override bool LessThan(DocsAndPositionsEnum a, DocsAndPositionsEnum b) { return a.DocID() < b.DocID(); } } private sealed class IntQueue { internal bool InstanceFieldsInitialized = false; public IntQueue() { if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; } } internal void InitializeInstanceFields() { _array = new int[_arraySize]; } internal int _arraySize = 16; internal int _index = 0; internal int _lastIndex = 0; internal int[] _array; internal void Add(int i) { if (_lastIndex == _arraySize) { GrowArray(); } _array[_lastIndex++] = i; } internal int Next() { return _array[_index++]; } internal void Sort() { Array.Sort(_array, _index, _lastIndex); } internal void Clear() { _index = 0; _lastIndex = 0; } internal int Size() { return (_lastIndex - _index); } private void GrowArray() { var newArray = new int[_arraySize * 2]; Array.Copy(_array, 0, newArray, 0, _arraySize); _array = newArray; _arraySize *= 2; } } private int _doc; private int _freq; private readonly DocsQueue _queue; private readonly IntQueue _posList; private readonly long _cost; public UnionDocsAndPositionsEnum(Bits liveDocs, AtomicReaderContext context, Term[] terms, IDictionary<Term, TermContext> termContexts, TermsEnum termsEnum) { ICollection<DocsAndPositionsEnum> docsEnums = new LinkedList<DocsAndPositionsEnum>(); for (int i = 0; i < terms.Length; i++) { Term term = terms[i]; TermState termState = termContexts[term].Get(context.Ord); if (termState == null) { // Term doesn't exist in reader continue; } termsEnum.SeekExact(term.Bytes, termState); DocsAndPositionsEnum postings = termsEnum.DocsAndPositions(liveDocs, null, DocsEnum.FLAG_NONE); if (postings == null) { // term does exist, but has no positions throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } _cost += postings.Cost(); docsEnums.Add(postings); } _queue = new DocsQueue(docsEnums); _posList = new IntQueue(); } public override sealed int NextDoc() { if (_queue.Size() == 0) { return NO_MORE_DOCS; } // TODO: move this init into positions(): if the search // doesn't need the positions for this doc then don't // waste CPU merging them: _posList.Clear(); _doc = _queue.Top().DocID(); // merge sort all positions together DocsAndPositionsEnum postings; do { postings = _queue.Top(); int freq = postings.Freq(); for (int i = 0; i < freq; i++) { _posList.Add(postings.NextPosition()); } if (postings.NextDoc() != NO_MORE_DOCS) { _queue.UpdateTop(); } else { _queue.Pop(); } } while (_queue.Size() > 0 && _queue.Top().DocID() == _doc); _posList.Sort(); _freq = _posList.Size(); return _doc; } public override int NextPosition() { return _posList.Next(); } public override int StartOffset() { return -1; } public override int EndOffset() { return -1; } public override BytesRef Payload { get { return null; } } public override sealed int Advance(int target) { while (_queue.Top() != null && target > _queue.Top().DocID()) { DocsAndPositionsEnum postings = _queue.Pop(); if (postings.Advance(target) != NO_MORE_DOCS) { _queue.Add(postings); } } return NextDoc(); } public override sealed int Freq() { return _freq; } public override sealed int DocID() { return _doc; } public override long Cost() { return _cost; } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Net; using System.IO; using System; using System.Reflection; using System.Xml.Serialization; namespace Igor { public class IgorOverridePlayerSettings : IgorModuleBase { public static StepID OverridePlayerSettingsStep = new StepID("OverridePlayerSettings", 260); static string[] kProjectSettingFiles = { "TimeManager.asset", "TagManager.asset", "QualitySettings.asset", "ProjectSettings.asset", "Physics2DSettings.asset", "NetworkManager.asset", "NavMeshLayers.asset", "InputManager.asset", "GraphicsSettings.asset", "EditorSettings.asset", "EditorBuildSettings.asset", "DynamicsManager.asset", "AudioManager.asset", }; static string kPlayerSettingsFolder = "Igor Override Player Settings"; static string kIgorProjectSettingExtension = ".igorplayersettings"; public static string PlayerSettingFilesToOverrideFlag = "player_settings_to_override"; public static string PlayerSettingsPathFlag = "player_settings_file"; private int SelectedProjectSettingsAsInt; public override string GetModuleName() { return "Configure.OverridePlayerSettings"; } public override void RegisterModule() { IgorCore.RegisterNewModule(this); } public override void ProcessArgs(IIgorStepHandler StepHandler) { if(IgorJobConfig.IsStringParamSet(PlayerSettingFilesToOverrideFlag) && IgorJobConfig.IsStringParamSet(PlayerSettingsPathFlag)) { IgorCore.SetModuleActiveForJob(this); StepHandler.RegisterJobStep(OverridePlayerSettingsStep, this, OverridePlayerSettings); } } public override string DrawJobInspectorAndGetEnabledParams(string CurrentParams) { string EnabledParams = CurrentParams; IgorConfigWindow ConfigurationWindow = IgorConfigWindow.OpenOrGetConfigWindow(); IgorPersistentJobConfig CurrentJob = ConfigurationWindow.CurrentJobInst; string CurrentJobAsString = CurrentJob != null ? CurrentJob.JobName : string.Empty; string TargetDirectory = kPlayerSettingsFolder + "/" + CurrentJobAsString; GUILayout.BeginHorizontal(); { string SelectedProjectSettingsAsString = IgorRuntimeUtils.GetStringParam(EnabledParams, PlayerSettingFilesToOverrideFlag).Trim('"'); if(!string.IsNullOrEmpty(SelectedProjectSettingsAsString)) { int OutResult = 0; if(Int32.TryParse(SelectedProjectSettingsAsString, out OutResult)) { SelectedProjectSettingsAsInt = OutResult; } } int newValue = EditorGUILayout.MaskField(SelectedProjectSettingsAsInt, kProjectSettingFiles); if(newValue != SelectedProjectSettingsAsInt) { SelectedProjectSettingsAsInt = newValue; if(newValue != 0) { EnabledParams = IgorRuntimeUtils.SetStringParam(EnabledParams, PlayerSettingFilesToOverrideFlag, SelectedProjectSettingsAsInt.ToString()); EnabledParams = IgorRuntimeUtils.SetStringParam(EnabledParams, PlayerSettingsPathFlag, '"' + TargetDirectory + '"'); } else { EnabledParams = IgorRuntimeUtils.ClearParam(EnabledParams, PlayerSettingFilesToOverrideFlag); EnabledParams = IgorRuntimeUtils.ClearParam(EnabledParams, PlayerSettingsPathFlag); } } } GUILayout.EndHorizontal(); string FilesToSave = string.Empty; for(int i = 0; i < kProjectSettingFiles.Length; ++i) { if(((1 << i) & SelectedProjectSettingsAsInt) != 0) { FilesToSave += ((string.IsNullOrEmpty(FilesToSave) ? string.Empty : ", ") + kProjectSettingFiles[i].Replace(".asset", string.Empty)); } } GUILayout.Space(5f); GUILayout.Label("Files to save: " + FilesToSave); if(Directory.Exists(TargetDirectory)) { GUILayout.Space(5f); string[] SourceFilesPaths = Directory.GetFiles(TargetDirectory); string ExistingOverrides = string.Empty; foreach(string SourceFilePath in SourceFilesPaths) { ExistingOverrides += ((string.IsNullOrEmpty(ExistingOverrides) ? string.Empty : ", ") + Path.GetFileName(SourceFilePath).Replace(kIgorProjectSettingExtension, string.Empty)); } GUILayout.Label("Existing overrides on disk: " + ExistingOverrides); GUILayout.Space(5f); } GUILayout.BeginHorizontal(); { GUI.enabled = CurrentJob != null && SelectedProjectSettingsAsInt != 0; if(GUILayout.Button("Save", GUILayout.ExpandWidth(false))) { if(!Directory.Exists(kPlayerSettingsFolder)) { Directory.CreateDirectory(kPlayerSettingsFolder); } IgorRuntimeUtils.DeleteDirectory(TargetDirectory); Directory.CreateDirectory(TargetDirectory); string[] SourceFilesPaths = Directory.GetFiles("ProjectSettings"); foreach(string SourceFilePath in SourceFilesPaths) { if(!SourceFilePath.EndsWith(".meta")) { string FileName = Path.GetFileName(SourceFilePath); int IndexInKnownAssetList = Array.IndexOf(kProjectSettingFiles, FileName, 0, kProjectSettingFiles.Length); if(IndexInKnownAssetList != -1) { if((((1 << IndexInKnownAssetList) & SelectedProjectSettingsAsInt) != 0) || SelectedProjectSettingsAsInt == -1) { string DestFilePath = SourceFilePath.Replace("ProjectSettings\\", string.Empty); DestFilePath = TargetDirectory + "/" + Path.ChangeExtension(DestFilePath, kIgorProjectSettingExtension); IgorRuntimeUtils.CopyFile(SourceFilePath, DestFilePath); } } } } AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); } string Tooltip = Directory.Exists(TargetDirectory) ? string.Empty : "Expected PlayerSettings directory " + " doesn't exist."; GUI.enabled &= Directory.Exists(TargetDirectory); if(GUILayout.Button(new GUIContent("Load saved settings file", Tooltip), GUILayout.ExpandWidth(false))) { CopyStoredPlayerSettingsOverCurrent(TargetDirectory); } GUI.enabled = true; } GUILayout.EndHorizontal(); return EnabledParams; } private static void CopyStoredPlayerSettingsOverCurrent(string TargetDirectory) { string[] SourceFilesPaths = Directory.GetFiles(TargetDirectory); if(SourceFilesPaths.Length > 0) { Debug.Log("Overriding player settings with data from " + TargetDirectory + "..."); foreach(string SourceFilePath in SourceFilesPaths) { string DestFilePath = SourceFilePath.Replace(TargetDirectory, "ProjectSettings"); DestFilePath = Path.ChangeExtension(DestFilePath, ".asset"); IgorRuntimeUtils.CopyFile(SourceFilePath, DestFilePath, true); Debug.Log("Replaced " + Path.GetFileName(DestFilePath)); // We need to find the ProjectSettings file and locate the defines text manually because otherwise // the recompile (if it even triggers; it's inconsistent) won't use the new defines. const string ScriptingDefineSymbolsTag = "scriptingDefineSymbols:\n"; if(DestFilePath.Contains("ProjectSettings.asset")) { string ProjectSettingsText = File.ReadAllText(SourceFilePath); int StartIndex = ProjectSettingsText.IndexOf(ScriptingDefineSymbolsTag) + ScriptingDefineSymbolsTag.Length; string StartOfDefinesBlock = ProjectSettingsText.Substring(StartIndex); HashSet<BuildTargetGroup> MatchedBuildTargetGroups = new HashSet<BuildTargetGroup>(); string NextLine; StringReader StringReader = new StringReader(StartOfDefinesBlock); bool bContinue = true; do { NextLine = StringReader.ReadLine(); if(NextLine != null) { NextLine = NextLine.Trim(); if(NextLine.Length > 0 && char.IsNumber(NextLine[0])) { int IndexOfColon = NextLine.IndexOf(':'); string BuildGroupText = NextLine.Substring(0, IndexOfColon); string Define = NextLine.Substring(IndexOfColon + 1); int BuildGroupAsInt = 0; Int32.TryParse(BuildGroupText, out BuildGroupAsInt); BuildTargetGroup TargetGroup = (BuildTargetGroup)BuildGroupAsInt; if(TargetGroup != BuildTargetGroup.Unknown) { PlayerSettings.SetScriptingDefineSymbolsForGroup(TargetGroup, Define); MatchedBuildTargetGroups.Add(TargetGroup); } } else { bContinue = false; } } } while(bContinue); // Make sure we wipe out defines on any other build targets. BuildTargetGroup[] AllTargetGroups = System.Enum.GetValues(typeof(BuildTargetGroup)) as BuildTargetGroup[]; foreach(BuildTargetGroup Group in AllTargetGroups) { if(!MatchedBuildTargetGroups.Contains(Group)) { PlayerSettings.SetScriptingDefineSymbolsForGroup(Group, string.Empty); } } } } AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } } public virtual bool OverridePlayerSettings() { string TargetDirectory = IgorJobConfig.GetStringParam(PlayerSettingsPathFlag); TargetDirectory = TargetDirectory.Replace("\"", string.Empty); CopyStoredPlayerSettingsOverCurrent(TargetDirectory); return true; } } }
/* * Copyright (c) 2006-2008, Second Life Reverse Engineering Team * 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 Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using libsecondlife.Packets; namespace libsecondlife { /// <summary> /// Access to the Linden dataserver which allows searching for land, events, people, etc /// </summary> /// <remarks>This class is automatically instantiated by the SecondLife class</remarks> public class DirectoryManager { /// <summary> /// The different categories a classified ad can be placed in /// </summary> public enum ClassifiedCategories { /// <summary></summary> Any = 0, /// <summary></summary> Shopping, /// <summary></summary> LandRental, /// <summary></summary> PropertyRental, /// <summary></summary> SpecialAttraction, /// <summary></summary> NewProducts, /// <summary></summary> Employment, /// <summary></summary> Wanted, /// <summary></summary> Service, /// <summary></summary> Personal } public enum EventCategories { All = 0, Discussion = 18, Sports = 19, LiveMusic = 20, Commercial = 22, Nightlife = 23, Games = 24, Pageants = 25, Education = 26, Arts = 27, Charity = 28, Miscellaneous = 29 } /// <summary> /// /// </summary> [Flags] public enum DirFindFlags { /// <summary></summary> People = 1 << 0, /// <summary></summary> Online = 1 << 1, /// <summary></summary> //[Obsolete] //Places = 1 << 2, /// <summary></summary> Events = 1 << 3, /// <summary></summary> Groups = 1 << 4, /// <summary></summary> DateEvents = 1 << 5, /// <summary></summary> AgentOwned = 1 << 6, /// <summary></summary> ForSale = 1 << 7, /// <summary></summary> GroupOwned = 1 << 8, /// <summary></summary> //[Obsolete] //Auction = 1 << 9, /// <summary></summary> DwellSort = 1 << 10, /// <summary></summary> PgSimsOnly = 1 << 11, /// <summary></summary> PicturesOnly = 1 << 12, /// <summary></summary> PgEventsOnly = 1 << 13, /// <summary></summary> MatureSimsOnly = 1 << 14, /// <summary></summary> SortAsc = 1 << 15, /// <summary></summary> PricesSort = 1 << 16, /// <summary></summary> PerMeterSort = 1 << 17, /// <summary></summary> AreaSort = 1 << 18, /// <summary></summary> NameSort = 1 << 19, /// <summary></summary> LimitByPrice = 1 << 20, /// <summary></summary> LimitByArea = 1 << 21 } /// <summary> /// Land types to search dataserver for /// </summary> [Flags] public enum SearchTypeFlags { /// <summary>Do not search</summary> None = 0, /// <summary>Land which is currently up for auction</summary> Auction = 1 << 1, /// <summary>Land available to new landowners (formerly the FirstLand program)</summary> //[Obsolete] //Newbie = 1 << 2, /// <summary>Parcels which are on the mainland (Linden owned) continents</summary> Mainland = 1 << 3, /// <summary>Parcels which are on privately owned simulators</summary> Estate = 1 << 4 } [Flags] public enum EventFlags { None = 0, Mature = 1 << 1 } /// <summary> /// A classified ad in Second Life /// </summary> public struct Classified { /// <summary>UUID for this ad, useful for looking up detailed /// information about it</summary> public LLUUID ID; /// <summary>The title of this classified ad</summary> public string Name; /// <summary>Unknown</summary> public byte Flags; /// <summary>Creation date of the ad</summary> public DateTime CreationDate; /// <summary>Expiration date of the ad</summary> public DateTime ExpirationDate; /// <summary>Price that was paid for this ad</summary> public int Price; } /// <summary> /// A parcel retrieved from the dataserver such as results from the /// "For-Sale" listings /// </summary> public struct DirectoryParcel { /// <summary></summary> public LLUUID ID; /// <summary></summary> public string Name; /// <summary></summary> public int ActualArea; /// <summary></summary> public int SalePrice; /// <summary></summary> public bool Auction; /// <summary></summary> public bool ForSale; } /// <summary> /// An Avatar returned from the dataserver /// </summary> public struct AgentSearchData { /// <summary>Online status of agent</summary> public bool Online; /// <summary>Agents first name</summary> public string FirstName; /// <summary>Agents last name</summary> public string LastName; /// <summary>Agents <seealso cref="T:libsecondlife.LLUUID"/></summary> public LLUUID AgentID; } /// <summary> /// Response to a "Groups" Search /// </summary> public struct GroupSearchData { public LLUUID GroupID; public string GroupName; public int Members; } /// <summary> /// Response to a "Places" Search /// Note: This is not DirPlacesReply /// </summary> public struct PlacesSearchData { public LLUUID OwnerID; public string Name; public string Desc; public int ActualArea; public int BillableArea; public byte Flags; public float GlobalX; public float GlobalY; public float GlobalZ; public string SimName; public LLUUID SnapshotID; public float Dwell; public int Price; } /// <summary> /// Response to "Events" search /// </summary> public struct EventsSearchData { public LLUUID Owner; public string Name; public uint ID; public string Date; public uint Time; public EventFlags Flags; } /// <summary> /// an Event returned from the dataserver /// </summary> public struct EventInfo { public uint ID; public LLUUID Creator; public string Name; public EventCategories Category; public string Desc; public string Date; public UInt32 DateUTC; public UInt32 Duration; public UInt32 Cover; public UInt32 Amount; public string SimName; public LLVector3d GlobalPos; public EventFlags Flags; } /// <summary> /// /// </summary> /// <param name="classifieds"></param> public delegate void ClassifiedReplyCallback(List<Classified> classifieds); /// <summary> /// /// </summary> /// <param name="dirParcels"></param> public delegate void DirLandReplyCallback(List<DirectoryParcel> dirParcels); /// <summary> /// /// </summary> /// <param name="queryID"></param> /// <param name="matchedPeople"></param> public delegate void DirPeopleReplyCallback(LLUUID queryID, List<AgentSearchData> matchedPeople); /// <summary> /// /// </summary> /// <param name="queryID"></param> /// <param name="matchedGroups"></param> public delegate void DirGroupsReplyCallback(LLUUID queryID, List<GroupSearchData> matchedGroups); /// <summary> /// /// </summary> /// <param name="queryID"></param> /// <param name="matchedPlaces"></param> public delegate void PlacesReplyCallback(LLUUID queryID, List<PlacesSearchData> matchedPlaces); /// <summary> /// /// </summary> /// <param name="queryID"></param> /// <param name="matchedEvents"></param> public delegate void EventReplyCallback(LLUUID queryID, List<EventsSearchData> matchedEvents); /// <summary> /// /// </summary> /// <param name="matchedEvent"></param> public delegate void EventInfoCallback(EventInfo matchedEvent); /// <summary> /// /// </summary> public event ClassifiedReplyCallback OnClassifiedReply; /// <summary> /// /// </summary> public event DirLandReplyCallback OnDirLandReply; public event DirPeopleReplyCallback OnDirPeopleReply; public event DirGroupsReplyCallback OnDirGroupsReply; public event PlacesReplyCallback OnPlacesReply; // List of Events public event EventReplyCallback OnEventsReply; // Event Details public event EventInfoCallback OnEventInfo; private SecondLife Client; public DirectoryManager(SecondLife client) { Client = client; Client.Network.RegisterCallback(PacketType.DirClassifiedReply, new NetworkManager.PacketCallback(DirClassifiedReplyHandler)); Client.Network.RegisterCallback(PacketType.DirLandReply, new NetworkManager.PacketCallback(DirLandReplyHandler)); Client.Network.RegisterCallback(PacketType.DirPeopleReply, new NetworkManager.PacketCallback(DirPeopleReplyHandler)); Client.Network.RegisterCallback(PacketType.DirGroupsReply, new NetworkManager.PacketCallback(DirGroupsReplyHandler)); Client.Network.RegisterCallback(PacketType.PlacesReply, new NetworkManager.PacketCallback(PlacesReplyHandler)); Client.Network.RegisterCallback(PacketType.DirEventsReply, new NetworkManager.PacketCallback(EventsReplyHandler)); Client.Network.RegisterCallback(PacketType.EventInfoReply, new NetworkManager.PacketCallback(EventInfoReplyHandler)); } public LLUUID StartClassifiedSearch(string searchText, ClassifiedCategories categories, bool mature) { DirClassifiedQueryPacket query = new DirClassifiedQueryPacket(); LLUUID queryID = LLUUID.Random(); query.AgentData.AgentID = Client.Self.AgentID; query.AgentData.SessionID = Client.Self.SessionID; query.QueryData.Category = (uint)categories; query.QueryData.QueryFlags = (uint)(mature ? 0 : 2); query.QueryData.QueryID = queryID; query.QueryData.QueryText = Helpers.StringToField(searchText); Client.Network.SendPacket(query); return queryID; } /// <summary> /// Starts a search for land sales using the directory /// </summary> /// <param name="typeFlags">What type of land to search for. Auction, /// estate, mainland, "first land", etc</param> /// <returns>A unique identifier that can identify packets associated /// with this query from other queries</returns> /// <remarks>The OnDirLandReply event handler must be registered before /// calling this function. There is no way to determine how many /// results will be returned, or how many times the callback will be /// fired other than you won't get more than 100 total parcels from /// each query.</remarks> public LLUUID StartLandSearch(SearchTypeFlags typeFlags) { return StartLandSearch(DirFindFlags.SortAsc | DirFindFlags.PerMeterSort, typeFlags, 0, 0, 0); } /// <summary> /// Starts a search for land sales using the directory /// </summary> /// <param name="typeFlags">What type of land to search for. Auction, /// estate, mainland, "first land", etc</param> /// <param name="priceLimit">Maximum price to search for</param> /// <param name="areaLimit">Maximum area to search for</param> /// <param name="queryStart">Each request is limited to 100 parcels /// being returned. To get the first 100 parcels of a request use 0, /// from 100-199 use 1, 200-299 use 2, etc.</param> /// <returns>A unique identifier that can identify packets associated /// with this query from other queries</returns> /// <remarks>The OnDirLandReply event handler must be registered before /// calling this function. There is no way to determine how many /// results will be returned, or how many times the callback will be /// fired other than you won't get more than 100 total parcels from /// each query.</remarks> public LLUUID StartLandSearch(SearchTypeFlags typeFlags, int priceLimit, int areaLimit, int queryStart) { return StartLandSearch(DirFindFlags.SortAsc | DirFindFlags.PerMeterSort | DirFindFlags.LimitByPrice | DirFindFlags.LimitByArea, typeFlags, priceLimit, areaLimit, queryStart); } /// <summary> /// Starts a search for land sales using the directory /// </summary> /// <param name="findFlags">A flags parameter that can modify the way /// search results are returned, for example changing the ordering of /// results or limiting based on price or area</param> /// <param name="typeFlags">What type of land to search for. Auction, /// estate, mainland, "first land", etc</param> /// <param name="priceLimit">Maximum price to search for, the /// DirFindFlags.LimitByPrice flag must be set</param> /// <param name="areaLimit">Maximum area to search for, the /// DirFindFlags.LimitByArea flag must be set</param> /// <param name="queryStart">Each request is limited to 100 parcels /// being returned. To get the first 100 parcels of a request use 0, /// from 100-199 use 100, 200-299 use 200, etc.</param> /// <returns>A unique identifier that can identify packets associated /// with this query from other queries</returns> /// <remarks>The OnDirLandReply event handler must be registered before /// calling this function. There is no way to determine how many /// results will be returned, or how many times the callback will be /// fired other than you won't get more than 100 total parcels from /// each query.</remarks> public LLUUID StartLandSearch(DirFindFlags findFlags, SearchTypeFlags typeFlags, int priceLimit, int areaLimit, int queryStart) { LLUUID queryID = LLUUID.Random(); DirLandQueryPacket query = new DirLandQueryPacket(); query.AgentData.AgentID = Client.Self.AgentID; query.AgentData.SessionID = Client.Self.SessionID; query.QueryData.Area = areaLimit; query.QueryData.Price = priceLimit; query.QueryData.QueryStart = queryStart; query.QueryData.SearchType = (uint)typeFlags; query.QueryData.QueryFlags = (uint)findFlags; query.QueryData.QueryID = queryID; Client.Network.SendPacket(query); return queryID; } /// <summary> /// Starts a search for a Group in the directory manager /// </summary> /// <param name="findFlags"></param> /// <param name="searchText">The text to search for</param> /// <param name="queryStart">Each request is limited to 100 parcels /// being returned. To get the first 100 parcels of a request use 0, /// from 100-199 use 100, 200-299 use 200, etc.</param> /// <returns>A unique identifier that can identify packets associated /// with this query from other queries</returns> /// <remarks>The OnDirLandReply event handler must be registered before /// calling this function. There is no way to determine how many /// results will be returned, or how many times the callback will be /// fired other than you won't get more than 100 total parcels from /// each query.</remarks> public LLUUID StartGroupSearch(DirFindFlags findFlags, string searchText, int queryStart) { return StartGroupSearch(findFlags, searchText, queryStart, LLUUID.Random()); } public LLUUID StartGroupSearch(DirFindFlags findFlags, string searchText, int queryStart, LLUUID queryID) { DirFindQueryPacket find = new DirFindQueryPacket(); find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryFlags = (uint)findFlags; find.QueryData.QueryText = Helpers.StringToField(searchText); find.QueryData.QueryID = queryID; find.QueryData.QueryStart = queryStart; Client.Network.SendPacket(find); return queryID; } public LLUUID StartPeopleSearch(DirFindFlags findFlags, string searchText, int queryStart) { return StartPeopleSearch(findFlags, searchText, queryStart, LLUUID.Random()); } public LLUUID StartPeopleSearch(DirFindFlags findFlags, string searchText, int queryStart, LLUUID queryID) { DirFindQueryPacket find = new DirFindQueryPacket(); find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryFlags = (uint)findFlags; find.QueryData.QueryText = Helpers.StringToField(searchText); find.QueryData.QueryID = queryID; find.QueryData.QueryStart = queryStart; Client.Network.SendPacket(find); return queryID; } /// <summary> /// Search "places" for Land you personally own /// </summary> public LLUUID StartPlacesSearch() { return StartPlacesSearch(DirFindFlags.AgentOwned, Parcel.ParcelCategory.Any, String.Empty, String.Empty, LLUUID.Zero, LLUUID.Zero); } /// <summary> /// Searches Places for Land owned by a specific user or group /// </summary> /// <param name="findFlags">One of the Values from the DirFindFlags struct, ie: AgentOwned, GroupOwned, etc.</param> /// <param name="groupID">LLUID of group you want to recieve land list for (You must be in group), or /// LLUID.Zero for Your own land</param> /// <returns>Transaction (Query) ID which can be associated with results from your request.</returns> public LLUUID StartPlacesSearch(DirFindFlags findFlags, LLUUID groupID) { return StartPlacesSearch(findFlags, Parcel.ParcelCategory.Any, String.Empty, String.Empty, groupID, LLUUID.Random()); } /// <summary> /// Search Places /// </summary> /// <param name="findFlags">One of the Values from the DirFindFlags struct, ie: AgentOwned, GroupOwned, etc.</param> /// <param name="searchCategory">One of the values from the SearchCategory Struct, ie: Any, Linden, Newcomer</param> /// <param name="groupID">LLUID of group you want to recieve results for</param> /// <param name="transactionID">Transaction (Query) ID which can be associated with results from your request.</param> /// <returns>Transaction (Query) ID which can be associated with results from your request.</returns> public LLUUID StartPlacesSearch(DirFindFlags findFlags, Parcel.ParcelCategory searchCategory, LLUUID groupID, LLUUID transactionID) { return StartPlacesSearch(findFlags, searchCategory, String.Empty, String.Empty, groupID, transactionID); } /// <summary> /// Search Places - All Options /// </summary> /// <param name="findFlags">One of the Values from the DirFindFlags struct, ie: AgentOwned, GroupOwned, etc.</param> /// <param name="searchCategory">One of the values from the SearchCategory Struct, ie: Any, Linden, Newcomer</param> /// <param name="searchText">String Text to search for</param> /// <param name="simulatorName">String Simulator Name to search in</param> /// <param name="groupID">LLUID of group you want to recieve results for</param> /// <param name="transactionID">Transaction (Query) ID which can be associated with results from your request.</param> /// <returns>Transaction (Query) ID which can be associated with results from your request.</returns> public LLUUID StartPlacesSearch(DirFindFlags findFlags, Parcel.ParcelCategory searchCategory, string searchText, string simulatorName, LLUUID groupID, LLUUID transactionID) { PlacesQueryPacket find = new PlacesQueryPacket(); find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.AgentData.QueryID = groupID; find.TransactionData.TransactionID = transactionID; find.QueryData.QueryText = Helpers.StringToField(searchText); find.QueryData.QueryFlags = (uint)findFlags; find.QueryData.Category = (sbyte)searchCategory; find.QueryData.SimName = Helpers.StringToField(simulatorName); Client.Network.SendPacket(find); return transactionID; } /// <summary> /// Search All Events with specifid searchText in all categories, includes Mature /// </summary> /// <param name="searchText">Text to search for</param> /// <returns>UUID of query to correlate results in callback.</returns> public LLUUID StartEventsSearch(string searchText) { return StartEventsSearch(searchText, true, EventCategories.All); } /// <summary> /// Search Events with Options to specify category and Mature events. /// </summary> /// <param name="searchText">Text to search for</param> /// <param name="showMature">true to include Mature events</param> /// <param name="category">category to search</param> /// <returns>UUID of query to correlate results in callback.</returns> public LLUUID StartEventsSearch(string searchText, bool showMature, EventCategories category) { return StartEventsSearch(searchText, showMature, "u", 0, category, LLUUID.Random()); } /// <summary> /// Search Events - ALL options /// </summary> /// <param name="searchText">string text to search for e.g.: live music</param> /// <param name="showMature">Include mature events in results</param> /// <param name="eventDay">"u" for now and upcoming events, -or- number of days since/until event is scheduled /// For example "0" = Today, "1" = tomorrow, "2" = following day, "-1" = yesterday, etc.</param> /// <param name="queryStart">Page # to show, 0 for First Page</param> /// <param name="category">EventCategory event is listed under.</param> /// <param name="queryID">a LLUUID that can be used to track queries with results.</param> /// <returns>UUID of query to correlate results in callback.</returns> public LLUUID StartEventsSearch(string searchText, bool showMature, string eventDay, uint queryStart, EventCategories category, LLUUID queryID) { DirFindQueryPacket find = new DirFindQueryPacket(); find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.QueryData.QueryID = queryID; find.QueryData.QueryText = Helpers.StringToField(eventDay + "|" + (int)category + "|" + searchText); find.QueryData.QueryFlags = showMature ? (uint)32 : (uint)8224; find.QueryData.QueryStart = (int)queryStart; Client.Network.SendPacket(find); return queryID; } /// <summary>Requests Event Details</summary> /// <param name="eventID">ID of Event returned from Places Search</param> public void EventInfoRequest(uint eventID) { EventInfoRequestPacket find = new EventInfoRequestPacket(); find.AgentData.AgentID = Client.Self.AgentID; find.AgentData.SessionID = Client.Self.SessionID; find.EventData.EventID = eventID; Client.Network.SendPacket(find); } #region Blocking Functions public bool PeopleSearch(DirFindFlags findFlags, string searchText, int queryStart, int timeoutMS, out List<AgentSearchData> results) { AutoResetEvent searchEvent = new AutoResetEvent(false); LLUUID id = LLUUID.Random(); List<AgentSearchData> people = null; DirPeopleReplyCallback callback = delegate(LLUUID queryid, List<AgentSearchData> matches) { if (id == queryid) { people = matches; searchEvent.Set(); } }; OnDirPeopleReply += callback; StartPeopleSearch(findFlags, searchText, queryStart, id); searchEvent.WaitOne(timeoutMS, false); OnDirPeopleReply -= callback; results = people; return (results != null); } #endregion Blocking Functions #region Packet Handlers private void DirClassifiedReplyHandler(Packet packet, Simulator simulator) { if (OnClassifiedReply != null) { DirClassifiedReplyPacket reply = (DirClassifiedReplyPacket)packet; List<Classified> classifieds = new List<Classified>(); foreach (DirClassifiedReplyPacket.QueryRepliesBlock block in reply.QueryReplies) { Classified classified = new Classified(); classified.CreationDate = Helpers.UnixTimeToDateTime(block.CreationDate); classified.ExpirationDate = Helpers.UnixTimeToDateTime(block.ExpirationDate); classified.Flags = block.ClassifiedFlags; classified.ID = block.ClassifiedID; classified.Name = Helpers.FieldToUTF8String(block.Name); classified.Price = block.PriceForListing; classifieds.Add(classified); } try { OnClassifiedReply(classifieds); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } private void DirLandReplyHandler(Packet packet, Simulator simulator) { if (OnDirLandReply != null) { List<DirectoryParcel> parcelsForSale = new List<DirectoryParcel>(); DirLandReplyPacket reply = (DirLandReplyPacket)packet; foreach (DirLandReplyPacket.QueryRepliesBlock block in reply.QueryReplies) { DirectoryParcel dirParcel = new DirectoryParcel(); dirParcel.ActualArea = block.ActualArea; dirParcel.ID = block.ParcelID; dirParcel.Name = Helpers.FieldToUTF8String(block.Name); dirParcel.SalePrice = block.SalePrice; dirParcel.Auction = block.Auction; dirParcel.ForSale = block.ForSale; parcelsForSale.Add(dirParcel); } try { OnDirLandReply(parcelsForSale); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } protected void DirPeopleReplyHandler(Packet packet, Simulator simulator) { if (OnDirPeopleReply != null) { DirPeopleReplyPacket peopleReply = packet as DirPeopleReplyPacket; List<AgentSearchData> matches = new List<AgentSearchData>(peopleReply.QueryReplies.Length); foreach (DirPeopleReplyPacket.QueryRepliesBlock reply in peopleReply.QueryReplies) { AgentSearchData searchData = new AgentSearchData(); searchData.Online = reply.Online; searchData.FirstName = Helpers.FieldToUTF8String(reply.FirstName); searchData.LastName = Helpers.FieldToUTF8String(reply.LastName); searchData.AgentID = reply.AgentID; matches.Add(searchData); } try { OnDirPeopleReply(peopleReply.QueryData.QueryID, matches); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } protected void DirGroupsReplyHandler(Packet packet, Simulator simulator) { if (OnDirGroupsReply != null) { DirGroupsReplyPacket groupsReply = packet as DirGroupsReplyPacket; List<GroupSearchData> matches = new List<GroupSearchData>(groupsReply.QueryReplies.Length); foreach (DirGroupsReplyPacket.QueryRepliesBlock reply in groupsReply.QueryReplies) { GroupSearchData groupsData = new GroupSearchData(); groupsData.GroupID = reply.GroupID; groupsData.GroupName = Helpers.FieldToUTF8String(reply.GroupName); groupsData.Members = reply.Members; matches.Add(groupsData); } try { OnDirGroupsReply(groupsReply.QueryData.QueryID, matches); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } private void PlacesReplyHandler(Packet packet, Simulator simulator) { if (OnPlacesReply != null) { PlacesReplyPacket placesReply = packet as PlacesReplyPacket; List<PlacesSearchData> places = new List<PlacesSearchData>(); foreach (PlacesReplyPacket.QueryDataBlock block in placesReply.QueryData) { PlacesSearchData place = new PlacesSearchData(); place.OwnerID = block.OwnerID; place.Name = Helpers.FieldToUTF8String(block.Name); place.Desc = Helpers.FieldToUTF8String(block.Desc); place.ActualArea = block.ActualArea; place.BillableArea = block.BillableArea; place.Flags = block.Flags; place.GlobalX = block.GlobalX; place.GlobalY = block.GlobalY; place.GlobalZ = block.GlobalZ; place.SimName = Helpers.FieldToUTF8String(block.SimName); place.SnapshotID = block.SnapshotID; place.Dwell = block.Dwell; place.Price = block.Price; places.Add(place); } try { OnPlacesReply(placesReply.TransactionData.TransactionID, places); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } private void EventsReplyHandler(Packet packet, Simulator simulator) { if (OnEventsReply != null) { DirEventsReplyPacket eventsReply = packet as DirEventsReplyPacket; List<EventsSearchData> matches = new List<EventsSearchData>(eventsReply.QueryReplies.Length); foreach (DirEventsReplyPacket.QueryRepliesBlock reply in eventsReply.QueryReplies) { EventsSearchData eventsData = new EventsSearchData(); eventsData.Owner = reply.OwnerID; eventsData.Name = Helpers.FieldToUTF8String(reply.Name); eventsData.ID = reply.EventID; eventsData.Date = Helpers.FieldToUTF8String(reply.Date); eventsData.Time = reply.UnixTime; eventsData.Flags = (EventFlags)reply.EventFlags; matches.Add(eventsData); } try { OnEventsReply(eventsReply.QueryData.QueryID, matches); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } private void EventInfoReplyHandler(Packet packet, Simulator simulator) { if (OnEventInfo != null) { EventInfoReplyPacket eventReply = (EventInfoReplyPacket)packet; EventInfo evinfo = new EventInfo(); evinfo.ID = eventReply.EventData.EventID; evinfo.Name = Helpers.FieldToUTF8String(eventReply.EventData.Name); evinfo.Desc = Helpers.FieldToUTF8String(eventReply.EventData.Desc); evinfo.Amount = eventReply.EventData.Amount; evinfo.Category = (EventCategories)Helpers.BytesToUInt(eventReply.EventData.Category); evinfo.Cover = eventReply.EventData.Cover; evinfo.Creator = (LLUUID)Helpers.FieldToUTF8String(eventReply.EventData.Creator); evinfo.Date = Helpers.FieldToUTF8String(eventReply.EventData.Date); evinfo.DateUTC = eventReply.EventData.DateUTC; evinfo.Duration = eventReply.EventData.Duration; evinfo.Flags = (EventFlags)eventReply.EventData.EventFlags; evinfo.SimName = Helpers.FieldToUTF8String(eventReply.EventData.SimName); evinfo.GlobalPos = eventReply.EventData.GlobalPos; try { OnEventInfo(evinfo); } catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } } #endregion Packet Handlers } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.PythonTools { /// <summary> /// Provides classification based upon the DLR TokenCategory enum. /// </summary> internal sealed class PythonClassifier : IClassifier { private readonly TokenCache _tokenCache; private readonly PythonClassifierProvider _provider; private readonly ITextBuffer _buffer; private PythonLanguageVersion _version; [ThreadStatic] private static Dictionary<PythonLanguageVersion, Tokenizer> _tokenizers; // tokenizer for each version, shared between all buffers internal PythonClassifier(PythonClassifierProvider provider, ITextBuffer buffer) { buffer.Changed += BufferChanged; buffer.ContentTypeChanged += BufferContentTypeChanged; _tokenCache = new TokenCache(); _provider = provider; _buffer = buffer; _buffer.RegisterForNewAnalysisEntry(NewAnalysisEntry); var analyzer = _buffer.GetAnalyzer(provider._serviceProvider); Debug.Assert(analyzer != null); _version = analyzer.InterpreterFactory.GetLanguageVersion(); } private void NewAnalysisEntry(AnalysisEntry entry) { var analyzer = entry.Analyzer; var newVersion = _version; if (newVersion != _version) { _tokenCache.Clear(); Debug.Assert(analyzer != null); _version = analyzer.InterpreterFactory.GetLanguageVersion(); var changed = ClassificationChanged; if (changed != null) { var snapshot = _buffer.CurrentSnapshot; changed(this, new ClassificationChangedEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length))); } } } #region IDlrClassifier // This event gets raised if the classification of existing test changes. public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged; /// <summary> /// This method classifies the given snapshot span. /// </summary> public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { var classifications = new List<ClassificationSpan>(); var snapshot = span.Snapshot; if (span.Length > 0) { // don't add classifications for REPL commands. if (!span.Snapshot.IsReplBufferWithCommand()) { AddClassifications(GetTokenizer(), classifications, span); } } return classifications; } private Tokenizer GetTokenizer() { if (_tokenizers == null) { _tokenizers = new Dictionary<PythonLanguageVersion, Tokenizer>(); } Tokenizer res; if (!_tokenizers.TryGetValue(_version, out res)) { _tokenizers[_version] = res = new Tokenizer(_version, options: TokenizerOptions.Verbatim | TokenizerOptions.VerbatimCommentsAndLineJoins); } return res; } public PythonClassifierProvider Provider { get { return _provider; } } #endregion #region Private Members private Dictionary<TokenCategory, IClassificationType> CategoryMap { get { return _provider.CategoryMap; } } private void BufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e) { _tokenCache.Clear(); _buffer.Changed -= BufferChanged; _buffer.ContentTypeChanged -= BufferContentTypeChanged; _buffer.Properties.RemoveProperty(typeof(PythonClassifier)); _buffer.UnregisterForNewAnalysisEntry(NewAnalysisEntry); } private void BufferChanged(object sender, TextContentChangedEventArgs e) { var snapshot = e.After; if (!snapshot.IsReplBufferWithCommand()) { _tokenCache.EnsureCapacity(snapshot.LineCount); var tokenizer = GetTokenizer(); foreach (var change in e.Changes) { if (change.LineCountDelta > 0) { _tokenCache.InsertLines(snapshot.GetLineNumberFromPosition(change.NewEnd) + 1 - change.LineCountDelta, change.LineCountDelta); } else if (change.LineCountDelta < 0) { _tokenCache.DeleteLines(snapshot.GetLineNumberFromPosition(change.NewEnd) + 1, -change.LineCountDelta); } ApplyChange(tokenizer, snapshot, change.NewSpan); } } } /// <summary> /// Adds classification spans to the given collection. /// Scans a contiguous sub-<paramref name="span"/> of a larger code span which starts at <paramref name="codeStartLine"/>. /// </summary> private void AddClassifications(Tokenizer tokenizer, List<ClassificationSpan> classifications, SnapshotSpan span) { Debug.Assert(span.Length > 0); var snapshot = span.Snapshot; int firstLine = snapshot.GetLineNumberFromPosition(span.Start); int lastLine = snapshot.GetLineNumberFromPosition(span.End - 1); Contract.Assert(firstLine >= 0); _tokenCache.EnsureCapacity(snapshot.LineCount); // find the closest line preceding firstLine for which we know categorizer state, stop at the codeStartLine: LineTokenization lineTokenization; int currentLine = _tokenCache.IndexOfPreviousTokenization(firstLine, 0, out lineTokenization) + 1; object state = lineTokenization.State; while (currentLine <= lastLine) { if (!_tokenCache.TryGetTokenization(currentLine, out lineTokenization)) { lineTokenization = TokenizeLine(tokenizer, snapshot, state, currentLine); _tokenCache[currentLine] = lineTokenization; } state = lineTokenization.State; for (int i = 0; i < lineTokenization.Tokens.Length; i++) { var token = lineTokenization.Tokens[i]; if (token.Category == TokenCategory.IncompleteMultiLineStringLiteral) { // we need to walk backwards to find the start of this multi-line string... TokenInfo startToken = token; int validPrevLine; int length = startToken.SourceSpan.Length; if (i == 0) { length += GetLeadingMultiLineStrings(tokenizer, snapshot, firstLine, currentLine, out validPrevLine, ref startToken); } else { validPrevLine = currentLine; } if (i == lineTokenization.Tokens.Length - 1) { length += GetTrailingMultiLineStrings(tokenizer, snapshot, currentLine, state); } var multiStrSpan = new Span(SnapshotSpanToSpan(snapshot, startToken, validPrevLine).Start, length); classifications.Add( new ClassificationSpan( new SnapshotSpan(snapshot, multiStrSpan), _provider.StringLiteral ) ); } else { var classification = ClassifyToken(span, token, currentLine); if (classification != null) { classifications.Add(classification); } } } currentLine++; } } private int GetLeadingMultiLineStrings(Tokenizer tokenizer, ITextSnapshot snapshot, int firstLine, int currentLine, out int validPrevLine, ref TokenInfo startToken) { validPrevLine = currentLine; int prevLine = currentLine - 1; int length = 0; while (prevLine >= 0) { LineTokenization prevLineTokenization; if (!_tokenCache.TryGetTokenization(prevLine, out prevLineTokenization)) { LineTokenization lineTokenizationTemp; int currentLineTemp = _tokenCache.IndexOfPreviousTokenization(firstLine, 0, out lineTokenizationTemp) + 1; object stateTemp = lineTokenizationTemp.State; while (currentLineTemp <= snapshot.LineCount) { if (!_tokenCache.TryGetTokenization(currentLineTemp, out lineTokenizationTemp)) { lineTokenizationTemp = TokenizeLine(tokenizer, snapshot, stateTemp, currentLineTemp); _tokenCache[currentLineTemp] = lineTokenizationTemp; } stateTemp = lineTokenizationTemp.State; } prevLineTokenization = TokenizeLine(tokenizer, snapshot, stateTemp, prevLine); _tokenCache[prevLine] = prevLineTokenization; } if (prevLineTokenization.Tokens.Length != 0) { if (prevLineTokenization.Tokens[prevLineTokenization.Tokens.Length - 1].Category != TokenCategory.IncompleteMultiLineStringLiteral) { break; } startToken = prevLineTokenization.Tokens[prevLineTokenization.Tokens.Length - 1]; length += startToken.SourceSpan.Length; } validPrevLine = prevLine; prevLine--; if (prevLineTokenization.Tokens.Length > 1) { // http://pytools.codeplex.com/workitem/749 // if there are multiple tokens on this line then our multi-line string // is terminated. break; } } return length; } private int GetTrailingMultiLineStrings(Tokenizer tokenizer, ITextSnapshot snapshot, int currentLine, object state) { int nextLine = currentLine + 1; var prevState = state; int length = 0; while (nextLine < snapshot.LineCount) { LineTokenization nextLineTokenization; if (!_tokenCache.TryGetTokenization(nextLine, out nextLineTokenization)) { nextLineTokenization = TokenizeLine(tokenizer, snapshot, prevState, nextLine); prevState = nextLineTokenization.State; _tokenCache[nextLine] = nextLineTokenization; } if (nextLineTokenization.Tokens.Length != 0) { if (nextLineTokenization.Tokens[0].Category != TokenCategory.IncompleteMultiLineStringLiteral) { break; } length += nextLineTokenization.Tokens[0].SourceSpan.Length; } nextLine++; } return length; } /// <summary> /// Rescans the part of the buffer affected by a change. /// Scans a contiguous sub-<paramref name="span"/> of a larger code span which starts at <paramref name="codeStartLine"/>. /// </summary> private void ApplyChange(Tokenizer tokenizer, ITextSnapshot snapshot, Span span) { int firstLine = snapshot.GetLineNumberFromPosition(span.Start); int lastLine = snapshot.GetLineNumberFromPosition(span.Length > 0 ? span.End - 1 : span.End); Contract.Assert(firstLine >= 0); // find the closest line preceding firstLine for which we know categorizer state, stop at the codeStartLine: LineTokenization lineTokenization; firstLine = _tokenCache.IndexOfPreviousTokenization(firstLine, 0, out lineTokenization) + 1; object state = lineTokenization.State; int currentLine = firstLine; object previousState; while (currentLine < snapshot.LineCount) { previousState = _tokenCache.TryGetTokenization(currentLine, out lineTokenization) ? lineTokenization.State : null; _tokenCache[currentLine] = lineTokenization = TokenizeLine(tokenizer, snapshot, state, currentLine); state = lineTokenization.State; // stop if we visted all affected lines and the current line has no tokenization state or its previous state is the same as the new state: if (currentLine > lastLine && (previousState == null || previousState.Equals(state))) { break; } currentLine++; } // classification spans might have changed between the start of the first and end of the last visited line: int changeStart = snapshot.GetLineFromLineNumber(firstLine).Start; int changeEnd = (currentLine < snapshot.LineCount) ? snapshot.GetLineFromLineNumber(currentLine).End : snapshot.Length; if (changeStart < changeEnd) { var classificationChanged = ClassificationChanged; if (classificationChanged != null) { var args = new ClassificationChangedEventArgs(new SnapshotSpan(snapshot, new Span(changeStart, changeEnd - changeStart))); classificationChanged(this, args); } } } private LineTokenization TokenizeLine(Tokenizer tokenizer, ITextSnapshot snapshot, object previousLineState, int lineNo) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(lineNo); SnapshotSpan lineSpan = new SnapshotSpan(snapshot, line.Start, line.LengthIncludingLineBreak); var tcp = new SnapshotSpanSourceCodeReader(lineSpan); tokenizer.Initialize(previousLineState, tcp, new SourceLocation(line.Start.Position, lineNo + 1, 1)); try { var tokens = tokenizer.ReadTokens(lineSpan.Length).ToArray(); return new LineTokenization(tokens, tokenizer.CurrentState); } finally { tokenizer.Uninitialize(); } } private ClassificationSpan ClassifyToken(SnapshotSpan span, TokenInfo token, int lineNumber) { IClassificationType classification = null; if (token.Category == TokenCategory.Operator) { if (token.Trigger == TokenTriggers.MemberSelect) { classification = _provider.DotClassification; } } else if (token.Category == TokenCategory.Grouping) { if ((token.Trigger & TokenTriggers.MatchBraces) != 0) { classification = _provider.GroupingClassification; } } else if (token.Category == TokenCategory.Delimiter) { if (token.Trigger == TokenTriggers.ParameterNext) { classification = _provider.CommaClassification; } } if (classification == null) { CategoryMap.TryGetValue(token.Category, out classification); } if (classification != null) { var tokenSpan = SnapshotSpanToSpan(span.Snapshot, token, lineNumber); var intersection = span.Intersection(tokenSpan); if (intersection != null && intersection.Value.Length > 0 || (span.Length == 0 && tokenSpan.Contains(span.Start))) { // handle zero-length spans which Intersect and Overlap won't return true on ever. return new ClassificationSpan(new SnapshotSpan(span.Snapshot, tokenSpan), classification); } } return null; } private static Span SnapshotSpanToSpan(ITextSnapshot snapshot, TokenInfo token, int lineNumber) { var line = snapshot.GetLineFromLineNumber(lineNumber); var index = line.Start.Position + token.SourceSpan.Start.Column - 1; var tokenSpan = new Span(index, token.SourceSpan.Length); return tokenSpan; } #endregion } internal static partial class ClassifierExtensions { public static PythonClassifier GetPythonClassifier(this ITextBuffer buffer) { PythonClassifier res; if (buffer.Properties.TryGetProperty<PythonClassifier>(typeof(PythonClassifier), out res)) { return res; } return null; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CK.Text { /// <summary> /// Small JSON visitor. /// </summary> [Obsolete("Please use System.Text.Json now!")] public class JSONVisitor { readonly StringMatcher _m; readonly List<Parent> _path; /// <summary> /// Describes a parent object: it is the name of a property and its index or the index in a array. /// </summary> public struct Parent { /// <summary> /// The name of the property or null if this is an array entry. /// </summary> public readonly string PropertyName; /// <summary> /// The index in the array or the property number (the count of properties /// that appear before this one in the object definition). /// </summary> public readonly int Index; /// <summary> /// Gets whether this is an array cell (ie. <see cref="PropertyName"/> is null). /// </summary> public bool IsArrayCell => PropertyName == null; /// <summary> /// Initializes a new parent object. /// </summary> /// <param name="propertyName">Name of the property. Null for an array entry.</param> /// <param name="index">Index of the property or index in an array.</param> public Parent( string propertyName, int index ) { PropertyName = propertyName; Index = index; } /// <summary> /// Overridden to return either <see cref="PropertyName"/> or [<see cref="Index"/>]. /// </summary> /// <returns>Representation of the accessor.</returns> public override string ToString() { return IsArrayCell ? '[' + Index.ToString( CultureInfo.InvariantCulture ) + ']' : PropertyName; } } /// <summary> /// Initializes a new <see cref="JSONVisitor"/> bound to a <see cref="Matcher"/>. /// </summary> /// <param name="m">The string matcher.</param> public JSONVisitor( StringMatcher m ) { _m = m; _path = new List<Parent>(); } /// <summary> /// Initializes a new <see cref="JSONVisitor"/> on a string. /// A <see cref="Matcher"/> is automatically created. /// </summary> /// <param name="s">The string to parse.</param> public JSONVisitor( string s ) : this( new StringMatcher( s ) ) { } /// <summary> /// Get the <see cref="StringMatcher"/> to which this visitor is bound. /// </summary> public StringMatcher Matcher => _m; /// <summary> /// Gets the current path of the visited item. /// </summary> protected IReadOnlyList<Parent> Path => _path; /// <summary> /// Visits any json item: it is either a terminal (<see cref="VisitTerminalValue"/>), /// {"an":"object"} (see <see cref="VisitObjectContent"/> or ["an","array"] (see <see cref="VisitArrayContent"/>). /// </summary> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> public virtual bool Visit() { SkipWhiteSpaces(); if( _m.TryMatchChar( '{' ) ) return VisitObjectContent(); if( _m.TryMatchChar( '[' ) ) return VisitArrayContent(); return VisitTerminalValue(); } /// <summary> /// Visits a comma seprarated list of "property" : ... fields until a closing } is found /// or <see cref="Matcher"/>.<see cref="StringMatcher.IsEnd">IsEnd</see> becomes true. /// </summary> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> public virtual bool VisitObjectContent() { int propertyNumber = 0; while( !_m.IsEnd ) { SkipWhiteSpaces(); if( _m.TryMatchChar( '}' ) ) return true; int startPropertyIndex = _m.StartIndex; string propName; if( !_m.TryMatchJSONQuotedString( out propName ) ) return false; SkipWhiteSpaces(); if( !_m.MatchChar( ':' ) || !VisitObjectProperty( startPropertyIndex, propName, propertyNumber ) ) return false; SkipWhiteSpaces(); // This accepts e trailing comma at the end of a property list: ..."a":0,} is not an error. _m.TryMatchChar( ',' ); ++propertyNumber; } return false; } /// <summary> /// Visits a "property" : ... JSON property. /// </summary> /// <param name="startPropertyIndex"> /// Starting index of the <paramref name="propertyName"/> in <see cref="Matcher"/>: /// this is the index of the opening quote ". /// </param> /// <param name="propertyName">Parsed property name.</param> /// <param name="propertyNumber">Zero based number of the property in the <see cref="Parent"/> object.</param> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> protected virtual bool VisitObjectProperty( int startPropertyIndex, string propertyName, int propertyNumber ) { try { _path.Add( new Parent( propertyName, propertyNumber ) ); return Visit(); } finally { _path.RemoveAt( _path.Count - 1 ); } } /// <summary> /// Visits a comma seprarated list of json items until a closing ']' is found. /// </summary> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> public virtual bool VisitArrayContent() { int cellNumber = 0; while( !_m.IsEnd ) { SkipWhiteSpaces(); if( _m.TryMatchChar( ']' ) ) return true; if( !VisitArrayCell( cellNumber ) ) return false; SkipWhiteSpaces(); _m.TryMatchChar( ',' ); ++cellNumber; } return false; } /// <summary> /// Visits a cell in a <see cref="Parent"/> array. /// </summary> /// <param name="cellNumber">Zero based cell nummber.</param> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> protected virtual bool VisitArrayCell( int cellNumber ) { try { _path.Add( new Parent( null, cellNumber ) ); return Visit(); } finally { _path.RemoveAt( _path.Count - 1 ); } } /// <summary> /// Visits a terminal value. This method simply calls <see cref="StringMatcher.MatchWhiteSpaces(int)">Matcher.MatchWhiteSpaces(0)</see> /// to skip any whitespace and <see cref="StringMatcherTextExtension.TryMatchJSONTerminalValue(StringMatcher)">TryMatchJSONTerminalValue</see> /// to skip the value itself. /// </summary> /// <returns>True on success. On error a message may be retrieved from the <see cref="Matcher"/>.</returns> protected virtual bool VisitTerminalValue() { SkipWhiteSpaces(); return _m.TryMatchJSONTerminalValue() || _m.SetError(); } /// <summary> /// Skips white spaces: simply calls <see cref="StringMatcher.MatchWhiteSpaces(int)"/> /// with 0 minimal count of spaces. /// </summary> protected virtual void SkipWhiteSpaces() { _m.MatchWhiteSpaces( 0 ); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Reflection; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics.Application; namespace System.ServiceModel.Dispatcher { internal class ImmutableClientRuntime { private int _correlationCount; private bool _addTransactionFlowProperties; private IInteractiveChannelInitializer[] _interactiveChannelInitializers; private IClientOperationSelector _operationSelector; private IChannelInitializer[] _channelInitializers; private IClientMessageInspector[] _messageInspectors; private Dictionary<string, ProxyOperationRuntime> _operations; private ProxyOperationRuntime _unhandled; private bool _useSynchronizationContext; private bool _validateMustUnderstand; internal ImmutableClientRuntime(ClientRuntime behavior) { _channelInitializers = EmptyArray<IChannelInitializer>.ToArray(behavior.ChannelInitializers); _interactiveChannelInitializers = EmptyArray<IInteractiveChannelInitializer>.ToArray(behavior.InteractiveChannelInitializers); _messageInspectors = EmptyArray<IClientMessageInspector>.ToArray(behavior.MessageInspectors); _operationSelector = behavior.OperationSelector; _useSynchronizationContext = behavior.UseSynchronizationContext; _validateMustUnderstand = behavior.ValidateMustUnderstand; _unhandled = new ProxyOperationRuntime(behavior.UnhandledClientOperation, this); _addTransactionFlowProperties = behavior.AddTransactionFlowProperties; _operations = new Dictionary<string, ProxyOperationRuntime>(); for (int i = 0; i < behavior.Operations.Count; i++) { ClientOperation operation = behavior.Operations[i]; ProxyOperationRuntime operationRuntime = new ProxyOperationRuntime(operation, this); _operations.Add(operation.Name, operationRuntime); } _correlationCount = _messageInspectors.Length + behavior.MaxParameterInspectors; } internal int MessageInspectorCorrelationOffset { get { return 0; } } internal int ParameterInspectorCorrelationOffset { get { return _messageInspectors.Length; } } internal int CorrelationCount { get { return _correlationCount; } } internal IClientOperationSelector OperationSelector { get { return _operationSelector; } } internal ProxyOperationRuntime UnhandledProxyOperation { get { return _unhandled; } } internal bool UseSynchronizationContext { get { return _useSynchronizationContext; } } internal bool ValidateMustUnderstand { get { return _validateMustUnderstand; } set { _validateMustUnderstand = value; } } internal void AfterReceiveReply(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { _messageInspectors[i].AfterReceiveReply(ref rpc.Reply, rpc.Correlation[offset + i]); if (TD.ClientMessageInspectorAfterReceiveInvokedIsEnabled()) { TD.ClientMessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void BeforeSendRequest(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { ServiceChannel clientChannel = ServiceChannelFactory.GetServiceChannel(rpc.Channel.Proxy); rpc.Correlation[offset + i] = _messageInspectors[i].BeforeSendRequest(ref rpc.Request, clientChannel); if (TD.ClientMessageInspectorBeforeSendInvokedIsEnabled()) { TD.ClientMessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void DisplayInitializationUI(ServiceChannel channel) { EndDisplayInitializationUI(BeginDisplayInitializationUI(channel, null, null)); } internal IAsyncResult BeginDisplayInitializationUI(ServiceChannel channel, AsyncCallback callback, object state) { return new DisplayInitializationUIAsyncResult(channel, _interactiveChannelInitializers, callback, state); } internal void EndDisplayInitializationUI(IAsyncResult result) { DisplayInitializationUIAsyncResult.End(result); } internal void InitializeChannel(IClientChannel channel) { try { for (int i = 0; i < _channelInitializers.Length; ++i) { _channelInitializers[i].Initialize(channel); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperation(MethodBase methodBase, object[] args, out bool canCacheResult) { if (_operationSelector == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException (SR.Format(SR.SFxNeedProxyBehaviorOperationSelector2, methodBase.Name, methodBase.DeclaringType.Name))); } try { if (_operationSelector.AreParametersRequiredForSelection) { canCacheResult = false; } else { args = null; canCacheResult = true; } string operationName = _operationSelector.SelectOperation(methodBase, args); ProxyOperationRuntime operation; if ((operationName != null) && _operations.TryGetValue(operationName, out operation)) { return operation; } else { // did not find the right operation, will not know how // to invoke the method. return null; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperationByName(string operationName) { ProxyOperationRuntime operation = null; if (_operations.TryGetValue(operationName, out operation)) return operation; else return null; } internal class DisplayInitializationUIAsyncResult : System.Runtime.AsyncResult { private ServiceChannel _channel; private int _index = -1; private IInteractiveChannelInitializer[] _initializers; private IClientChannel _proxy; private static AsyncCallback s_callback = Fx.ThunkCallback(new AsyncCallback(DisplayInitializationUIAsyncResult.Callback)); internal DisplayInitializationUIAsyncResult(ServiceChannel channel, IInteractiveChannelInitializer[] initializers, AsyncCallback callback, object state) : base(callback, state) { _channel = channel; _initializers = initializers; _proxy = ServiceChannelFactory.GetServiceChannel(channel.Proxy); this.CallBegin(true); } private void CallBegin(bool completedSynchronously) { while (++_index < _initializers.Length) { IAsyncResult result = null; Exception exception = null; try { result = _initializers[_index].BeginDisplayInitializationUI( _proxy, DisplayInitializationUIAsyncResult.s_callback, this ); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception == null) { if (!result.CompletedSynchronously) { return; } this.CallEnd(result, out exception); } if (exception != null) { this.CallComplete(completedSynchronously, exception); return; } } this.CallComplete(completedSynchronously, null); } private static void Callback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } DisplayInitializationUIAsyncResult outer = (DisplayInitializationUIAsyncResult)result.AsyncState; Exception exception = null; outer.CallEnd(result, out exception); if (exception != null) { outer.CallComplete(false, exception); return; } outer.CallBegin(false); } private void CallEnd(IAsyncResult result, out Exception exception) { try { _initializers[_index].EndDisplayInitializationUI(result); exception = null; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } } private void CallComplete(bool completedSynchronously, Exception exception) { this.Complete(completedSynchronously, exception); } internal static void End(IAsyncResult result) { System.Runtime.AsyncResult.End<DisplayInitializationUIAsyncResult>(result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; using System.Collections; using System.Globalization; namespace System.Xml.Xsl.XsltOld { internal abstract class SequentialOutput : IRecordOutput { private const char s_Colon = ':'; private const char s_GreaterThan = '>'; private const char s_LessThan = '<'; private const char s_Space = ' '; private const char s_Quote = '\"'; private const char s_Semicolon = ';'; private const char s_NewLine = '\n'; private const char s_Return = '\r'; private const char s_Ampersand = '&'; private const string s_LessThanQuestion = "<?"; private const string s_QuestionGreaterThan = "?>"; private const string s_LessThanSlash = "</"; private const string s_SlashGreaterThan = " />"; private const string s_EqualQuote = "=\""; private const string s_DocType = "<!DOCTYPE "; private const string s_CommentBegin = "<!--"; private const string s_CommentEnd = "-->"; private const string s_CDataBegin = "<![CDATA["; private const string s_CDataEnd = "]]>"; private const string s_VersionAll = " version=\"1.0\""; private const string s_Standalone = " standalone=\""; private const string s_EncodingStart = " encoding=\""; private const string s_Public = "PUBLIC "; private const string s_System = "SYSTEM "; private const string s_QuoteSpace = "\" "; private const string s_CDataSplit = "]]]]><![CDATA[>"; private const string s_EnLessThan = "&lt;"; private const string s_EnGreaterThan = "&gt;"; private const string s_EnAmpersand = "&amp;"; private const string s_EnQuote = "&quot;"; private const string s_EnNewLine = "&#xA;"; private const string s_EnReturn = "&#xD;"; private const string s_EndOfLine = "\r\n"; private static readonly char[] s_TextValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan }; private static readonly string[] s_TextValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan }; private static readonly char[] s_XmlAttributeValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan, s_Quote, s_NewLine, s_Return }; private static readonly string[] s_XmlAttributeValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan, s_EnQuote, s_EnNewLine, s_EnReturn }; // Instance members private readonly Processor _processor; protected Encoding encoding; private ArrayList _outputCache; private bool _firstLine = true; private bool _secondRoot; // Cached Output propertes: private XsltOutput _output; private bool _isHtmlOutput; private bool _isXmlOutput; private Hashtable _cdataElements; private bool _indentOutput; private bool _outputDoctype; private bool _outputXmlDecl; private bool _omitXmlDeclCalled; // Uri Escaping: private byte[] _byteBuffer; private Encoding _utf8Encoding; private XmlCharType _xmlCharType = XmlCharType.Instance; private void CacheOuptutProps(XsltOutput output) { _output = output; _isXmlOutput = _output.Method == XsltOutput.OutputMethod.Xml; _isHtmlOutput = _output.Method == XsltOutput.OutputMethod.Html; _cdataElements = _output.CDataElements; _indentOutput = _output.Indent; _outputDoctype = _output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null); _outputXmlDecl = _isXmlOutput && !_output.OmitXmlDeclaration && !_omitXmlDeclCalled; } // // Constructor // internal SequentialOutput(Processor processor) { _processor = processor; CacheOuptutProps(processor.Output); } public void OmitXmlDecl() { _omitXmlDeclCalled = true; _outputXmlDecl = false; } // // Particular outputs // private void WriteStartElement(RecordBuilder record) { Debug.Assert(record.MainNode.NodeType == XmlNodeType.Element); BuilderInfo mainNode = record.MainNode; HtmlElementProps htmlProps = null; if (_isHtmlOutput) { if (mainNode.Prefix.Length == 0) { htmlProps = mainNode.htmlProps; if (htmlProps == null && mainNode.search) { htmlProps = HtmlElementProps.GetProps(mainNode.LocalName); } record.Manager.CurrentElementScope.HtmlElementProps = htmlProps; mainNode.IsEmptyTag = false; } } else if (_isXmlOutput) { if (mainNode.Depth == 0) { if ( _secondRoot && ( _output.DoctypeSystem != null || _output.Standalone ) ) { throw XsltException.Create(SR.Xslt_MultipleRoots); } _secondRoot = true; } } if (_outputDoctype) { WriteDoctype(mainNode); _outputDoctype = false; } if (_cdataElements != null && _cdataElements.Contains(new XmlQualifiedName(mainNode.LocalName, mainNode.NamespaceURI)) && _isXmlOutput) { record.Manager.CurrentElementScope.ToCData = true; } Indent(record); Write(s_LessThan); WriteName(mainNode.Prefix, mainNode.LocalName); WriteAttributes(record.AttributeList, record.AttributeCount, htmlProps); if (mainNode.IsEmptyTag) { Debug.Assert(!_isHtmlOutput || mainNode.Prefix != null, "Html can't have abbreviated elements"); Write(s_SlashGreaterThan); } else { Write(s_GreaterThan); } if (htmlProps != null && htmlProps.Head) { mainNode.Depth++; Indent(record); mainNode.Depth--; Write("<META http-equiv=\"Content-Type\" content=\""); Write(_output.MediaType); Write("; charset="); Write(this.encoding.WebName); Write("\">"); } } private void WriteTextNode(RecordBuilder record) { BuilderInfo mainNode = record.MainNode; OutputScope scope = record.Manager.CurrentElementScope; scope.Mixed = true; if (scope.HtmlElementProps != null && scope.HtmlElementProps.NoEntities) { // script or stile Write(mainNode.Value); } else if (scope.ToCData) { WriteCDataSection(mainNode.Value); } else { WriteTextNode(mainNode); } } private void WriteTextNode(BuilderInfo node) { for (int i = 0; i < node.TextInfoCount; i++) { string text = node.TextInfo[i]; if (text == null) { // disableEscaping marker i++; Debug.Assert(i < node.TextInfoCount, "disableEscaping marker can't be last TextInfo record"); Write(node.TextInfo[i]); } else { WriteWithReplace(text, s_TextValueFind, s_TextValueReplace); } } } private void WriteCDataSection(string value) { Write(s_CDataBegin); WriteCData(value); Write(s_CDataEnd); } private void WriteDoctype(BuilderInfo mainNode) { Debug.Assert(_outputDoctype == true, "It supposed to check this condition before actual call"); Debug.Assert(_output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null), "We set outputDoctype == true only if"); Indent(0); Write(s_DocType); if (_isXmlOutput) { WriteName(mainNode.Prefix, mainNode.LocalName); } else { WriteName(string.Empty, "html"); } Write(s_Space); if (_output.DoctypePublic != null) { Write(s_Public); Write(s_Quote); Write(_output.DoctypePublic); Write(s_QuoteSpace); } else { Write(s_System); } if (_output.DoctypeSystem != null) { Write(s_Quote); Write(_output.DoctypeSystem); Write(s_Quote); } Write(s_GreaterThan); } private void WriteXmlDeclaration() { Debug.Assert(_outputXmlDecl == true, "It supposed to check this condition before actual call"); Debug.Assert(_isXmlOutput && !_output.OmitXmlDeclaration, "We set outputXmlDecl == true only if"); _outputXmlDecl = false; Indent(0); Write(s_LessThanQuestion); WriteName(string.Empty, "xml"); Write(s_VersionAll); if (this.encoding != null) { Write(s_EncodingStart); Write(this.encoding.WebName); Write(s_Quote); } if (_output.HasStandalone) { Write(s_Standalone); Write(_output.Standalone ? "yes" : "no"); Write(s_Quote); } Write(s_QuestionGreaterThan); } private void WriteProcessingInstruction(RecordBuilder record) { Indent(record); WriteProcessingInstruction(record.MainNode); } private void WriteProcessingInstruction(BuilderInfo node) { Write(s_LessThanQuestion); WriteName(node.Prefix, node.LocalName); Write(s_Space); Write(node.Value); if (_isHtmlOutput) { Write(s_GreaterThan); } else { Write(s_QuestionGreaterThan); } } private void WriteEndElement(RecordBuilder record) { HtmlElementProps htmlProps = record.Manager.CurrentElementScope.HtmlElementProps; if (htmlProps != null && htmlProps.Empty) { return; } Indent(record); Write(s_LessThanSlash); WriteName(record.MainNode.Prefix, record.MainNode.LocalName); Write(s_GreaterThan); } // // RecordOutput interface method implementation // public Processor.OutputResult RecordDone(RecordBuilder record) { if (_output.Method == XsltOutput.OutputMethod.Unknown) { if (!DecideDefaultOutput(record.MainNode)) { CacheRecord(record); } else { OutputCachedRecords(); OutputRecord(record); } } else { OutputRecord(record); } record.Reset(); return Processor.OutputResult.Continue; } public void TheEnd() { OutputCachedRecords(); Close(); } private bool DecideDefaultOutput(BuilderInfo node) { XsltOutput.OutputMethod method = XsltOutput.OutputMethod.Xml; switch (node.NodeType) { case XmlNodeType.Element: if (node.NamespaceURI.Length == 0 && string.Equals("html", node.LocalName, StringComparison.OrdinalIgnoreCase)) { method = XsltOutput.OutputMethod.Html; } break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (_xmlCharType.IsOnlyWhitespace(node.Value)) { return false; } method = XsltOutput.OutputMethod.Xml; break; default: return false; } if (_processor.SetDefaultOutput(method)) { CacheOuptutProps(_processor.Output); } return true; } private void CacheRecord(RecordBuilder record) { if (_outputCache == null) { _outputCache = new ArrayList(); } _outputCache.Add(record.MainNode.Clone()); } private void OutputCachedRecords() { if (_outputCache == null) { return; } for (int record = 0; record < _outputCache.Count; record++) { Debug.Assert(_outputCache[record] is BuilderInfo); BuilderInfo info = (BuilderInfo)_outputCache[record]; OutputRecord(info); } _outputCache = null; } private void OutputRecord(RecordBuilder record) { BuilderInfo mainNode = record.MainNode; if (_outputXmlDecl) { WriteXmlDeclaration(); } switch (mainNode.NodeType) { case XmlNodeType.Element: WriteStartElement(record); break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteTextNode(record); break; case XmlNodeType.CDATA: Debug.Fail("Should never get here"); break; case XmlNodeType.EntityReference: Write(s_Ampersand); WriteName(mainNode.Prefix, mainNode.LocalName); Write(s_Semicolon); break; case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(record); break; case XmlNodeType.Comment: Indent(record); Write(s_CommentBegin); Write(mainNode.Value); Write(s_CommentEnd); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Write(mainNode.Value); break; case XmlNodeType.EndElement: WriteEndElement(record); break; default: break; } } private void OutputRecord(BuilderInfo node) { if (_outputXmlDecl) { WriteXmlDeclaration(); } Indent(0); // we can have only top level stuff here switch (node.NodeType) { case XmlNodeType.Element: Debug.Fail("Should never get here"); break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteTextNode(node); break; case XmlNodeType.CDATA: Debug.Fail("Should never get here"); break; case XmlNodeType.EntityReference: Write(s_Ampersand); WriteName(node.Prefix, node.LocalName); Write(s_Semicolon); break; case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(node); break; case XmlNodeType.Comment: Write(s_CommentBegin); Write(node.Value); Write(s_CommentEnd); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Write(node.Value); break; case XmlNodeType.EndElement: Debug.Fail("Should never get here"); break; default: break; } } // // Internal helpers // private void WriteName(string prefix, string name) { if (prefix != null && prefix.Length > 0) { Write(prefix); if (name != null && name.Length > 0) { Write(s_Colon); } else { return; } } Write(name); } private void WriteXmlAttributeValue(string value) { Debug.Assert(value != null); WriteWithReplace(value, s_XmlAttributeValueFind, s_XmlAttributeValueReplace); } private void WriteHtmlAttributeValue(string value) { Debug.Assert(value != null); int length = value.Length; int i = 0; while (i < length) { char ch = value[i]; i++; switch (ch) { case '&': if (i != length && value[i] == '{') { // &{ hasn't to be encoded in HTML output. Write(ch); } else { Write(s_EnAmpersand); } break; case '"': Write(s_EnQuote); break; default: Write(ch); break; } } } private void WriteHtmlUri(string value) { Debug.Assert(value != null); Debug.Assert(_isHtmlOutput); int length = value.Length; int i = 0; while (i < length) { char ch = value[i]; i++; switch (ch) { case '&': if (i != length && value[i] == '{') { // &{ hasn't to be encoded in HTML output. Write(ch); } else { Write(s_EnAmpersand); } break; case '"': Write(s_EnQuote); break; case '\n': Write(s_EnNewLine); break; case '\r': Write(s_EnReturn); break; default: if (127 < ch) { if (_utf8Encoding == null) { _utf8Encoding = Encoding.UTF8; _byteBuffer = new byte[_utf8Encoding.GetMaxByteCount(1)]; } int bytes = _utf8Encoding.GetBytes(value, i - 1, 1, _byteBuffer, 0); for (int j = 0; j < bytes; j++) { Write("%"); Write(((uint)_byteBuffer[j]).ToString("X2", CultureInfo.InvariantCulture)); } } else { Write(ch); } break; } } } private void WriteWithReplace(string value, char[] find, string[] replace) { Debug.Assert(value != null); Debug.Assert(find.Length == replace.Length); int length = value.Length; int pos = 0; while (pos < length) { int newPos = value.IndexOfAny(find, pos); if (newPos == -1) { break; // not found; } // output clean leading part of the string while (pos < newPos) { Write(value[pos]); pos++; } // output replacement char badChar = value[pos]; int i; for (i = find.Length - 1; 0 <= i; i--) { if (find[i] == badChar) { Write(replace[i]); break; } } Debug.Assert(0 <= i, "find char wasn't realy find"); pos++; } // output rest of the string if (pos == 0) { Write(value); } else { while (pos < length) { Write(value[pos]); pos++; } } } private void WriteCData(string value) { Debug.Assert(value != null); Write(value.Replace(s_CDataEnd, s_CDataSplit)); } private void WriteAttributes(ArrayList list, int count, HtmlElementProps htmlElementsProps) { Debug.Assert(count <= list.Count); for (int attrib = 0; attrib < count; attrib++) { Debug.Assert(list[attrib] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)list[attrib]; string attrValue = attribute.Value; bool abr = false, uri = false; { if (htmlElementsProps != null && attribute.Prefix.Length == 0) { HtmlAttributeProps htmlAttrProps = attribute.htmlAttrProps; if (htmlAttrProps == null && attribute.search) { htmlAttrProps = HtmlAttributeProps.GetProps(attribute.LocalName); } if (htmlAttrProps != null) { abr = htmlElementsProps.AbrParent && htmlAttrProps.Abr; uri = htmlElementsProps.UriParent && (htmlAttrProps.Uri || htmlElementsProps.NameParent && htmlAttrProps.Name ); } } } Write(s_Space); WriteName(attribute.Prefix, attribute.LocalName); if (abr && string.Equals(attribute.LocalName, attrValue, StringComparison.OrdinalIgnoreCase)) { // Since the name of the attribute = the value of the attribute, // this is a boolean attribute whose value should be suppressed continue; } Write(s_EqualQuote); if (uri) { WriteHtmlUri(attrValue); } else if (_isHtmlOutput) { WriteHtmlAttributeValue(attrValue); } else { WriteXmlAttributeValue(attrValue); } Write(s_Quote); } } private void Indent(RecordBuilder record) { if (!record.Manager.CurrentElementScope.Mixed) { Indent(record.MainNode.Depth); } } private void Indent(int depth) { if (_firstLine) { if (_indentOutput) { _firstLine = false; } return; // preven leading CRLF } Write(s_EndOfLine); for (int i = 2 * depth; 0 < i; i--) { Write(" "); } } // // Abstract methods internal abstract void Write(char outputChar); internal abstract void Write(string outputText); internal abstract void Close(); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; [Serializable] [System.Runtime.InteropServices.ComVisible(false)] [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Collection<T>: IList<T>, IList, IReadOnlyList<T> { IList<T> items; [NonSerialized] private Object _syncRoot; #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public Collection() { items = new List<T>(); } public Collection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } items = list; } public int Count { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return items.Count; } } protected IList<T> Items { get { return items; } } public T this[int index] { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return items[index]; } set { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } SetItem(index, value); } } public void Add(T item) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.Count; InsertItem(index, item); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public void Clear() { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ClearItems(); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public void CopyTo(T[] array, int index) { items.CopyTo(array, index); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public bool Contains(T item) { return items.Contains(item); } public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public int IndexOf(T item) { return items.IndexOf(item); } public void Insert(int index, T item) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index > items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } InsertItem(index, item); } public bool Remove(T item) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.IndexOf(item); if (index < 0) return false; RemoveItem(index); return true; } public void RemoveAt(int index) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } RemoveItem(index); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif protected virtual void ClearItems() { items.Clear(); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif protected virtual void InsertItem(int index, T item) { items.Insert(index, item); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif protected virtual void RemoveItem(int index) { items.RemoveAt(index); } protected virtual void SetItem(int index, T item) { items[index] = item; } bool ICollection<T>.IsReadOnly { get { return items.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if( _syncRoot == null) { ICollection c = items as ICollection; if( c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 ) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } T[] tArray = array as T[]; if (tArray != null) { items.CopyTo(tArray , index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if( objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = items.Count; try { for (int i = 0; i < count; i++) { objects[index++] = items[i]; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } object IList.this[int index] { get { return items[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } bool IList.IsReadOnly { get { return items.IsReadOnly; } } bool IList.IsFixedSize { get { // There is no IList<T>.IsFixedSize, so we must assume that only // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. IList list = items as IList; if(list != null) { return list.IsFixedSize; } return items.IsReadOnly; } } int IList.Add(object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Add((T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } return this.Count - 1; } bool IList.Contains(object value) { if(IsCompatibleObject(value)) { return Contains((T) value); } return false; } int IList.IndexOf(object value) { if(IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Insert(index, (T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } void IList.Remove(object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if(IsCompatibleObject(value)) { Remove((T) value); } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } } }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using System; using Alachisoft.NCache.Runtime.Events; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Logger; using System.Collections.Generic; using Alachisoft.NCache.Runtime.Caching; using Alachisoft.NCache.Caching.Util; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Caching.Events; using static Alachisoft.NCache.Client.EventUtil; using System.Threading.Tasks; using Alachisoft.NCache.Common.Enum; namespace Alachisoft.NCache.Client { /// <summary> /// Has the responsibility of creating <see cref=" CacheEventDescriptor"/> and registering it agains a ResourcePool /// </summary> internal class EventManager { public const short REFSTART = -1; public const short SELECTIVEREFSTARTRemove = 8000; public const short SELECTIVEREFSTARTUpdate = 9000; public const short SELECTIVEREFSTARTPolling = 10000; public const short COLLECTIONREFSTARTAdd = 11000; public const short COLLECTIONREFSTARTUpdate = 12000; public const short COLLECTIONREFSTARTRemove = 13000; System.Threading.WaitCallback waitC = new System.Threading.WaitCallback(Fire); string _cacheName = null; private NCacheLogger _logger; private object sync_lock_collection = new object(); private object sync_lock_selective = new object(); private object sync_lock_general = new object(); private PollNotificationCallback _pollPubSubCallback; private static AsyncCallback asyn = new System.AsyncCallback(EndAsyncCallback); private Cache _cache; private int addCallbacks = -1; private int removeCallbacks = -1; private int updateCallbacks = -1; #region Resource Pools private ResourcePool _addEventPool = null; private EventDataFilter _addDataFilter = EventDataFilter.None; private ResourcePool _removeEventPool = null; private EventDataFilter _removeDataFilter = EventDataFilter.None; private ResourcePool _updateEventPool = null; private EventDataFilter _updateDataFilter = EventDataFilter.None; private short _addEventRegistrationSequence = REFSTART; //Significant difference from old callback numbers private short _updateEventRegisrationSequenceId = REFSTART; //Significant difference from old callback numbers private short _removeEventRegistrationSequenceId = REFSTART; //Significant difference from old callback numbers private ResourcePool _selectiveRemoveEventPool = null; private ResourcePool _selectiveRemoveEventIDPool = null; private ResourcePool _oldSelectiveCallbackPool = new ResourcePool(); private ResourcePool _oldSelectiveMappingCallbackPool = new ResourcePool(); private short _selectveRemoveCallbackRef = SELECTIVEREFSTARTRemove; private ResourcePool _selectiveUpdateEventPool = null; private ResourcePool _selectiveUpdateEventIDPool = null; private short _selectiveUpdateCallbackRef = SELECTIVEREFSTARTUpdate; private EventDataFilter _generalAddDataFilter = EventDataFilter.None; private EventDataFilter _generalUpdateDataFilter = EventDataFilter.None; private EventDataFilter _generalRemoveDataFilter = EventDataFilter.None; private short _pollingNotificationCallbackRef = SELECTIVEREFSTARTPolling; private TopicSubscription _selectiveEventsSubscription; private TopicSubscription _collectionEventsSubscription; #region -- Collection Events Specific Fields -- private ResourcePool _collectionAddEventPool = null; private ResourcePool _collectionAddEventIdPool = null; private short _collectionAddCallbackRef = COLLECTIONREFSTARTAdd; private ResourcePool _collectionUpdateEventPool = null; private ResourcePool _collectionUpdateEventIdPool = null; private short _collectionUpdateCallbackRef = COLLECTIONREFSTARTUpdate; private ResourcePool _collectionRemoveEventPool = null; private ResourcePool _collectionRemoveEventIdPool = null; private short _collectionRemoveCallbackRef = COLLECTIONREFSTARTRemove; #endregion #endregion internal EventManager(string cacheName, NCacheLogger logger, Cache cache) { _cacheName = cacheName; _logger = logger; _cache = cache; } internal short AddSequenceNumber { get { return _addEventRegistrationSequence; } } internal short UpdateSequenceNumber { get { return _updateEventRegisrationSequenceId; } } internal short RemoveSequenceNumber { get { return _removeEventRegistrationSequenceId; } } internal object SyncLockGeneral { get { return sync_lock_general; } } internal object SyncLockSelective { get { return sync_lock_selective; } } internal object SyncLockCollection { get { return sync_lock_collection; } } /// <summary> /// Provide /// </summary> /// <param name="eventType"></param> /// <returns></returns> internal short GeneralEventRefCountAgainstEvent(EventTypeInternal eventType) { if ((eventType & EventTypeInternal.ItemAdded) != 0) return _addEventRegistrationSequence; if ((eventType & EventTypeInternal.ItemRemoved) != 0) return _removeEventRegistrationSequenceId; if ((eventType & EventTypeInternal.ItemUpdated) != 0) return _updateEventRegisrationSequenceId; return -1; } /// <summary> /// Returns the filter type of the eventType /// </summary> /// <param name="eventType"></param> /// <returns></returns> internal EventDataFilter MaxFilterAgainstEvent(EventTypeInternal eventType) { if ((eventType & EventTypeInternal.ItemAdded) != 0) return _addDataFilter; if ((eventType & EventTypeInternal.ItemRemoved) != 0) return _removeDataFilter; if ((eventType & EventTypeInternal.ItemUpdated) != 0) return _updateDataFilter; return EventDataFilter.None; } /// <summary> /// Registeres the callback sepeartely and returns short values of registeredCallbacks /// </summary> /// <param name="key"></param> /// <param name="callback"></param> /// <param name="eventType"></param> /// <param name="datafilter"></param> /// <returns>short array,<para>1st element is updated callbackRef</para><para>2st element is removed callbackRef</para></returns> internal short[] RegisterSelectiveEvent(CacheDataNotificationCallback callback, EventTypeInternal eventType, EventDataFilter datafilter, CallbackType callbackType = CallbackType.PushBasedNotification) { if (callback != null) { //Avoiding new ResourcePool(inside = new Hashtable) at constructor level if (_selectiveUpdateEventPool == null) { _selectiveUpdateEventPool = new ResourcePool(); _selectiveUpdateEventIDPool = new ResourcePool(); } if (_selectiveRemoveEventPool == null) { _selectiveRemoveEventPool = new ResourcePool(); _selectiveRemoveEventIDPool = new ResourcePool(); } return RegisterSelectiveDiscriptor(callback, eventType,callbackType); } else return null; } internal short RegisterPollingEvent(PollNotificationCallback callback, EventTypeInternal eventType) { // Only one poll callback can be configured. // No need to use pools. if ((eventType & EventTypeInternal.PubSub) != 0) { _pollPubSubCallback = callback; } return 10001; } internal CacheEventDescriptor RegisterGeneralEvents(CacheDataNotificationCallback callback, EventType eventType, EventDataFilter datafilter) { if (callback != null) { //Avoiding new ResourcePool(inside = new Hashtable) at constructor level if (_addEventPool == null) { _addEventPool = new ResourcePool(); } if (_removeEventPool == null) { _removeEventPool = new ResourcePool(); } if (_updateEventPool == null) { _updateEventPool = new ResourcePool(); } CacheEventDescriptor discriptor = CacheEventDescriptor.CreateCacheDiscriptor(eventType, _cacheName, callback, datafilter); //Registers the handl) bool registeredDescriptor = RegisterGeneralDiscriptor(discriptor, EventsUtil.GetEventTypeInternal(eventType)); if (!registeredDescriptor) return null; return discriptor; } else return null; } internal void UnregisterAll() { } /// <summary> /// TheadSafe and no locks internally /// </summary> /// <param name="key"></param> /// <param name="eventType">Should contain one type i.e. should not be used as a flag. /// Every EventType should be executed from another thread</param> /// <param name="item"></param> /// <param name="oldItem"></param> /// <param name="reason"></param> /// <param name="notifyAsync"></param> internal void RaiseGeneralCacheNotification(string key, EventType eventType, EventCacheItem item, EventCacheItem oldItem, CacheItemRemovedReason reason, bool notifyAsync) { try { object[] registeredDiscriptors = null; ResourcePool eventPool = GetEventPool(EventsUtil.GetEventTypeInternal(eventType)); if (eventPool != null) registeredDiscriptors = eventPool.GetAllResourceKeys(); if (registeredDiscriptors != null && registeredDiscriptors.Length > 0) { for (int i = 0; i < registeredDiscriptors.Length; i++) { CacheEventDescriptor discriptor = registeredDiscriptors[i] as CacheEventDescriptor; if (discriptor == null) continue; var bitSet = new BitSet(); if (_cache.SerializationFormat == Common.Enum.SerializationFormat.Json) bitSet.SetBit(BitSetConstants.JsonData); if (item != null) item.SetValue(_cache.SafeDeserialize<object>(item.GetValue<object>(), _cache.SerializationContext, bitSet, UserObjectType.CacheItem)); if (oldItem != null) oldItem.SetValue(_cache.SafeDeserialize<object>(oldItem.GetValue<object>(), _cache.SerializationContext, bitSet, UserObjectType.CacheItem)); var arg = CreateCacheEventArgument(discriptor.DataFilter, key, _cacheName, eventType, item, oldItem, reason); arg.Descriptor = discriptor; if (notifyAsync) { #if !NETCORE discriptor.CacheDataNotificationCallback.BeginInvoke(key, arg, asyn, null); #elif NETCORE //TODO: ALACHISOFT (BeginInvoke is not supported in .Net Core thus using TaskFactory) TaskFactory factory = new TaskFactory(); Task task = factory.StartNew(() => discriptor.CacheDataNotificationCallback(key, arg)); #endif } else discriptor.CacheDataNotificationCallback.Invoke(key, arg); } } } catch (Exception ex) { if (_logger != null && _logger.IsErrorEnabled) _logger.CriticalInfo(ex.ToString()); } } internal void RaisePollNotification(short callbackId, EventTypeInternal eventType) { try { // just invoke the callback if not null. // callbackId is of no use here. PollNotificationCallback _pollCallback = null; if ((eventType & EventTypeInternal.PubSub) != 0) { _pollCallback = _pollPubSubCallback; } if (_pollCallback != null) _pollCallback.Invoke(); } catch (Exception ex) { if (_logger != null && _logger.IsErrorEnabled) _logger.CriticalInfo(ex.ToString()); } } private CacheEventArg CreateCacheEventArgument(EventDataFilter dataFilter, string key, string cacheName, EventType eventType, EventCacheItem item, EventCacheItem oldItem, CacheItemRemovedReason removedReason) { EventCacheItem cloneItem = null; EventCacheItem cloneOldItem = null; CacheEventArg eventArg = new CacheEventArg(key, cacheName, eventType, cloneItem, null, removedReason); if (eventType == EventType.ItemUpdated) eventArg.OldItem = cloneOldItem; return eventArg; } /// <summary> /// TheadSafe and no locks internally /// </summary> /// <param name="key"></param> /// <param name="eventType">Should contain one type i.e. should not be used as a flag. /// Every EventType should be executed from another thread</param> /// <param name="item"></param> /// <param name="oldItem"></param> /// <param name="reason"></param> /// <param name="_notifyAsync"></param> /// <param name="eventhandle"></param> internal void RaiseSelectiveCacheNotification(string key, EventType eventType, EventCacheItem item, EventCacheItem oldItem, CacheItemRemovedReason reason, bool _notifyAsync, EventHandle eventhandle, EventDataFilter dataFilter) { try { ResourcePool poolID = null; CacheEventArg arg = null; var bitSet = new BitSet(); if (_cache.SerializationFormat == Common.Enum.SerializationFormat.Json) bitSet.SetBit(BitSetConstants.JsonData); if (item != null) item.SetValue(_cache.SafeDeserialize<object>(item.GetValue<object>(), _cache.SerializationContext, bitSet, UserObjectType.CacheItem)); if (oldItem != null) oldItem.SetValue(_cache.SafeDeserialize<object>(oldItem.GetValue<object>(), _cache.SerializationContext, bitSet, UserObjectType.CacheItem)); if ((eventType & EventType.ItemUpdated) != 0) { poolID = _selectiveUpdateEventIDPool; } else if ((eventType & EventType.ItemRemoved) != 0) { poolID = _selectiveRemoveEventIDPool; } arg = CreateCacheEventArgument(dataFilter, key, _cacheName, eventType, item, oldItem, reason); if (poolID == null) return; CacheDataNotificationCallback callback = poolID.GetResource((short)eventhandle.Handle) as CacheDataNotificationCallback; if (callback == null) //Can occur if Unregistered concurrently return; if (_notifyAsync) System.Threading.ThreadPool.QueueUserWorkItem(waitC, new object[] { callback, key, arg }); //Faster and better else callback.Invoke(key, arg); } catch (Exception ex) { if (_logger != null && _logger.IsErrorEnabled) _logger.CriticalInfo(ex.ToString()); } } /// <summary> /// TheadSafe and no locks internally. /// </summary> private static void Fire(object obj) { try { object[] objArray = (object[])obj; ((CacheDataNotificationCallback)objArray[0]).Invoke((string)objArray[1], (CacheEventArg)objArray[2]); } catch (Exception) { } } internal short RegisterSelectiveCallback(CacheItemRemovedCallback removedCallback, CallbackType callbackType) { if (removedCallback == null) return -1; lock (SyncLockSelective) { SelectiveRemoveCallbackWrapper callbackWrapper = null; // callback is not already registered with the same method, so add if (_oldSelectiveCallbackPool.GetResource(removedCallback) == null) { callbackWrapper = new SelectiveRemoveCallbackWrapper(removedCallback); _oldSelectiveCallbackPool.AddResource(removedCallback, callbackWrapper); _oldSelectiveMappingCallbackPool.AddResource(callbackWrapper, removedCallback); } // already present against the same method, so no need to add again. else { callbackWrapper = (SelectiveRemoveCallbackWrapper)_oldSelectiveCallbackPool.GetResource(removedCallback); _oldSelectiveCallbackPool.AddResource(removedCallback, callbackWrapper);//just to increment the refCount } short[] callbackIds = RegisterSelectiveEvent(callbackWrapper.MappingCallback, EventTypeInternal.ItemRemoved, EventDataFilter.None, callbackType); return callbackIds[1]; } } internal short UnRegisterSelectiveCallback(CacheItemRemovedCallback removedCallback) { if (removedCallback == null) return -1; SelectiveRemoveCallbackWrapper callbackWrapper = null; // callback is not already registered with the same method, so add lock (SyncLockSelective) { //a callback more then one time or against wrong items. callbackWrapper = (SelectiveRemoveCallbackWrapper)_oldSelectiveCallbackPool.GetResource(removedCallback); if (callbackWrapper != null) { short[] callbackIds = UnregisterSelectiveNotification(callbackWrapper.MappingCallback, EventTypeInternal.ItemRemoved); return callbackIds[1]; } return -1; } } internal short RegisterSelectiveCallback(CacheItemUpdatedCallback updateCallback, CallbackType callbackType) { if (updateCallback == null) return -1; SelectiveUpdateCallbackWrapper callbackWrapper = null; lock (SyncLockSelective) { // callback is not already registered with the same method, so add if (_oldSelectiveCallbackPool.GetResource(updateCallback) == null) { callbackWrapper = new SelectiveUpdateCallbackWrapper(updateCallback); _oldSelectiveCallbackPool.AddResource(updateCallback, callbackWrapper); _oldSelectiveMappingCallbackPool.AddResource(callbackWrapper, updateCallback); } // already present against the same method, so no need to add again. else { callbackWrapper = (SelectiveUpdateCallbackWrapper)_oldSelectiveCallbackPool.GetResource(updateCallback); _oldSelectiveCallbackPool.AddResource(updateCallback, callbackWrapper);//to increment the refcount } short[] callbackIds = RegisterSelectiveEvent(callbackWrapper.MappingCallback, EventTypeInternal.ItemUpdated, EventDataFilter.None,callbackType); return callbackIds[0]; } } internal short UnRegisterSelectiveCallback(CacheItemUpdatedCallback updateCallback) { if (updateCallback == null) return -1; lock (SyncLockSelective) { SelectiveUpdateCallbackWrapper callbackWrapper = (SelectiveUpdateCallbackWrapper)_oldSelectiveCallbackPool.GetResource(updateCallback); //a callback more then one time or against wrong items. if (callbackWrapper != null) { short[] callbackIds = RegisterSelectiveEvent(callbackWrapper.MappingCallback, EventTypeInternal.ItemUpdated, EventDataFilter.None); return callbackIds[0]; } return -1; } } /// <summary> /// Returning Negative value means operation not successfull /// </summary> /// <param name="discriptor"></param> /// <param name="eventType"></param> /// <returns>short array <para>1st value is Update callbackRef</para> <para>nd value is removeRef</para></returns> private short[] RegisterSelectiveDiscriptor(CacheDataNotificationCallback callback, EventTypeInternal eventType, CallbackType callbackType) { if (callback == null) return null; //FAIL CONDITION short[] returnValue = new short[] { -1, -1 }; //First value update callback ref & sencond is remove callbackref foreach (EventTypeInternal type in Enum.GetValues(typeof(EventTypeInternal))) { if (type == EventTypeInternal.ItemAdded) //ItemAdded not supported Yet continue; lock (SyncLockSelective) { ResourcePool pool = null; ResourcePool poolID = null; #region pool selection if (type == EventTypeInternal.ItemRemoved && (eventType & EventTypeInternal.ItemRemoved) != 0) { pool = _selectiveRemoveEventPool; poolID = _selectiveRemoveEventIDPool; } else if (type == EventTypeInternal.ItemUpdated && (eventType & EventTypeInternal.ItemUpdated) != 0) { pool = _selectiveUpdateEventPool; poolID = _selectiveUpdateEventIDPool; } if (pool == null) continue; #endregion while (true) { int i = type == EventTypeInternal.ItemUpdated ? 0 : 1; if (pool.GetResource(callback) == null) { returnValue[i] = type == EventTypeInternal.ItemUpdated ? ++_selectiveUpdateCallbackRef : ++_selectveRemoveCallbackRef; pool.AddResource(callback, returnValue[i]); poolID.AddResource(returnValue[i], callback); break; } else { try { short cref = (short)pool.GetResource(callback); if (cref < 0) break; //FAIL CONDITION //add it again into the table for updating ref count. pool.AddResource(callback, cref); poolID.AddResource(cref, callback); returnValue[i] = cref; break; } catch (NullReferenceException) { //Legacy code: can create an infinite loop //Recomendation of returning a negative number instead of continue continue; } } } } } if (_selectiveEventsSubscription == null && callbackType != CallbackType.PullBasedCallback) { Topic topic = (Topic)_cache._messagingService.GetTopic(TopicConstant.ItemLevelEventsTopic, true); _selectiveEventsSubscription = (TopicSubscription)topic.CreateEventSubscription(OnSelectiveEventMessageReceived); } return returnValue; } private bool RegisterGeneralDiscriptor(CacheEventDescriptor discriptor, EventTypeInternal eventType) { if (discriptor == null) return false; //FAIL CONDITION EventHandle handle = null; foreach (EventTypeInternal type in Enum.GetValues(typeof(EventTypeInternal))) { ResourcePool pool = null; bool registrationUpdated = false; #region Pool selection if ((type & eventType) != 0) pool = GetEventPool(type); if (pool == null) continue; #endregion short registrationSequenceId = -1; lock (SyncLockGeneral) { pool.AddResource(discriptor, 1); // Everytime a new Discriptor is forcefully created //Keeps a sequence number switch (type) { case EventTypeInternal.ItemAdded: if (discriptor.DataFilter > _generalAddDataFilter || _addEventRegistrationSequence == REFSTART) { registrationUpdated = true; registrationSequenceId = ++_addEventRegistrationSequence; _generalAddDataFilter = discriptor.DataFilter; } else registrationSequenceId = _addEventRegistrationSequence; break; case EventTypeInternal.ItemRemoved: if (discriptor.DataFilter > _generalRemoveDataFilter || _removeEventRegistrationSequenceId == REFSTART) { registrationUpdated = true; registrationSequenceId = ++_removeEventRegistrationSequenceId; _generalRemoveDataFilter = discriptor.DataFilter; } else registrationSequenceId = _removeEventRegistrationSequenceId; break; case EventTypeInternal.ItemUpdated: if (discriptor.DataFilter > _generalUpdateDataFilter || _updateEventRegisrationSequenceId == REFSTART) { registrationUpdated = true; registrationSequenceId = ++_updateEventRegisrationSequenceId; _generalUpdateDataFilter = discriptor.DataFilter; } else registrationSequenceId = _updateEventRegisrationSequenceId; break; } //Although the handle doesnt matter in general events if (handle == null) handle = new EventHandle(registrationSequenceId); } if (_cache != null && registrationSequenceId != -1) _cache.RegisterCacheNotificationDataFilter(type, discriptor.DataFilter, registrationSequenceId); } discriptor.IsRegistered = true; discriptor.Handle = handle; return true; } /// <summary> /// Unregisters CacheDataNotificationCallback /// <para>Flag based unregistration</para> /// </summary> /// <param name="callback"></param> /// <param name="key"></param> /// <param name="eventType"></param> internal short[] UnregisterSelectiveNotification(CacheDataNotificationCallback callback, EventTypeInternal eventType) { if (callback == null) return null; short[] returnValue = new short[] { -1, -1 }; //First value update callback ref & sencond is remove callbackref foreach (EventTypeInternal type in Enum.GetValues(typeof(EventTypeInternal))) { if (type == EventTypeInternal.ItemAdded) //ItemAdded not supported Yet continue; object id = -1; lock (SyncLockSelective) { ResourcePool pool = null; ResourcePool poolID = null; #region pool selection if (type == EventTypeInternal.ItemRemoved && (eventType & EventTypeInternal.ItemRemoved) != 0) { pool = _selectiveRemoveEventPool; poolID = _selectiveRemoveEventIDPool; if (pool == null) removeCallbacks = 0; } else if (type == EventTypeInternal.ItemUpdated && (eventType & EventTypeInternal.ItemUpdated) != 0) { pool = _selectiveUpdateEventPool; poolID = _selectiveUpdateEventIDPool; if (pool == null) updateCallbacks = 0; } if(removeCallbacks == 0 && updateCallbacks == 0) { _selectiveEventsSubscription.UnSubscribeEventTopic(); _selectiveEventsSubscription = null; } if (pool == null) continue; #endregion int i = type == EventTypeInternal.ItemUpdated ? 0 : 1; id = pool.GetResource(callback); if (id is short) { returnValue[i] = (short)id; } } } return returnValue; } internal EventHandle UnregisterDiscriptor(CacheEventDescriptor discriptor) { if (discriptor == null || !discriptor.IsRegistered) return null; foreach (EventType type in Enum.GetValues(typeof(EventType))) { ResourcePool pool = null; #region Pool selection if ((type & discriptor.RegisteredAgainst) != 0) pool = GetEventPool(EventsUtil.GetEventTypeInternal(type)); if (pool == null) continue; #endregion short registrationSequenceId = -1; bool unregisterNotification = false; EventDataFilter maxDataFilter = EventDataFilter.None; lock (SyncLockGeneral) { object retVal = pool.RemoveResource(discriptor); if (retVal == null) continue; unregisterNotification = pool.Count == 0; if (!unregisterNotification) { object[] pooledDescriptors = pool.GetAllResourceKeys(); if (pooledDescriptors != null) { for (int i = 0; i < pooledDescriptors.Length; i++) { CacheEventDescriptor pooledDescriptor = pooledDescriptors[i] as CacheEventDescriptor; if (pooledDescriptor.DataFilter > maxDataFilter) maxDataFilter = pooledDescriptor.DataFilter; } } } discriptor.IsRegistered = false; //keeps a sequence number switch (type) { case EventType.ItemAdded: //Data filter is being updated if (maxDataFilter != _generalAddDataFilter) { _generalAddDataFilter = maxDataFilter; registrationSequenceId = ++_addEventRegistrationSequence; } if (unregisterNotification) _generalAddDataFilter = EventDataFilter.None; break; case EventType.ItemRemoved: if (maxDataFilter != _generalRemoveDataFilter) { _generalRemoveDataFilter = maxDataFilter; registrationSequenceId = ++_removeEventRegistrationSequenceId; } if (unregisterNotification) _generalAddDataFilter = EventDataFilter.None; break; case EventType.ItemUpdated: if (maxDataFilter != _generalUpdateDataFilter) { _generalUpdateDataFilter = maxDataFilter; registrationSequenceId = ++_updateEventRegisrationSequenceId; } if (unregisterNotification) _generalAddDataFilter = EventDataFilter.None; break; } } if (_cache != null) { if (unregisterNotification) { //client is no more interested in event, therefore unregister it from server _cache.UnregiserGeneralCacheNotification(EventsUtil.GetEventTypeInternal(type)); } else if (registrationSequenceId != -1) { //only caused update of data filter either upgrade or downgrade _cache.RegisterCacheNotificationDataFilter(EventsUtil.GetEventTypeInternal(type), maxDataFilter, registrationSequenceId); } } } return null; } public EventRegistrationInfo[] GetEventRegistrationInfo() { List<EventRegistrationInfo> registeredEvents = new List<EventRegistrationInfo>(); lock (SyncLockGeneral) { if (_addEventPool != null && _addEventPool.Count > 0) { registeredEvents.Add(new EventRegistrationInfo(EventTypeInternal.ItemAdded, _generalAddDataFilter, _addEventRegistrationSequence)); } if (_updateEventPool != null && _updateEventPool.Count > 0) { registeredEvents.Add(new EventRegistrationInfo(EventTypeInternal.ItemUpdated, _generalUpdateDataFilter, _updateEventRegisrationSequenceId)); } if (_removeEventPool != null && _removeEventPool.Count > 0) { registeredEvents.Add(new EventRegistrationInfo(EventTypeInternal.ItemRemoved, _generalRemoveDataFilter, _removeEventRegistrationSequenceId)); } } return registeredEvents.ToArray(); } private ResourcePool GetEventPool(EventTypeInternal eventType) { ResourcePool pool = null; if ((eventType & EventTypeInternal.ItemAdded) != 0) pool = _addEventPool; else if ((eventType & EventTypeInternal.ItemRemoved) != 0) pool = _removeEventPool; else if ((eventType & EventTypeInternal.ItemUpdated) != 0) pool = _updateEventPool; return pool; } private static void EndAsyncCallback(IAsyncResult arr) { CacheDataNotificationCallback subscribber = (CacheDataNotificationCallback)arr.AsyncState; try { subscribber.EndInvoke(arr); } catch (Exception e) { } } #region Event Message received handlers /// <summary> /// Handles what to do when a general event message is received /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void OnGeneralEventMessageReceived(object sender, MessageEventArgs args) { MessageItemType type = GetMessageItemType(args); switch (type) { case MessageItemType.MessageEventItem: OnGeneralEventMessageReceived((MessageEventItem)args.Message.Payload); break; case MessageItemType.MessageEventItems: MessageEventItem[] messages = args.Message.Payload as MessageEventItem[]; if (messages != null) { foreach (MessageEventItem item in messages) { OnGeneralEventMessageReceived(item); } } break; } } internal void OnGeneralEventMessageReceived(MessageEventItem eventMessage) { string key = eventMessage.Key; switch (eventMessage.EventType) { case Alachisoft.NCache.Persistence.EventType.ITEM_ADDED_EVENT: RaiseGeneralCacheNotification(key, EventType.ItemAdded, eventMessage.Item, null, CacheItemRemovedReason.Underused, false); break; case Alachisoft.NCache.Persistence.EventType.ITEM_UPDATED_EVENT: RaiseGeneralCacheNotification(key, EventType.ItemUpdated, eventMessage.Item, eventMessage.OldItem, CacheItemRemovedReason.Underused, false); break; case Alachisoft.NCache.Persistence.EventType.ITEM_REMOVED_EVENT: RaiseGeneralCacheNotification(key, EventType.ItemRemoved, eventMessage.Item, null, eventMessage.Reason, false); break; } } /// <summary> /// Handles what to do when a selective event message is received /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void OnSelectiveEventMessageReceived(object sender, MessageEventArgs args) { MessageItemType type = GetMessageItemType(args); switch (type) { case MessageItemType.MessageEventItem: OnSelectiveEventsMessageRecieved((MessageEventItem)args.Message.Payload); break; case MessageItemType.MessageEventItems: MessageEventItem[] messages = args.Message.Payload as MessageEventItem[]; if (messages !=null) { foreach (MessageEventItem item in messages) { OnSelectiveEventsMessageRecieved(item); } } break; } } internal void OnSelectiveEventsMessageRecieved(MessageEventItem eventMessage) { string key = eventMessage.Key; CallbackInfo cbInfo = new CallbackInfo(null, eventMessage.Callback, eventMessage.DataFilter); EventHandle handle = null; if (cbInfo != null) { short handler = (short)cbInfo.Callback; handle = new EventHandle(handler); } switch (eventMessage.EventType) { case Alachisoft.NCache.Persistence.EventType.ITEM_UPDATED_CALLBACK: RaiseSelectiveCacheNotification(key, EventType.ItemUpdated, eventMessage.Item, eventMessage.OldItem, CacheItemRemovedReason.Underused, false, handle, cbInfo.DataFilter); break; case Alachisoft.NCache.Persistence.EventType.ITEM_REMOVED_CALLBACK: RaiseSelectiveCacheNotification(key, EventType.ItemRemoved, eventMessage.Item, null, eventMessage.Reason, false, handle, cbInfo.DataFilter); break; } } #endregion #region / --- Inner Classes --- / class SelectiveRemoveCallbackWrapper { CacheItemRemovedCallback _callback; CacheDataNotificationCallback _mappingCallback; public SelectiveRemoveCallbackWrapper(CacheItemRemovedCallback callback) { _callback = callback; } public void OnCacheDataNotification(string key, CacheEventArg arg) { if (_callback != null) _callback(key, arg.Item.GetValue<object>(), arg.CacheItemRemovedReason); } public CacheDataNotificationCallback MappingCallback { get { if (_mappingCallback == null) _mappingCallback = new CacheDataNotificationCallback(OnCacheDataNotification); return _mappingCallback; } } } class SelectiveUpdateCallbackWrapper { CacheItemUpdatedCallback _callback; CacheDataNotificationCallback _mappingCallback; public SelectiveUpdateCallbackWrapper(CacheItemUpdatedCallback callback) { _callback = callback; } public void OnCacheDataNotification(string key, CacheEventArg arg) { if (_callback != null) _callback(key); } public CacheDataNotificationCallback MappingCallback { get { if (_mappingCallback == null) _mappingCallback = new CacheDataNotificationCallback(OnCacheDataNotification); return _mappingCallback; } } } internal class EventRegistrationInfo { private EventTypeInternal _eventType; private EventDataFilter _filter; private short _registrationSequence; public EventRegistrationInfo() { } public EventRegistrationInfo(EventTypeInternal eventTYpe, EventDataFilter filter, short sequenceId) { _eventType = eventTYpe; _filter = filter; _registrationSequence = sequenceId; } public EventTypeInternal EventTYpe { get { return _eventType; } set { _eventType = value; } } public EventDataFilter DataFilter { get { return _filter; } set { _filter = value; } } public short RegistrationSequence { get { return _registrationSequence; } set { _registrationSequence = value; } } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Mvc.Async; using Abp.Application.Features; using Abp.Auditing; using Abp.Authorization; using Abp.Collections.Extensions; using Abp.Configuration; using Abp.Domain.Uow; using Abp.Localization; using Abp.Localization.Sources; using Abp.Reflection; using Abp.Runtime.Session; using Abp.Timing; using Abp.Web.Models; using Abp.Web.Mvc.Controllers.Results; using Castle.Core.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Abp.Web.Mvc.Controllers { /// <summary> /// Base class for all MVC Controllers in Abp system. /// </summary> public abstract class AbpController : Controller { /// <summary> /// Gets current session information. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Reference to the permission manager. /// </summary> public IPermissionManager PermissionManager { get; set; } /// <summary> /// Reference to the setting manager. /// </summary> public ISettingManager SettingManager { get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IPermissionChecker PermissionChecker { protected get; set; } /// <summary> /// Reference to the feature manager. /// </summary> public IFeatureManager FeatureManager { protected get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IFeatureChecker FeatureChecker { protected get; set; } /// <summary> /// Reference to the localization manager. /// </summary> public ILocalizationManager LocalizationManager { protected get; set; } /// <summary> /// Gets/sets name of the localization source that is used in this application service. /// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods. /// </summary> protected string LocalizationSourceName { get; set; } /// <summary> /// Gets localization source. /// It's valid if <see cref="LocalizationSourceName"/> is set. /// </summary> protected ILocalizationSource LocalizationSource { get { if (LocalizationSourceName == null) { throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource"); } if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName) { _localizationSource = LocalizationManager.GetSource(LocalizationSourceName); } return _localizationSource; } } private ILocalizationSource _localizationSource; /// <summary> /// Reference to the logger to write logs. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets current session information. /// </summary> [Obsolete("Use AbpSession property instead. CurrentSetting will be removed in future releases.")] protected IAbpSession CurrentSession { get { return AbpSession; } } /// <summary> /// Reference to <see cref="IUnitOfWorkManager"/>. /// </summary> public IUnitOfWorkManager UnitOfWorkManager { get { if (_unitOfWorkManager == null) { throw new AbpException("Must set UnitOfWorkManager before use it."); } return _unitOfWorkManager; } set { _unitOfWorkManager = value; } } private IUnitOfWorkManager _unitOfWorkManager; /// <summary> /// Gets current unit of work. /// </summary> protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } } public IAuditingConfiguration AuditingConfiguration { get; set; } public IAuditInfoProvider AuditInfoProvider { get; set; } public IAuditingStore AuditingStore { get; set; } /// <summary> /// This object is used to measure an action execute duration. /// </summary> private Stopwatch _actionStopwatch; private AuditInfo _auditInfo; /// <summary> /// Constructor. /// </summary> protected AbpController() { AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; LocalizationManager = NullLocalizationManager.Instance; PermissionChecker = NullPermissionChecker.Instance; AuditingStore = SimpleLogAuditingStore.Instance; } /// <summary> /// Gets localized string for given key name and current language. /// </summary> /// <param name="name">Key name</param> /// <returns>Localized string</returns> protected virtual string L(string name) { return LocalizationSource.GetString(name); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, params object[] args) { return LocalizationSource.GetString(name, args); } /// <summary> /// Gets localized string for given key name and specified culture information. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <returns>Localized string</returns> protected virtual string L(string name, CultureInfo culture) { return LocalizationSource.GetString(name, culture); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, CultureInfo culture, params object[] args) { return LocalizationSource.GetString(name, culture, args); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected Task<bool> IsGrantedAsync(string permissionName) { return PermissionChecker.IsGrantedAsync(permissionName); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected bool IsGranted(string permissionName) { return PermissionChecker.IsGranted(permissionName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual Task<bool> IsEnabledAsync(string featureName) { return FeatureChecker.IsEnabledAsync(featureName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual bool IsEnabled(string featureName) { return FeatureChecker.IsEnabled(featureName); } /// <summary> /// Json the specified data, contentType, contentEncoding and behavior. /// </summary> /// <param name="data">Data.</param> /// <param name="contentType">Content type.</param> /// <param name="contentEncoding">Content encoding.</param> /// <param name="behavior">Behavior.</param> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { if (data == null) { data = new AjaxResponse(); } else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>))) { data = new AjaxResponse(data); } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } protected override void OnActionExecuting(ActionExecutingContext filterContext) { HandleAuditingBeforeAction(filterContext); base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HandleAuditingAfterAction(filterContext); } #region Auditing private static MethodInfo GetMethodInfo(ActionDescriptor actionDescriptor) { if (actionDescriptor is ReflectedActionDescriptor) { return ((ReflectedActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is ReflectedAsyncActionDescriptor) { return ((ReflectedAsyncActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is TaskAsyncActionDescriptor) { return ((TaskAsyncActionDescriptor)actionDescriptor).MethodInfo; } throw new AbpException("Could not get MethodInfo for the action '" + actionDescriptor.ActionName + "' of controller '" + actionDescriptor.ControllerDescriptor.ControllerName + "'."); } private void HandleAuditingBeforeAction(ActionExecutingContext filterContext) { if (!ShouldSaveAudit(filterContext)) { _auditInfo = null; return; } var methodInfo = GetMethodInfo(filterContext.ActionDescriptor); _actionStopwatch = Stopwatch.StartNew(); _auditInfo = new AuditInfo { TenantId = AbpSession.TenantId, UserId = AbpSession.UserId, ImpersonatorUserId = AbpSession.ImpersonatorUserId, ImpersonatorTenantId = AbpSession.ImpersonatorTenantId, ServiceName = methodInfo.DeclaringType != null ? methodInfo.DeclaringType.FullName : filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, MethodName = methodInfo.Name, Parameters = ConvertArgumentsToJson(filterContext.ActionParameters), ExecutionTime = Clock.Now }; } private void HandleAuditingAfterAction(ActionExecutedContext filterContext) { if (_auditInfo == null || _actionStopwatch == null) { return; } _actionStopwatch.Stop(); _auditInfo.ExecutionDuration = Convert.ToInt32(_actionStopwatch.Elapsed.TotalMilliseconds); _auditInfo.Exception = filterContext.Exception; if (AuditInfoProvider != null) { AuditInfoProvider.Fill(_auditInfo); } AuditingStore.Save(_auditInfo); } private bool ShouldSaveAudit(ActionExecutingContext filterContext) { if (AuditingConfiguration == null) { return false; } if (!AuditingConfiguration.MvcControllers.IsEnabled) { return false; } if (filterContext.IsChildAction && !AuditingConfiguration.MvcControllers.IsEnabledForChildActions) { return false; } return AuditingHelper.ShouldSaveAudit( GetMethodInfo(filterContext.ActionDescriptor), AuditingConfiguration, AbpSession, true ); } private string ConvertArgumentsToJson(IDictionary<string, object> arguments) { try { if (arguments.IsNullOrEmpty()) { return "{}"; } var dictionary = new Dictionary<string, object>(); foreach (var argument in arguments) { dictionary[argument.Key] = argument.Value; } return JsonConvert.SerializeObject( dictionary, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } catch (Exception ex) { Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName); Logger.Warn(ex.ToString(), ex); return "{}"; } } #endregion } }
using System; using System.Collections.Generic; using System.Text; //using NationalInstruments; //using NationalInstruments.Analysis.Math; //using NationalInstruments.Analysis.Dsp; using Data; using Data.EDM; using EDMConfig; namespace Analysis.EDM { public class BlockDemodulator { // you'll be in trouble if the number of points per block is not divisible by this number! private const int kFourierAverage = 16; private const int kNumReplicates = 50; private Random r = new Random(); // This function gates the detector data first, and then demodulates the channels. // This means that it can give innacurate results for non-linear combinations // of channels that vary appreciably over the TOF. There's another, slower, function // DemodulateBlockNL that takes care of this. public DemodulatedBlock DemodulateBlock(Block b, DemodulationConfig config) { // *** copy across the metadata *** DemodulatedBlock db = new DemodulatedBlock(); db.TimeStamp = b.TimeStamp; db.Config = b.Config; db.DemodulationConfig = config; // *** extract the gated detector data using the given config *** List<GatedDetectorData> gatedDetectorData = new List<GatedDetectorData>(); int ind = 0; foreach (string d in b.detectors) { GatedDetectorExtractSpec gdes; config.GatedDetectorExtractSpecs.TryGetValue(d, out gdes); if (gdes != null) { gatedDetectorData.Add(GatedDetectorData.ExtractFromBlock(b, gdes)); db.DetectorIndices.Add(gdes.Name, ind); ind++; db.DetectorCalibrations.Add(gdes.Name, ((TOF)((EDMPoint)b.Points[0]).Shot.TOFs[gdes.Index]).Calibration); } } //foreach (KeyValuePair<string, GatedDetectorExtractSpec> spec in config.GatedDetectorExtractSpecs) //{ // GatedDetectorExtractSpec gate = spec.Value; // gatedDetectorData.Add(GatedDetectorData.ExtractFromBlock(b, gate)); // db.DetectorIndices.Add(gate.Name, ind); // ind++; // db.DetectorCalibrations.Add(gate.Name, // ((TOF)((EDMPoint)b.Points[0]).Shot.TOFs[gate.Index]).Calibration); //} // ** normalise the top detector ** gatedDetectorData.Add( gatedDetectorData[db.DetectorIndices["top"]] / gatedDetectorData[db.DetectorIndices["norm"]]); db.DetectorIndices.Add("topNormed", db.DetectorIndices.Count); // *** extract the point detector data *** List<PointDetectorData> pointDetectorData = new List<PointDetectorData>(); foreach (string channel in config.PointDetectorChannels) { pointDetectorData.Add(PointDetectorData.ExtractFromBlock(b, channel)); // for the moment all single point detector channels are set to have a calibration // of 1.0 . db.DetectorCalibrations.Add(channel, 1.0); } // *** build the list of detector data *** List<DetectorData> detectorData = new List<DetectorData>(); for (int i = 0; i < gatedDetectorData.Count; i++) detectorData.Add(gatedDetectorData[i]); for (int i = 0; i < config.PointDetectorChannels.Count; i++) { detectorData.Add(pointDetectorData[i]); db.DetectorIndices.Add(config.PointDetectorChannels[i], i + gatedDetectorData.Count); } // calculate the norm FFT db.NormFourier = DetectorFT.MakeFT(gatedDetectorData[db.DetectorIndices["norm"]], kFourierAverage); // *** demodulate channels *** // ** build the list of modulations ** List<string> modNames = new List<string>(); List<Waveform> modWaveforms = new List<Waveform>(); foreach (AnalogModulation mod in b.Config.AnalogModulations) { modNames.Add(mod.Name); modWaveforms.Add(mod.Waveform); } foreach (DigitalModulation mod in b.Config.DigitalModulations) { modNames.Add(mod.Name); modWaveforms.Add(mod.Waveform); } foreach (TimingModulation mod in b.Config.TimingModulations) { modNames.Add(mod.Name); modWaveforms.Add(mod.Waveform); } // ** work out the switch state for each point ** int blockLength = modWaveforms[0].Length; List<bool[]> wfBits = new List<bool[]>(); foreach (Waveform wf in modWaveforms) wfBits.Add(wf.Bits); List<uint> switchStates = new List<uint>(blockLength); for (int i = 0; i < blockLength; i++) { uint switchState = 0; for (int j = 0; j < wfBits.Count; j++) { if (wfBits[j][i]) switchState += (uint)Math.Pow(2, j); } switchStates.Add(switchState); } // pre-calculate the state signs for each analysis channel // the first index selects the analysis channel, the second the switchState int numStates = (int)Math.Pow(2, modWaveforms.Count); int[,] stateSigns = new int[numStates, numStates]; for (uint i = 0; i < numStates; i++) { for (uint j = 0; j < numStates; j++) { stateSigns[i, j] = stateSign(j, i); } } // ** the following needs to be done for each detector ** for (int detector = 0; detector < detectorData.Count; detector++) { DetectorChannelValues dcv = new DetectorChannelValues(); for (int i = 0; i < modNames.Count; i++) dcv.SwitchMasks.Add(modNames[i], (uint)(1 << i)); // * divide the data up into bins according to switch state * List<List<double>> statePoints = new List<List<double>>(numStates); for (int i = 0; i < numStates; i++) statePoints.Add(new List<double>(blockLength / numStates)); for (int i = 0; i < blockLength; i++) { statePoints[(int)switchStates[i]].Add(detectorData[detector].PointValues[i]); } // * calculate the channel values * int subLength = blockLength / numStates; double[,] channelValues = new double[numStates, subLength]; for (int channel = 0; channel < numStates; channel++) { for (int subIndex = 0; subIndex < subLength; subIndex++) { double chanVal = 0; for (int i = 0; i < numStates; i++) chanVal += stateSigns[channel, i] * statePoints[i][subIndex]; chanVal /= (double)numStates; channelValues[channel, subIndex] = chanVal; } } //* calculate the channel means * double[] channelMeans = new double[numStates]; for (int channel = 0; channel < numStates; channel++) { double total = 0; for (int i = 0; i < subLength; i++) total += channelValues[channel, i]; total /= blockLength / numStates; channelMeans[channel] = total; } dcv.Values = channelMeans; //* calculate the channel errors * double[] channelErrors = new double[numStates]; for (int channel = 0; channel < numStates; channel++) { double total = 0; for (int i = 0; i < subLength; i++) total += Math.Pow(channelValues[channel, i] - channelMeans[channel], 2); total /= subLength * (subLength - 1); total = Math.Sqrt(total); channelErrors[channel] = total; } dcv.Errors = channelErrors; db.ChannelValues.Add(dcv); } return db; } // DemodulateBlockNL augments the channel values returned by DemodulateBlock // with several non-linear combinations of channels (E.B/DB, the correction, etc). // These non-linear channels are calculated point-by-point for the TOF and then // integrated according to the Demodulation config. This is calculated for top and // topNormed detectors only for speed. // public DemodulatedBlock DemodulateBlockNL(Block b, DemodulationConfig config) { // we start with the standard demodulated block DemodulatedBlock dblock = DemodulateBlock(b, config); // First do everything for the un-normalised top detector int tdi = dblock.DetectorIndices["top"]; // TOF demodulate the block to get the channel wiggles // the BlockTOFDemodulator only demodulates the PMT detector BlockTOFDemodulator btdt = new BlockTOFDemodulator(); TOFChannelSet tcst = btdt.TOFDemodulateBlock(b, tdi, false); // now repeat having normed the block // normalise the PMT signal b.Normalise(config.GatedDetectorExtractSpecs["norm"]); int tndi = dblock.DetectorIndices["topNormed"]; // TOF demodulate the block to get the channel wiggles // the BlockTOFDemodulator only demodulates the PMT detector BlockTOFDemodulator btd = new BlockTOFDemodulator(); TOFChannelSet tcs = btd.TOFDemodulateBlock(b, tndi, false); // get hold of the gating data GatedDetectorExtractSpec gate = config.GatedDetectorExtractSpecs["top"]; // gate the special channels TOFChannel edmDB = (TOFChannel)tcs.GetChannel("EDMDB" ); double edmDBG = edmDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel corrDB = (TOFChannel)tcs.GetChannel( "CORRDB" ); double corrDBG = corrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel edmCorrDB = (TOFChannel)tcs.GetChannel( "EDMCORRDB" ); double edmCorrDBG = edmCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel corrDB_old = (TOFChannel)tcs.GetChannel( "CORRDB_OLD" ); double corrDBG_old = corrDB_old.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel edmCorrDB_old = (TOFChannel)tcs.GetChannel( "EDMCORRDB_OLD" ); double edmCorrDBG_old = edmCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1fDB = (TOFChannel)tcs.GetChannel( "RF1FDB" ); double rf1fDBG = rf1fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2fDB = (TOFChannel)tcs.GetChannel( "RF2FDB" ); double rf2fDBG = rf2fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1fDBDB = (TOFChannel)tcs.GetChannel( "RF1FDBDB" ); double rf1fDBDBG = rf1fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2fDBDB = (TOFChannel)tcs.GetChannel( "RF2FDBDB" ); double rf2fDBDBG = rf2fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1aDB = (TOFChannel)tcs.GetChannel("RF1ADB"); double rf1aDBG = rf1aDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2aDB = (TOFChannel)tcs.GetChannel("RF2ADB"); double rf2aDBG = rf2aDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1aDBDB = (TOFChannel)tcs.GetChannel("RF1ADBDB"); double rf1aDBDBG = rf1aDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2aDBDB = (TOFChannel)tcs.GetChannel("RF2ADBDB"); double rf2aDBDBG = rf2aDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf1DB = (TOFChannel)tcs.GetChannel("LF1DB"); double lf1DBG = lf1DB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf1DBDB = (TOFChannel)tcs.GetChannel("LF1DBDB"); double lf1DBDBG = lf1DBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf2DB = (TOFChannel)tcs.GetChannel("LF2DB"); double lf2DBG = lf2DB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf2DBDB = (TOFChannel)tcs.GetChannel("LF2DBDB"); double lf2DBDBG = lf2DBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel BDB = (TOFChannel)tcs.GetChannel("BDB"); double BDBG = BDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf1fDB = (TOFChannel)tcs.GetChannel( "ERF1FDB" ); double erf1fDBG = erf1fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf2fDB = (TOFChannel)tcs.GetChannel( "ERF2FDB" ); double erf2fDBG = erf2fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf1fDBDB = (TOFChannel)tcs.GetChannel( "ERF1FDBDB" ); double erf1fDBDBG = erf1fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf2fDBDB = (TOFChannel)tcs.GetChannel("ERF2FDBDB" ); double erf2fDBDBG = erf2fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel brf1fCorrDB = (TOFChannel)tcs.GetChannel( "BRF1FCORRDB" ); double brf1fCorrDBG = brf1fCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel brf2fCorrDB = (TOFChannel)tcs.GetChannel( "BRF2FCORRDB" ); double brf2fCorrDBG = brf2fCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); //Repeat for top TOFChannel edmDBtop = (TOFChannel)tcst.GetChannel("EDMDB"); double edmDBGtop = edmDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel corrDBtop = (TOFChannel)tcst.GetChannel("CORRDB"); double corrDBGtop = corrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel edmCorrDBtop = (TOFChannel)tcst.GetChannel("EDMCORRDB"); double edmCorrDBGtop = edmCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel corrDB_oldtop = (TOFChannel)tcst.GetChannel("CORRDB_OLD"); double corrDBG_oldtop = corrDB_old.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel edmCorrDB_oldtop = (TOFChannel)tcst.GetChannel("EDMCORRDB_OLD"); double edmCorrDBG_oldtop = edmCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1fDBtop = (TOFChannel)tcst.GetChannel("RF1FDB"); double rf1fDBGtop = rf1fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2fDBtop = (TOFChannel)tcst.GetChannel("RF2FDB"); double rf2fDBGtop = rf2fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1fDBDBtop = (TOFChannel)tcst.GetChannel("RF1FDBDB"); double rf1fDBDBGtop = rf1fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2fDBDBtop = (TOFChannel)tcst.GetChannel("RF2FDBDB"); double rf2fDBDBGtop = rf2fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1aDBtop = (TOFChannel)tcst.GetChannel("RF1ADB"); double rf1aDBGtop = rf1aDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2aDBtop = (TOFChannel)tcst.GetChannel("RF2ADB"); double rf2aDBGtop = rf2aDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf1aDBDBtop = (TOFChannel)tcst.GetChannel("RF1ADBDB"); double rf1aDBDBGtop = rf1aDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel rf2aDBDBtop = (TOFChannel)tcst.GetChannel("RF2ADBDB"); double rf2aDBDBGtop = rf2aDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf1DBtop = (TOFChannel)tcst.GetChannel("LF1DB"); double lf1DBGtop = lf1DB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf1DBDBtop = (TOFChannel)tcst.GetChannel("LF1DBDB"); double lf1DBDBGtop = lf1DBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf2DBtop = (TOFChannel)tcst.GetChannel("LF2DB"); double lf2DBGtop = lf2DB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel lf2DBDBtop = (TOFChannel)tcst.GetChannel("LF2DBDB"); double lf2DBDBGtop = lf2DBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel BDBtop = (TOFChannel)tcst.GetChannel("BDB"); double BDBGtop = BDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf1fDBtop = (TOFChannel)tcst.GetChannel("ERF1FDB"); double erf1fDBGtop = erf1fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf2fDBtop = (TOFChannel)tcst.GetChannel("ERF2FDB"); double erf2fDBGtop = erf2fDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf1fDBDBtop = (TOFChannel)tcst.GetChannel("ERF1FDBDB"); double erf1fDBDBGtop = erf1fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel erf2fDBDBtop = (TOFChannel)tcst.GetChannel("ERF2FDBDB"); double erf2fDBDBGtop = erf2fDBDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel brf1fCorrDBtop = (TOFChannel)tcst.GetChannel("BRF1FCORRDB"); double brf1fCorrDBGtop = brf1fCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); TOFChannel brf2fCorrDBtop = (TOFChannel)tcst.GetChannel("BRF2FCORRDB"); double brf2fCorrDBGtop = brf2fCorrDB.Difference.GatedMean(gate.GateLow, gate.GateHigh); // we bodge the errors, which aren't really used for much anyway // by just using the error from the normal dblock. I ignore the error in DB. // I use the simple correction error for the full correction. Doesn't much matter. DetectorChannelValues dcv = dblock.ChannelValues[tndi]; double edmDBE = dcv.GetError(new string[] { "E", "B" }) / dcv.GetValue(new string[] { "DB" }); double corrDBE = Math.Sqrt( Math.Pow(dcv.GetValue(new string[] { "E", "DB" }) * dcv.GetError(new string[] { "B" }), 2) + Math.Pow(dcv.GetValue(new string[] { "B" }) * dcv.GetError(new string[] { "E", "DB" }), 2) ) / Math.Pow(dcv.GetValue(new string[] { "DB" }), 2); double edmCorrDBE = Math.Sqrt( Math.Pow(edmDBE, 2) + Math.Pow(corrDBE, 2)); double rf1fDBE = dcv.GetError(new string[] { "RF1F" }) / dcv.GetValue(new string[] { "DB" }); double rf2fDBE = dcv.GetError(new string[] { "RF2F" }) / dcv.GetValue(new string[] { "DB" }); double rf1fDBDBE = dcv.GetError(new string[] { "DB", "RF1F" }) / dcv.GetValue(new string[] { "DB" }); double rf2fDBDBE = dcv.GetError(new string[] { "DB", "RF2F" }) / dcv.GetValue(new string[] { "DB" }); double rf1aDBE = dcv.GetError(new string[] { "RF1A" }) / dcv.GetValue(new string[] { "DB" }); double rf2aDBE = dcv.GetError(new string[] { "RF2A" }) / dcv.GetValue(new string[] { "DB" }); double rf1aDBDBE = dcv.GetError(new string[] { "DB", "RF1A" }) / dcv.GetValue(new string[] { "DB" }); double rf2aDBDBE = dcv.GetError(new string[] { "DB", "RF2A" }) / dcv.GetValue(new string[] { "DB" }); double lf1DBE = dcv.GetError(new string[] { "LF1" }) / dcv.GetValue(new string[] { "DB" }); double lf1DBDBE = dcv.GetError(new string[] { "DB", "LF1" }) / dcv.GetValue(new string[] { "DB" }); double lf2DBE = dcv.GetError(new string[] { "LF2" }) / dcv.GetValue(new string[] { "DB" }); double lf2DBDBE = dcv.GetError(new string[] { "DB", "LF2" }) / dcv.GetValue(new string[] { "DB" }); double brf1fDBE = dcv.GetError(new string[] { "B", "RF1F" }) / dcv.GetValue(new string[] { "DB" }); double brf2fDBE = dcv.GetError(new string[] { "B", "RF2F" }) / dcv.GetValue(new string[] { "DB" }); double erf1fDBE = dcv.GetError(new string[] { "E", "RF1F" }) / dcv.GetValue(new string[] { "DB" }); double erf2fDBE = dcv.GetError(new string[] { "E", "RF2F" }) / dcv.GetValue(new string[] { "DB" }); double erf1fDBDBE = dcv.GetError(new string[] { "E", "DB", "RF1F" }) / dcv.GetValue(new string[] { "DB" }); double erf2fDBDBE = dcv.GetError(new string[] { "E", "DB", "RF2F" }) / dcv.GetValue(new string[] { "DB" }); double BDBE = dcv.GetError(new string[] { "B" }) / dcv.GetValue(new string[] { "DB" }); //repeat for top DetectorChannelValues dcvt = dblock.ChannelValues[tdi]; double lf2DBEtop = dcvt.GetError(new string[] { "LF2" }) / dcvt.GetValue(new string[] { "DB" }); //Change the db channel back to topNormed double lf2DBDBEtop = dcvt.GetError(new string[] { "DB", "LF2" }) / dcvt.GetValue(new string[] { "DB" }); //Change the db channel back to topNormed double edmDBEtop = dcvt.GetError(new string[] { "E", "B" }) / dcvt.GetValue(new string[] { "DB" }); double corrDBEtop = Math.Sqrt( Math.Pow(dcvt.GetValue(new string[] { "E", "DB" }) * dcvt.GetError(new string[] { "B" }), 2) + Math.Pow(dcvt.GetValue(new string[] { "B" }) * dcvt.GetError(new string[] { "E", "DB" }), 2)) / Math.Pow(dcvt.GetValue(new string[] { "DB" }), 2); double edmCorrDBEtop = Math.Sqrt(Math.Pow(edmDBEtop, 2) + Math.Pow(corrDBEtop, 2)); double rf1fDBEtop = dcvt.GetError(new string[] { "RF1F" }) / dcvt.GetValue(new string[] { "DB" }); double rf2fDBEtop = dcvt.GetError(new string[] { "RF2F" }) / dcvt.GetValue(new string[] { "DB" }); double rf1fDBDBEtop = dcvt.GetError(new string[] { "DB", "RF1F" }) / dcvt.GetValue(new string[] { "DB" }); double rf2fDBDBEtop = dcvt.GetError(new string[] { "DB", "RF2F" }) / dcvt.GetValue(new string[] { "DB" }); double rf1aDBEtop = dcvt.GetError(new string[] { "RF1A" }) / dcvt.GetValue(new string[] { "DB" }); double rf2aDBEtop = dcvt.GetError(new string[] { "RF2A" }) / dcvt.GetValue(new string[] { "DB" }); double rf1aDBDBEtop = dcvt.GetError(new string[] { "DB", "RF1A" }) / dcvt.GetValue(new string[] { "DB" }); double rf2aDBDBEtop = dcvt.GetError(new string[] { "DB", "RF2A" }) / dcvt.GetValue(new string[] { "DB" }); double lf1DBEtop = dcvt.GetError(new string[] { "LF1" }) / dcvt.GetValue(new string[] { "DB" }); double lf1DBDBEtop = dcvt.GetError(new string[] { "DB", "LF1" }) / dcvt.GetValue(new string[] { "DB" }); double brf1fDBEtop = dcvt.GetError(new string[] { "B", "RF1F" }) / dcvt.GetValue(new string[] { "DB" }); double brf2fDBEtop = dcvt.GetError(new string[] { "B", "RF2F" }) / dcvt.GetValue(new string[] { "DB" }); double erf1fDBEtop = dcvt.GetError(new string[] { "E", "RF1F" }) / dcvt.GetValue(new string[] { "DB" }); double erf2fDBEtop = dcvt.GetError(new string[] { "E", "RF2F" }) / dcvt.GetValue(new string[] { "DB" }); double erf1fDBDBEtop = dcvt.GetError(new string[] { "E", "DB", "RF1F" }) / dcvt.GetValue(new string[] { "DB" }); double erf2fDBDBEtop = dcvt.GetError(new string[] { "E", "DB", "RF2F" }) / dcvt.GetValue(new string[] { "DB" }); double BDBEtop = dcvt.GetError(new string[] { "B" }) / dcvt.GetValue(new string[] { "DB" }); // stuff the data into the dblock dblock.ChannelValues[tndi].SpecialValues["EDMDB"] = new double[] { edmDBG, edmDBE }; dblock.ChannelValues[tndi].SpecialValues["CORRDB"] = new double[] { corrDBG, corrDBE }; dblock.ChannelValues[tndi].SpecialValues["EDMCORRDB"] = new double[] { edmCorrDBG, edmCorrDBE }; dblock.ChannelValues[tndi].SpecialValues["CORRDB_OLD"] = new double[] { corrDBG_old, corrDBE }; dblock.ChannelValues[tndi].SpecialValues["EDMCORRDB_OLD"] = new double[] { edmCorrDBG_old, edmCorrDBE }; dblock.ChannelValues[tndi].SpecialValues["RF1FDB"] = new double[] { rf1fDBG, rf1fDBE }; dblock.ChannelValues[tndi].SpecialValues["RF2FDB"] = new double[] { rf2fDBG, rf2fDBE }; dblock.ChannelValues[tndi].SpecialValues["RF1FDBDB"] = new double[] { rf1fDBDBG, rf1fDBDBE }; dblock.ChannelValues[tndi].SpecialValues["RF2FDBDB"] = new double[] { rf2fDBDBG, rf2fDBDBE }; dblock.ChannelValues[tndi].SpecialValues["RF1ADB"] = new double[] { rf1aDBG, rf1aDBE }; dblock.ChannelValues[tndi].SpecialValues["RF2ADB"] = new double[] { rf2aDBG, rf2aDBE }; dblock.ChannelValues[tndi].SpecialValues["RF1ADBDB"] = new double[] { rf1aDBDBG, rf1aDBDBE }; dblock.ChannelValues[tndi].SpecialValues["RF2ADBDB"] = new double[] { rf2aDBDBG, rf2aDBDBE }; dblock.ChannelValues[tndi].SpecialValues["BRF1FCORRDB"] = new double[] { brf1fCorrDBG, brf1fDBE }; dblock.ChannelValues[tndi].SpecialValues["BRF2FCORRDB"] = new double[] { brf2fCorrDBG, brf2fDBE }; dblock.ChannelValues[tndi].SpecialValues["ERF1FDB"] = new double[] { erf1fDBG, erf1fDBE }; dblock.ChannelValues[tndi].SpecialValues["ERF2FDB"] = new double[] { erf2fDBG, erf2fDBE }; dblock.ChannelValues[tndi].SpecialValues["ERF1FDBDB"] = new double[] { erf1fDBDBG, erf1fDBDBE }; dblock.ChannelValues[tndi].SpecialValues["ERF2FDBDB"] = new double[] { erf2fDBDBG, erf2fDBDBE }; dblock.ChannelValues[tndi].SpecialValues["LF1DB"] = new double[] { lf1DBG, lf1DBE }; dblock.ChannelValues[tndi].SpecialValues["LF1DBDB"] = new double[] { lf1DBDBG, lf1DBDBE }; dblock.ChannelValues[tndi].SpecialValues["LF2DB"] = new double[] { lf2DBG, lf2DBE }; dblock.ChannelValues[tndi].SpecialValues["LF2DBDB"] = new double[] { lf2DBDBG, lf2DBDBE }; dblock.ChannelValues[tndi].SpecialValues["BDB"] = new double[] { BDBG, BDBE }; dblock.ChannelValues[tdi].SpecialValues["EDMDB"] = new double[] { edmDBGtop, edmDBEtop }; dblock.ChannelValues[tdi].SpecialValues["CORRDB"] = new double[] { corrDBGtop, corrDBEtop }; dblock.ChannelValues[tdi].SpecialValues["EDMCORRDB"] = new double[] { edmCorrDBGtop, edmCorrDBEtop }; dblock.ChannelValues[tdi].SpecialValues["CORRDB_OLD"] = new double[] { corrDBG_oldtop, corrDBEtop }; dblock.ChannelValues[tdi].SpecialValues["EDMCORRDB_OLD"] = new double[] { edmCorrDBG_oldtop, edmCorrDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF1FDB"] = new double[] { rf1fDBGtop, rf1fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF2FDB"] = new double[] { rf2fDBGtop, rf2fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF1FDBDB"] = new double[] { rf1fDBDBGtop, rf1fDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF2FDBDB"] = new double[] { rf2fDBDBGtop, rf2fDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF1ADB"] = new double[] { rf1aDBGtop, rf1aDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF2ADB"] = new double[] { rf2aDBGtop, rf2aDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF1ADBDB"] = new double[] { rf1aDBDBGtop, rf1aDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["RF2ADBDB"] = new double[] { rf2aDBDBGtop, rf2aDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["BRF1FCORRDB"] = new double[] { brf1fCorrDBGtop, brf1fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["BRF2FCORRDB"] = new double[] { brf2fCorrDBGtop, brf2fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["ERF1FDB"] = new double[] { erf1fDBGtop, erf1fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["ERF2FDB"] = new double[] { erf2fDBGtop, erf2fDBEtop }; dblock.ChannelValues[tdi].SpecialValues["ERF1FDBDB"] = new double[] { erf1fDBDBGtop, erf1fDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["ERF2FDBDB"] = new double[] { erf2fDBDBGtop, erf2fDBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["LF1DB"] = new double[] { lf1DBGtop, lf1DBEtop }; dblock.ChannelValues[tdi].SpecialValues["LF1DBDB"] = new double[] { lf1DBDBGtop, lf1DBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["LF2DB"] = new double[] { lf2DBGtop, lf2DBEtop }; dblock.ChannelValues[tdi].SpecialValues["LF2DBDB"] = new double[] { lf2DBDBGtop, lf2DBDBEtop }; dblock.ChannelValues[tdi].SpecialValues["BDB"] = new double[] { BDBGtop, BDBEtop }; return dblock; } // calculate, for a given analysis channel, whether a given state contributes // positively or negatively public int stateSign(uint state, uint analysisChannel) { uint maskedState = state & analysisChannel; if (parity(maskedState) == parity(analysisChannel)) return 1; else return -1; } // now _this_ is code! Old skool!!! public uint parity(uint p) { p = p ^ (p >> 16); p = p ^ (p >> 8); p = p ^ (p >> 4); p = p ^ (p >> 2); p = p ^ (p >> 1); return p & 1; } public double bootstrapMean(double[] values) { // make the replicate double[] replicate = new double[values.Length]; for (int i = 0; i < values.Length; i++) replicate[i] = values[r.Next(values.Length)]; // find its mean double total = 0.0; foreach (double d in replicate) total += d; total /= replicate.Length; return total; } } }
using System; using System.Collections; using ASPNET.StarterKit.DataAccessLayer; using System.Collections.Generic; namespace ASPNET.StarterKit.BusinessLogicLayer { public class Project { /*** FIELD PRIVATE ***/ private decimal _ActualDuration; private string _CreatorUserName; private DateTime _CompletionDate; private DateTime _DateCreated; private string _Description; private decimal _EstimateDuration; private int _Id; private string _ManagerUserName; private string _Name; /*** CONSTRUCTOR ***/ public Project(string creatorUsername, string managerUserName, string name) : this(DefaultValues.GetDurationMinValue(), creatorUsername, DefaultValues.GetDateTimeMinValue(), DefaultValues.GetDateTimeMinValue(), string.Empty, DefaultValues.GetProjectDurationMinValue(), DefaultValues.GetProjectIdMinValue(), managerUserName, name) { } public Project(string creatorUsername, string description, int id, string managerUserName, string name) : this(DefaultValues.GetDurationMinValue(), creatorUsername, DefaultValues.GetDateTimeMinValue(), DefaultValues.GetDateTimeMinValue(), string.Empty, DefaultValues.GetProjectDurationMinValue(), DefaultValues.GetProjectIdMinValue(), managerUserName, name) { } public Project(decimal actualDuration, string creatorUserName, DateTime completionDate, DateTime dateCreated, string description, decimal estimateDuration, int id, string managerUserName, string name) { // Validate Mandatory Fields// if (String.IsNullOrEmpty(creatorUserName)) throw (new NullReferenceException("creatorUsername")); if (String.IsNullOrEmpty(managerUserName)) throw (new NullReferenceException("managerUserName")); if (String.IsNullOrEmpty(name)) throw (new NullReferenceException("name")); _ActualDuration = actualDuration; _CreatorUserName = creatorUserName; _CompletionDate = completionDate; _DateCreated = dateCreated; _Description = description; _EstimateDuration = estimateDuration; _Id = id; _ManagerUserName = managerUserName; _Name = name; } /*** PROPERTIES ***/ public decimal ActualDuration { get { return _ActualDuration; } } public string CreatorUserName { get { if (String.IsNullOrEmpty(_CreatorUserName)) return string.Empty; else return _CreatorUserName; } } public DateTime CompletionDate { get { return _CompletionDate; } set { _CompletionDate = value; } } public DateTime DateCreated { get { return _DateCreated; } } public string Description { get { if (String.IsNullOrEmpty(_Description)) return string.Empty; else return _Description; } set { _Description = value; } } public decimal EstimateDuration { get { return _EstimateDuration; } set { _EstimateDuration = value; } } public int Id { get { return _Id; } } public string ManagerUserName { get { if (String.IsNullOrEmpty(_ManagerUserName)) return string.Empty; else return _ManagerUserName; } set { _ManagerUserName = value; } } public string Name { get { if (String.IsNullOrEmpty(_Name)) return string.Empty; else return _Name; } set { _Name = value; } } /*** METHODS ***/ public bool Delete() { if (this.Id > DefaultValues.GetProjectIdMinValue()) { DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return DALLayer.DeleteProject(this.Id); } else return false; } public bool Save() { DataAccess DALLayer = DataAccessHelper.GetDataAccess(); if (Id <= DefaultValues.GetProjectIdMinValue()) { int TempId = DALLayer.CreateNewProject(this); if (TempId > DefaultValues.GetProjectIdMinValue()) { _Id = TempId; return true; } else return false; } else return (DALLayer.UpdateProject(this)); } /*** METHOD STATIC ***/ public static bool AddUserToProject(int projectId, string userName) { if (projectId <= DefaultValues.GetProjectIdMinValue()) throw (new ArgumentOutOfRangeException("projectId")); if (String.IsNullOrEmpty(userName)) throw (new NullReferenceException("userName")); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.AddUserToProject(projectId, userName)); } public static bool DeleteProject(int Id) { if (Id <= DefaultValues.GetProjectIdMinValue()) throw (new ArgumentOutOfRangeException("Id")); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.DeleteProject(Id)); } public static List<Project> GetAllProjects() { DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.GetAllProjects()); } public static List<Project> GetAllProjects(string sortParameter) { DataAccess DALLayer = DataAccessHelper.GetDataAccess(); List<Project> projectList = DALLayer.GetAllProjects(); if (String.IsNullOrEmpty(sortParameter)) projectList.Sort(new ProjectComparer(sortParameter)); return (projectList); } public static Project GetProjectById(int Id) { if (Id <= DefaultValues.GetProjectIdMinValue()) return (null); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.GetProjectById(Id)); } public static List<Project> GetProjectByIds(string ProjectIds) { if (String.IsNullOrEmpty(ProjectIds)) return (new List<Project>()); char[] separator = new char[] { ',' }; string[] substrings = ProjectIds.Split(separator); List<Project> list = new List<Project>(); foreach (string str in substrings) { if (!string.IsNullOrEmpty(str)) { int id = Convert.ToInt32(str); list.Add(Project.GetProjectById(id)); } } return list; } public static List<Project> GetProjectsByManagerUserName(string sortParameter, string userName) { if (String.IsNullOrEmpty(userName)) return (new List<Project>()); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); List<Project> prjColl = DALLayer.GetProjectsByManagerUserName(userName); if (String.IsNullOrEmpty(sortParameter)) prjColl.Sort(new ProjectComparer(sortParameter)); return prjColl; } public static List<string> GetProjectMembers(int Id) { if (Id <= DefaultValues.GetProjectIdMinValue()) return (new List<string>()); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.GetProjectMembers(Id)); } public static List<string> GetProjectMembers(string userNames) { if (String.IsNullOrEmpty(userNames)) return (new List<string>()); char[] separator = new char[] { ',' }; string[] substrings = userNames.Split(separator); List<string> list = new List<string>(); foreach (string str in substrings) { if (!string.IsNullOrEmpty(str)) { int Id = Convert.ToInt32(str); List<string> tempList = Project.GetProjectMembers(Id); foreach (string userName in tempList) { if (!list.Contains(userName)) { list.Add(userName); } } } } return list; } public static List<Project> GetProjectsByUserName(string userName) { if (String.IsNullOrEmpty(userName)) return (new List<Project>()); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.GetProjectsByUserName(userName)); } public static bool RemoveUserFromProject(int projectId, string userName) { if (projectId <= DefaultValues.GetProjectIdMinValue()) throw (new ArgumentOutOfRangeException("projectId")); if (String.IsNullOrEmpty(userName)) throw (new NullReferenceException("userName")); DataAccess DALLayer = DataAccessHelper.GetDataAccess(); return (DALLayer.RemoveUserFromProject(projectId, userName)); } } }
// Track BuildR // Available on the Unity3D Asset Store // Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com // For support contact email@jasperstocker.com // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections.Generic; public class TrackBuildRGenerator : MonoBehaviour { public TrackBuildRTrack track; public List<GameObject> meshHolders = new List<GameObject>(); public List<GameObject> colliderHolders = new List<GameObject>(); public void OnEnable() { hideFlags = HideFlags.HideInInspector; } public void UpdateRender() { if (track.numberOfCurves == 0) return; track.RecalculateCurves(); float trackMeshRes = track.meshResolution; float bumperDistanceA = 0; float bumperDistanceB = 0; int numberOfCurves = track.numberOfCurves; bool renderTrack = track.render; float UVOffset = 0; int polyCount = 0; for (int i = 0; i < numberOfCurves; i++) { TrackBuildRPoint curve = track[i]; DynamicMeshGenericMultiMaterialMesh dynamicTrackMesh = curve.dynamicTrackMesh; DynamicMeshGenericMultiMaterialMesh dynamicBoundaryMesh = curve.dynamicBoundaryMesh; DynamicMeshGenericMultiMaterialMesh dynamicOffroadMesh = curve.dynamicOffroadMesh; DynamicMeshGenericMultiMaterialMesh dynamicBumperMesh = curve.dynamicBumperMesh; DynamicMeshGenericMultiMaterialMesh dynamicColliderMesh = curve.dynamicColliderMesh; DynamicMeshGenericMultiMaterialMesh dynamicBottomMesh = curve.dynamicBottomMesh; if (!curve.render || !renderTrack) { dynamicTrackMesh.Clear(); dynamicBoundaryMesh.Clear(); dynamicColliderMesh.Clear(); dynamicOffroadMesh.Clear(); dynamicBumperMesh.Clear(); dynamicBottomMesh.Clear(); } if (curve.shouldReRender && curve.render && renderTrack) { dynamicTrackMesh.Clear(); dynamicTrackMesh.subMeshCount = 1; dynamicBoundaryMesh.Clear(); dynamicBoundaryMesh.subMeshCount = 1; dynamicColliderMesh.Clear(); dynamicColliderMesh.subMeshCount = 1; dynamicOffroadMesh.Clear(); dynamicOffroadMesh.subMeshCount = 1; dynamicBumperMesh.Clear(); dynamicBumperMesh.subMeshCount = 1; dynamicBottomMesh.Clear(); dynamicBottomMesh.subMeshCount = 1; dynamicTrackMesh.name = "curve " + i + " track mesh"; dynamicBoundaryMesh.name = "curve " + i + " boundary mesh"; dynamicColliderMesh.name = "curve " + i + " trackCollider mesh"; dynamicOffroadMesh.name = "curve " + i + " offroad mesh"; dynamicBumperMesh.name = "curve " + i + " bumper mesh"; dynamicBottomMesh.name = "curve " + i + " bottom mesh"; bool trackTextureFlip = (track.numberOfTextures > 0) ? track.Texture(curve.trackTextureStyleIndex).flipped : false; bool boundaryTextureFlip = (track.numberOfTextures > 0) ? track.Texture(curve.boundaryTextureStyleIndex).flipped : false; bool bumperTextureFlip = (track.numberOfTextures > 0) ? track.Texture(curve.bumperTextureStyleIndex).flipped : false; bool bottomTextureFlip = (track.numberOfTextures > 0) ? track.Texture(curve.bottomTextureStyleIndex).flipped : false; int storedPointSize = curve.storedPointSize; float curveLength = curve.arcLength; //Store these points so we can use previous values when Bezier clips itself Vector3 leftPointA = curve.sampledLeftBoundaryPoints[0]; Vector3 rightPointA = curve.sampledRightBoundaryPoints[0]; Vector3 leftPointB = curve.sampledLeftBoundaryPoints[0]; Vector3 rightPointB = curve.sampledRightBoundaryPoints[0]; for (int p = 0; p < storedPointSize - 1; p++) { float tA = curve.normalisedT[p]; float tB = curve.normalisedT[p+1]; int sampleIndexA = p; int sampleIndexB = sampleIndexA + 1; Vector3 pointA = curve.sampledPoints[sampleIndexA]; Vector3 pointB = curve.sampledPoints[sampleIndexB]; float trackWidthA = curve.sampledWidths[sampleIndexA] * 0.5f; float trackWidthB = curve.sampledWidths[sampleIndexB] * 0.5f; float trackCrownA = curve.sampledCrowns[sampleIndexA]; float trackCrownB = curve.sampledCrowns[sampleIndexB]; Vector3 trackUpA = curve.sampledTrackUps[sampleIndexA]; Vector3 trackUpB = curve.sampledTrackUps[sampleIndexB]; Vector3 trackCrossA = curve.sampledTrackCrosses[sampleIndexA]; Vector3 trackCrossB = curve.sampledTrackCrosses[sampleIndexB]; float trackAngle = curve.sampledAngles[sampleIndexA]; if (trackUpA == Vector3.zero || trackUpB == Vector3.zero) return; //TrackBuildRTexture texture = track.Texture(curve.trackTextureStyleIndex) ;// track.trackTexture; int pointANumber = Mathf.Max(Mathf.CeilToInt(trackWidthA / trackMeshRes / 2) * 2, 2);//number of verts along line A int pointBNumber = Mathf.Max(Mathf.CeilToInt(trackWidthB / trackMeshRes / 2) * 2, 2);//number of verts along line B int numberOfNewVerts = pointANumber + pointBNumber; Vector3[] uncrownedVerts = new Vector3[numberOfNewVerts]; if (curve.clipArrayLeft[sampleIndexA]) leftPointA = (pointA + (trackCrossA * -trackWidthA)); if (curve.clipArrayRight[sampleIndexA]) rightPointA = (pointA + (trackCrossA * trackWidthA)); float curveLengthA = (curveLength * tA) / trackWidthA + UVOffset; float curveLengthB = (curveLength * tB) / trackWidthB + UVOffset; float lerpASize = 1.0f / (pointANumber - 1); //track vertex/uv data for point nextNormIndex Vector3[] newAPoints = new Vector3[pointANumber]; Vector3[] newTrackPoints = new Vector3[pointANumber + pointBNumber]; Vector2[] newTrackUVs = new Vector2[pointANumber + pointBNumber]; for (int pa = 0; pa < pointANumber; pa++) { float lerpValue = lerpASize * pa; Vector3 crownVector = Quaternion.LookRotation(trackUpA) * new Vector3(0, 0, Mathf.Sin(lerpValue * Mathf.PI) * trackCrownA); Vector3 uncrownedVert = Vector3.Lerp(leftPointA, rightPointA, lerpValue); uncrownedVerts[pa] = uncrownedVert; Vector3 newVert = uncrownedVert + crownVector; newAPoints[pa] = newVert; newTrackPoints[pa] = newVert; Vector2 newUV = (!trackTextureFlip) ? new Vector2(lerpValue, curveLengthA) : new Vector2(curveLengthA, lerpValue); newTrackUVs[pa] = newUV; } //track vertex/uv data for point prevNormIndex if (curve.clipArrayLeft[sampleIndexB]) leftPointB = (pointB + (trackCrossB * -trackWidthB)); if (curve.clipArrayRight[sampleIndexB]) rightPointB = (pointB + (trackCrossB * trackWidthB)); float lerpBSize = 1.0f / (pointBNumber - 1); Vector3[] newBPoints = new Vector3[pointBNumber]; for (int pb = 0; pb < pointBNumber; pb++) { float lerpValue = lerpBSize * pb; Vector3 crownVector = Quaternion.LookRotation(trackUpB) * new Vector3(0, 0, Mathf.Sin(lerpValue * Mathf.PI) * trackCrownB); Vector3 uncrownedVert = Vector3.Lerp(leftPointB, rightPointB, lerpValue); uncrownedVerts[pb + pointANumber] = uncrownedVert; Vector3 newVert = uncrownedVert + crownVector; newBPoints[pb] = newVert; newTrackPoints[pb + pointANumber] = newVert; Vector2 newUV = (!trackTextureFlip) ? new Vector2(lerpValue, curveLengthB) : new Vector2(curveLengthB, lerpValue); newTrackUVs[pb + pointANumber] = newUV; } int baseTriPointA = 0; int baseTriPointB = pointANumber; int triPointA = baseTriPointA; int triPointB = baseTriPointB; int newTriPointCountA = 1; int newTriPointCountB = 1; int[] newTrackTris = new int[(numberOfNewVerts - 2) * 3]; for (int v = 0; v < numberOfNewVerts - 2; v++) { int newTriPointA = baseTriPointA + newTriPointCountA; int newTriPointB = baseTriPointB + newTriPointCountB; float newTriPointADist, newTriPointBDist; if (newTriPointA >= baseTriPointA + pointANumber) newTriPointADist = float.PositiveInfinity; else newTriPointADist = Vector3.SqrMagnitude(uncrownedVerts[newTriPointA] - uncrownedVerts[baseTriPointA]); if (newTriPointB >= baseTriPointB + pointBNumber) newTriPointBDist = float.PositiveInfinity; else newTriPointBDist = Vector3.SqrMagnitude(uncrownedVerts[newTriPointB] - uncrownedVerts[baseTriPointB]); if (newTriPointADist < newTriPointBDist) { newTrackTris[v * 3] = triPointA; newTrackTris[v * 3 + 1] = triPointB; newTrackTris[v * 3 + 2] = newTriPointA; triPointA = newTriPointA; newTriPointCountA++; } else { newTrackTris[v * 3] = triPointA; newTrackTris[v * 3 + 1] = triPointB; newTrackTris[v * 3 + 2] = newTriPointB; triPointB = newTriPointB; newTriPointCountB++; } } dynamicTrackMesh.AddData(newTrackPoints, newTrackUVs, newTrackTris, 0); dynamicColliderMesh.AddData(newTrackPoints, newTrackUVs, newTrackTris, 0); //Boundary float trackBoundaryWallHeight = curve.boundaryHeight;// track.boundaryHeight; Vector3 leftBoundaryPointA, leftBoundaryPointB, rightBoundaryPointA, rightBoundaryPointB; if (track.disconnectBoundary) { leftBoundaryPointA = curve.sampledLeftBoundaryPoints[sampleIndexA]; leftBoundaryPointB = curve.sampledLeftBoundaryPoints[sampleIndexB]; rightBoundaryPointA = curve.sampledRightBoundaryPoints[sampleIndexA]; rightBoundaryPointB = curve.sampledRightBoundaryPoints[sampleIndexB]; } else { leftBoundaryPointA = leftPointA; leftBoundaryPointB = leftPointB; rightBoundaryPointA = rightPointA; rightBoundaryPointB = rightPointB; } Vector3[] newWallVerts; Vector2[] newWallUVs; int[] newWallTris; //Boundary Render Mesh if(curve.renderBounds) { //LEFT newWallVerts = new[]{leftBoundaryPointA, leftBoundaryPointB, leftBoundaryPointA + trackUpA * trackBoundaryWallHeight, leftBoundaryPointB + trackUpB * trackBoundaryWallHeight}; if(!boundaryTextureFlip) newWallUVs = new[]{new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1),}; else newWallUVs = new[]{new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB),}; newWallTris = new[]{1, 0, 2, 1, 2, 3}; // newWallTris = (boundaryTextureFlip) ? (new[] { 1, 0, 2, 1, 2, 3 }) : (new[] { 0,2,1,2,3,1 }); // newWallTris = (!track.renderBoundaryWallReverse) ? new[] { 1, 0, 2, 1, 2, 3 } : new[] { 1, 0, 2, 1, 2, 3, 0, 1, 2, 2, 1, 3 }; dynamicBoundaryMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if(track.renderBoundaryWallReverse) { newWallTris = new[]{0, 1, 2, 2, 1, 3}; // newWallTris = (boundaryTextureFlip) ? (new[] { 0, 1, 2, 2, 1, 3 }) : (new[] { 0, 2, 1, 2, 3, 1 }); dynamicBoundaryMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } //RIGHT newWallVerts = (new[]{rightBoundaryPointA, rightBoundaryPointB, rightBoundaryPointA + trackUpA * trackBoundaryWallHeight, rightBoundaryPointB + trackUpB * trackBoundaryWallHeight}); //newWallUVs = new[] { new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1), }; if(!boundaryTextureFlip) newWallUVs = new[]{new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1),}; else newWallUVs = new[]{new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB),}; newWallTris = new[]{0, 1, 2, 2, 1, 3}; //newWallTris = (!track.renderBoundaryWallReverse) ? new[] { 0, 1, 2, 2, 1, 3 } : new[] { 1, 0, 2, 1, 2, 3, 0, 1, 2, 2, 1, 3 }; dynamicBoundaryMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if(track.renderBoundaryWallReverse) { newWallTris = new[]{1, 0, 2, 1, 2, 3}; dynamicBoundaryMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } } if(curve.trackCollider) { //COLLIDER walls for on track border float trackColliderWallHeight = track.trackColliderWallHeight; if(curve.colliderSides) { newWallVerts = (new[]{leftBoundaryPointA, leftBoundaryPointB, leftBoundaryPointA + trackUpA * trackColliderWallHeight, leftBoundaryPointB + trackUpB * trackColliderWallHeight}); newWallUVs = (new[]{Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero}); newWallTris = (new[]{1, 0, 2, 1, 2, 3}); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); newWallVerts = (new[]{rightBoundaryPointA, rightBoundaryPointB, rightBoundaryPointA + trackUpA * trackColliderWallHeight, rightBoundaryPointB + trackUpB * trackColliderWallHeight}); newWallUVs = (new[]{Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero}); newWallTris = (new[]{0, 1, 2, 2, 1, 3}); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } //offroad bits if(track.disconnectBoundary) { Vector2 offroadTextureSize = Vector2.one; if(track.numberOfTextures > 0) offroadTextureSize = track.Texture(curve.offroadTextureStyleIndex).textureUnitSize;// track.offroadTexture.textureUnitSize; newWallVerts = (new[]{leftPointA, leftPointB, leftBoundaryPointA, leftBoundaryPointB}); newWallUVs = (new[]{new Vector2(leftPointA.x / offroadTextureSize.x, leftPointA.z / offroadTextureSize.y), new Vector2(leftPointB.x / offroadTextureSize.x, leftPointB.z / offroadTextureSize.y), new Vector2(leftBoundaryPointA.x / offroadTextureSize.x, leftBoundaryPointA.z / offroadTextureSize.y), new Vector2(leftBoundaryPointB.x / offroadTextureSize.x, leftBoundaryPointB.z / offroadTextureSize.y)}); newWallTris = (new[]{1, 0, 2, 1, 2, 3}); dynamicOffroadMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); newWallVerts = (new[]{rightPointA, rightPointB, rightBoundaryPointA, rightBoundaryPointB}); newWallUVs = (new[]{new Vector2(rightPointA.x / offroadTextureSize.x, rightPointA.z / offroadTextureSize.y), new Vector2(rightPointB.x / offroadTextureSize.x, rightPointB.z / offroadTextureSize.y), new Vector2(rightBoundaryPointA.x / offroadTextureSize.x, rightBoundaryPointA.z / offroadTextureSize.y), new Vector2(rightBoundaryPointB.x / offroadTextureSize.x, rightBoundaryPointB.z / offroadTextureSize.y)}); newWallTris = (new[]{0, 1, 2, 2, 1, 3}); dynamicOffroadMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); newWallVerts = (new[]{leftPointA, leftPointB, leftBoundaryPointA, leftBoundaryPointB}); newWallUVs = (new[]{Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero}); newWallTris = (new[]{1, 0, 2, 1, 2, 3}); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); newWallVerts = (new[]{rightPointA, rightPointB, rightBoundaryPointA, rightBoundaryPointB}); newWallUVs = (new[]{Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero}); newWallTris = (new[]{0, 1, 2, 2, 1, 3}); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } if(track.includeColliderRoof) { newWallVerts = (new[]{leftBoundaryPointA + trackUpA * trackColliderWallHeight, leftBoundaryPointB + trackUpB * trackColliderWallHeight, rightBoundaryPointA + trackUpA * trackColliderWallHeight, rightBoundaryPointB + trackUpB * trackColliderWallHeight}); newWallUVs = (new[]{Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero}); newWallTris = (new[]{1, 0, 2, 1, 2, 3}); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } } if ((track.trackBumpers && curve.generateBumpers) || curve.generateBumpers) { float bumperWidth = track.bumperWidth; float bumperHeight = track.bumperHeight; Vector3 bumperRaisedA = trackUpA * bumperHeight; Vector3 bumperRaisedB = trackUpB * bumperHeight; float trackAngleThreashold = track.bumperAngleThresold; //left bumpers if (trackAngle >= trackAngleThreashold) { Vector3 offroadEdgeDirectionA = (leftBoundaryPointA - leftPointA).normalized; Vector3 trackEdgeDirectionA = (newAPoints[1] - newAPoints[0]).normalized; Vector3 bumperDirectionA = (Vector3.Project(offroadEdgeDirectionA, trackUpA) - trackEdgeDirectionA).normalized; Vector3 offroadEdgeDirectionB = (leftBoundaryPointB - leftPointB).normalized; Vector3 trackEdgeDirectionB = (newBPoints[1] - newBPoints[0]).normalized; Vector3 bumperDirectionB = (Vector3.Project(offroadEdgeDirectionB, trackUpB) - trackEdgeDirectionB).normalized; float trackEdgeA = Vector3.Distance(pointA, leftPointA); float offroadEdgeA = Vector3.Distance(pointA, leftBoundaryPointA); bool offroadBumper = (trackEdgeA < (offroadEdgeA - bumperWidth)); Vector3 bumperLeft0 = (offroadBumper ? leftPointA + bumperDirectionA * bumperWidth : leftBoundaryPointA) + bumperRaisedA; Vector3 bumperLeft1 = (offroadBumper ? leftPointA : bumperLeft0 - (bumperDirectionA * bumperWidth) - bumperRaisedB);//bumperLeft0 + (trackEdgeDirectionA * bumperWidth)) - bumperRaisedB; Vector3 bumperLeft2 = (offroadBumper ? leftPointB + bumperDirectionB * bumperWidth : leftBoundaryPointB) + bumperRaisedB; Vector3 bumperLeft3 = (offroadBumper ? leftPointB : bumperLeft2 - (bumperDirectionB * bumperWidth) - bumperRaisedB); float bumperSegmentDistanceA = Vector3.Distance(bumperLeft0, bumperLeft2); float uvStartA, uvEndA; if (track.numberOfTextures > 0) { uvStartA = bumperDistanceA / track.Texture(curve.bumperTextureStyleIndex).textureUnitSize.y;// track.bumperTexture.textureUnitSize.y; uvEndA = (bumperDistanceA + bumperSegmentDistanceA) / track.Texture(curve.bumperTextureStyleIndex).textureUnitSize.y;// track.bumperTexture.textureUnitSize.y; } else { uvStartA = bumperDistanceA;// track.bumperTexture.textureUnitSize.y; uvEndA = (bumperDistanceA + bumperSegmentDistanceA);// track.bumperTexture.textureUnitSize.y; } newWallVerts = (new[] { bumperLeft0, bumperLeft1, bumperLeft2, bumperLeft3 }); if (!bumperTextureFlip) newWallUVs = (new[] { new Vector2(uvStartA, 1), new Vector2(uvStartA, 0), new Vector2(uvEndA, 1), new Vector2(uvEndA, 0) }); else newWallUVs = (new[] { new Vector2(1, uvStartA), new Vector2(0, uvStartA), new Vector2(1, uvEndA), new Vector2(0, uvEndA) }); newWallTris = (new[] { 1, 0, 2, 1, 2, 3 }); dynamicBumperMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); bumperDistanceA += bumperSegmentDistanceA; newWallVerts = (new[] { bumperLeft0, bumperLeft1, bumperLeft2, bumperLeft3 }); newWallUVs = (new[] { Vector2.zero, Vector2.zero, Vector2.zero, Vector2.zero }); newWallTris = (new[] { 1, 0, 2, 1, 2, 3 }); dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } //Right bumpers if (trackAngle < -trackAngleThreashold) { Vector3 trackEdgeDirectionA = (newAPoints[pointANumber - 2] - newAPoints[pointANumber - 1]).normalized; Vector3 trackEdgeDirectionB = (newBPoints[pointBNumber - 2] - newBPoints[pointBNumber - 1]).normalized; Vector3 bumperRight0 = ((Vector3.Distance(pointA, rightPointA) < (Vector3.Distance(pointA, rightBoundaryPointA) - bumperWidth)) ? rightPointA : rightBoundaryPointA) + bumperRaisedA; Vector3 bumperRight1 = bumperRight0 + (trackEdgeDirectionA * bumperWidth); Vector3 bumperRight2 = ((Vector3.Distance(pointB, rightPointB) < (Vector3.Distance(pointB, rightBoundaryPointB) - bumperWidth)) ? rightPointB : rightBoundaryPointB) + bumperRaisedB; Vector3 bumperRight3 = bumperRight2 + (trackEdgeDirectionB * bumperWidth); float bumperSegmentDistanceB = Vector3.Distance(bumperRight0, bumperRight2); //float bumperSegmentDistanceA = Vector3.Distance(bumperLeft0, bumperLeft2); float uvStartB, uvEndB; if (track.numberOfTextures > 0) { uvStartB = bumperDistanceB / track.Texture(curve.bumperTextureStyleIndex).textureUnitSize.y;// track.bumperTexture.textureUnitSize.y; uvEndB = (bumperDistanceB + bumperSegmentDistanceB) / track.Texture(curve.bumperTextureStyleIndex).textureUnitSize.y;// track.bumperTexture.textureUnitSize.y; } else { uvStartB = bumperDistanceB; uvEndB = (bumperDistanceB + bumperSegmentDistanceB); } newWallVerts = (new[] { bumperRight0, bumperRight1, bumperRight2, bumperRight3 }); if (!bumperTextureFlip) newWallUVs = (new[] { new Vector2(uvStartB, 1), new Vector2(uvStartB, 0), new Vector2(uvEndB, 1), new Vector2(uvEndB, 0) }); else newWallUVs = (new[] { new Vector2(1, uvStartB), new Vector2(0, uvStartB), new Vector2(1, uvEndB), new Vector2(0, uvEndB) }); // newWallTris = (new[] { 1, 0, 2, 1, 2, 3 }); newWallTris = (new[]{0, 1, 2, 1, 3, 2}); dynamicBumperMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); bumperDistanceB += bumperSegmentDistanceB; } } //Track Bottom Mesh if (curve.extrudeTrack || curve.extrudeTrackBottom) { float extrusionLength = curve.extrudeLength; Vector3 extrusionA = -trackUpA * extrusionLength; Vector3 extrusionB = -trackUpB * extrusionLength; Vector3 pl0 = leftBoundaryPointA; Vector3 pl1 = leftBoundaryPointB; Vector3 pl2 = leftBoundaryPointA + extrusionA; Vector3 pl3 = leftBoundaryPointB + extrusionB; Vector3 pr0 = rightBoundaryPointA; Vector3 pr1 = rightBoundaryPointB; Vector3 pr2 = rightBoundaryPointA + extrusionA; Vector3 pr3 = rightBoundaryPointB + extrusionB; float bevelLerp = 0.5f - curve.extrudeBevel * 0.3333f; Vector3 bevelOutA = trackCrossA.normalized * (trackWidthA*0.5f); Vector3 bevelOutB = trackCrossB.normalized * (trackWidthB*0.5f); Vector3 pl2b = Vector3.Lerp(pl2 - bevelOutA, pr2 + bevelOutA, bevelLerp); Vector3 pl3b = Vector3.Lerp(pl3 - bevelOutB, pr3 + bevelOutB, bevelLerp); Vector3 pr2b = Vector3.Lerp(pr2 + bevelOutA, pl2 - bevelOutA, bevelLerp); Vector3 pr3b = Vector3.Lerp(pr3 + bevelOutB, pl3 - bevelOutB, bevelLerp); if(curve.extrudeTrack) { //LEFT newWallVerts = new[]{pl0, pl1, pl2b, pl3b}; if(!bottomTextureFlip) newWallUVs = new[]{new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1),}; else newWallUVs = new[]{new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB),}; newWallTris = new[]{1, 0, 2, 1, 2, 3}; dynamicBottomMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if(curve.trackCollider) dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); //RIGHT newWallVerts = (new[]{pr0, pr1, pr2b, pr3b}); if(!bottomTextureFlip) newWallUVs = new[]{new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1),}; else newWallUVs = new[]{new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB),}; newWallTris = new[]{0, 1, 2, 2, 1, 3}; dynamicBottomMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if(curve.trackCollider) dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if(curve.extrudeCurveEnd) { //Ends if(p == 0) { newWallVerts = (new[] { pl0, pl2b, pr0, pr2b}); if (!bottomTextureFlip) newWallUVs = new[] { new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1), }; else newWallUVs = new[] { new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB), }; newWallTris = new[] { 1, 0, 2, 1, 2, 3 }; dynamicBottomMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if (curve.trackCollider) dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } if (p == storedPointSize-2) { newWallVerts = (new[] { pl1, pl3b, pr1, pr3b }); if (!bottomTextureFlip) newWallUVs = new[] { new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1), }; else newWallUVs = new[] { new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB), }; newWallTris = new[]{0, 1, 2, 2, 1, 3}; dynamicBottomMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if (curve.trackCollider) dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } } } if (curve.extrudeTrackBottom) { if(!curve.extrudeTrack) newWallVerts = new[] { pl0, pl1, pr0, pr1 }; else newWallVerts = new[] { pl2b, pl3b, pr2b, pr3b }; if (!bottomTextureFlip) newWallUVs = new[] { new Vector2(curveLengthA, 0), new Vector2(curveLengthB, 0), new Vector2(curveLengthA, 1), new Vector2(curveLengthB, 1), }; else newWallUVs = new[] { new Vector2(1, curveLengthA), new Vector2(1, curveLengthB), new Vector2(0, curveLengthA), new Vector2(0, curveLengthB), }; newWallTris = new[] { 1, 0, 2, 1, 2, 3 }; dynamicBottomMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); if (curve.trackCollider) dynamicColliderMesh.AddData(newWallVerts, newWallUVs, newWallTris, 0); } } if (p == storedPointSize - 2) UVOffset = curveLengthB; } if (curve.holder != null) DestroyImmediate(curve.holder); GameObject newCurveMeshHolder = new GameObject("curve " + (i + 1)); newCurveMeshHolder.transform.parent = transform; newCurveMeshHolder.transform.localPosition = Vector3.zero; curve.holder = newCurveMeshHolder; int numberOfMeshes; if (!dynamicTrackMesh.isEmpty) { dynamicTrackMesh.name = "Curve " + i + " Track Mesh"; dynamicTrackMesh.Build(); numberOfMeshes = dynamicTrackMesh.meshCount; for(int m = 0; m < numberOfMeshes; m++) { GameObject newMeshHolder = new GameObject("model " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshFilter>().sharedMesh = dynamicTrackMesh[m].mesh; if(track.numberOfTextures > 0) newMeshHolder.AddComponent<MeshRenderer>().material = track.Texture(curve.trackTextureStyleIndex).GetMaterial();// track.trackTexture.material; #if UNITY_EDITOR EditorUtility.SetSelectedWireframeHidden(newMeshHolder.renderer, !track.showWireframe); #endif } } if (!dynamicBoundaryMesh.isEmpty) { dynamicBoundaryMesh.Build(); numberOfMeshes = dynamicBoundaryMesh.meshCount; for(int m = 0; m < numberOfMeshes; m++) { GameObject newMeshHolder = new GameObject("boundary " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshFilter>().sharedMesh = dynamicBoundaryMesh[m].mesh; if(track.numberOfTextures > 0) newMeshHolder.AddComponent<MeshRenderer>().material = track.Texture(curve.boundaryTextureStyleIndex).GetMaterial();// track.trackTexture.material; #if UNITY_EDITOR EditorUtility.SetSelectedWireframeHidden(newMeshHolder.renderer, !track.showWireframe); #endif } } if (track.disconnectBoundary && !dynamicOffroadMesh.isEmpty) { dynamicOffroadMesh.Build(); numberOfMeshes = dynamicOffroadMesh.meshCount; for (int m = 0; m < numberOfMeshes; m++) { GameObject newMeshHolder = new GameObject("offroad " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshFilter>().sharedMesh = dynamicOffroadMesh[m].mesh; if (track.numberOfTextures > 0) newMeshHolder.AddComponent<MeshRenderer>().material = track.Texture(curve.offroadTextureStyleIndex).GetMaterial();// track.offroadTexture.material; #if UNITY_EDITOR EditorUtility.SetSelectedWireframeHidden(newMeshHolder.renderer, !track.showWireframe); #endif } } if (track.includeCollider && curve.trackCollider && !dynamicColliderMesh.isEmpty) { dynamicColliderMesh.Build(); int numberOfColliderMeshes = dynamicColliderMesh.meshCount; for (int m = 0; m < numberOfColliderMeshes; m++) { GameObject newMeshHolder = new GameObject("trackCollider " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshCollider>().sharedMesh = dynamicColliderMesh[m].mesh; } } if (track.trackBumpers && !dynamicBumperMesh.isEmpty) { dynamicBumperMesh.Build(); numberOfMeshes = dynamicBumperMesh.meshCount; for (int m = 0; m < numberOfMeshes; m++) { GameObject newMeshHolder = new GameObject("bumper " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshFilter>().sharedMesh = dynamicBumperMesh[m].mesh; if (track.numberOfTextures > 0) newMeshHolder.AddComponent<MeshRenderer>().material = track.Texture(curve.bumperTextureStyleIndex).GetMaterial();// track.bumperTexture.material; #if UNITY_EDITOR EditorUtility.SetSelectedWireframeHidden(newMeshHolder.renderer, !track.showWireframe); #endif } } if (!dynamicBottomMesh.isEmpty) { dynamicBottomMesh.Build(); numberOfMeshes = dynamicBottomMesh.meshCount; for(int m = 0; m < numberOfMeshes; m++) { GameObject newMeshHolder = new GameObject("bottom " + (m + 1)); newMeshHolder.transform.parent = curve.holder.transform; newMeshHolder.transform.localPosition = Vector3.zero; newMeshHolder.AddComponent<MeshFilter>().sharedMesh = dynamicBottomMesh[m].mesh; if(track.numberOfTextures > 0) newMeshHolder.AddComponent<MeshRenderer>().material = track.Texture(curve.bottomTextureStyleIndex).GetMaterial();// track.trackTexture.material; #if UNITY_EDITOR EditorUtility.SetSelectedWireframeHidden(newMeshHolder.renderer, !track.showWireframe); #endif } } } else { if (curve.holder != null && (!curve.render || !renderTrack)) DestroyImmediate(curve.holder); } polyCount += dynamicBottomMesh.triangleCount / 3; polyCount += dynamicBoundaryMesh.triangleCount / 3; polyCount += dynamicBumperMesh.triangleCount / 3; polyCount += dynamicOffroadMesh.triangleCount / 3; polyCount += dynamicTrackMesh.triangleCount / 3; } track.TrackRendered(); track.lastPolycount = polyCount; #if UNITY_EDITOR EditorUtility.UnloadUnusedAssets(); #endif } private Vector2 CalculateUV(int i, int pointNumber, float UVy) { Vector2 returnUV = Vector2.zero; if (pointNumber == 2) { float lerpASize = 1.0f / (pointNumber - 1); float lerpValue = lerpASize * i; returnUV = (new Vector2(lerpValue, UVy)); } else { if (i == 0) { returnUV = (new Vector2(0.0f, UVy)); } else if (i == 1) { returnUV = (new Vector2(0.333f, UVy)); } else if (i == pointNumber - 2) { returnUV = (new Vector2(0.666f, UVy)); } else if (i == pointNumber - 1) { returnUV = (new Vector2(1.0f, UVy)); } else { returnUV = (new Vector2(0.333f + 0.333f * (1 - (i % 2)), UVy)); } } return returnUV; } private float SignedAngle(Vector3 from, Vector3 to, Vector3 up) { Vector3 direction = (to - from).normalized; Vector3 cross = Vector3.Cross(up, direction); float dot = Vector3.Dot(from, cross); return Vector3.Angle(from, to) * Mathf.Sign(dot); } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // 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.Reflection; using System.Globalization; using NUnit.Common; using NUnit.Options; using NUnit.Framework; namespace NUnitLite.Tests { using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.TestUtilities; [TestFixture] public class CommandLineTests { #region Argument PreProcessor Tests [TestCase("--arg", "--arg")] [TestCase("--ArG", "--ArG")] [TestCase("--arg1 --arg2", "--arg1", "--arg2")] [TestCase("--arg1 data --arg2", "--arg1", "data", "--arg2")] [TestCase("")] [TestCase(" ")] [TestCase("\"--arg 1\" --arg2", "--arg 1", "--arg2")] [TestCase("--arg1 \"--arg 2\"", "--arg1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\"", "--arg 1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("--arg1 \"--arg 2\" arg3 \"arg 4\"", "--arg1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\" \"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg\"", "--arg")] [TestCase("\"--arg 1\"", "--arg 1")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\" --arg abc \"", " --arg abc ")] [TestCase("\"--arg=abc\"", "--arg=abc")] [TestCase("\"--arg=aBc\"", "--arg=aBc")] [TestCase("\"--arg = abc\"", "--arg = abc")] [TestCase("\"--arg=abc,xyz\"", "--arg=abc,xyz")] [TestCase("\"--arg=abc, xyz\"", "--arg=abc, xyz")] [TestCase("\"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz\"", "@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz")] public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs) { var actualArgs = CommandLineOptions.GetArgs(cmdline); Assert.AreEqual(expectedArgs, actualArgs); } [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1\r\n--filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 data", "--arg1", "--filearg1", "data", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes\"", "--arg1", "--filearg1", "data in quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with 'single' quotes\"", "--arg1", "--filearg1", "data in quotes with 'single' quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with /slashes/\"", "--arg1", "--filearg1", "data in quotes with /slashes/", "--arg2")] [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:", "--arg1", "--arg2")] // Blank lines [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n\n\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n \n\t\t\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n\r\n\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n \r\n\t\t\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2\r\n\n--filearg3 --filearg4", "--arg1", "--filearg1", "--filearg2", "--filearg3", "--filearg4", "--arg2")] // Comments [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\nThis is NOT treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "This", "is", "NOT", "treated", "as", "a", "COMMENT", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n#This is treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] // Nested files [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3 @file3.txt,file3.txt:--filearg4", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3", "--filearg4")] // Where clauses [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test==somelongname", "testfile.dll", "--where", "test==somelongname", "--arg2")] // NOTE: The next is not valid. Where clause is spread over several args and therefore won't parse. Quotes are required. [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test == somelongname", "testfile.dll", "--where", "test", "==", "somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or test == /another long name/ or cat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or\ntest == /another long name/ or\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname ||\ntest == /another long name/ ||\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname || test == /another long name/ || cat == SomeCategory", "--arg2")] public void GetArgsFromFiles(string commandLine, string files, params string[] expectedArgs) { var filespecs = files.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var testFiles = new TestFile[filespecs.Length]; for (int ix = 0; ix < filespecs.Length; ++ix) { var filespec = filespecs[ix]; var split = filespec.IndexOf( ':' ); if (split < 0) throw new Exception("Invalid test data"); var fileName = filespec.Substring(0, split); var fileContent = filespec.Substring(split + 1); testFiles[ix] = new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, fileName), fileContent, true); } var options = new NUnitLiteOptions(); string[] expandedArgs; try { expandedArgs = options.PreParse(CommandLineOptions.GetArgs(commandLine)).ToArray(); } finally { foreach (var tf in testFiles) tf.Dispose(); } Assert.AreEqual(expectedArgs, expandedArgs); Assert.Zero(options.ErrorMessages.Count); } [TestCase("--arg1 @file1.txt --arg2", "The file \"file1.txt\" was not found.")] [TestCase("--arg1 @ --arg2", "You must include a file name after @.")] public void GetArgsFromFiles_FailureTests(string args, string errorMessage) { var options = new NUnitLiteOptions(); options.PreParse(CommandLineOptions.GetArgs(args)); Assert.That(options.ErrorMessages, Is.EqualTo(new object[] { errorMessage })); } //[Test] public void GetArgsFromFiles_NestingOverflow() { var options = new NUnitLiteOptions(); var args = new[] { "--arg1", "@file1.txt", "--arg2" }; var expectedErrors = new string[] { "@ nesting exceeds maximum depth of 3." }; using (new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "file1.txt"), "@file1.txt", true)) { var expandedArgs = options.PreParse(args); Assert.AreEqual(args, expandedArgs); Assert.AreEqual(expectedErrors, options.ErrorMessages); } } #endregion #region General Tests [Test] public void NoInputFiles() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.Null(options.InputFile); } [TestCase("ShowHelp", "help|h")] [TestCase("ShowVersion", "version|V")] [TestCase("StopOnError", "stoponerror")] [TestCase("WaitBeforeExit", "wait")] [TestCase("NoHeader", "noheader|noh")] [TestCase("TeamCity", "teamcity")] public void CanRecognizeBooleanOptions(string propertyName, string pattern) { Console.WriteLine("Testing " + propertyName); string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName); NUnitLiteOptions options; foreach (string option in prototypes) { if (option.Length == 1) { options = new NUnitLiteOptions("-" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option); } else { options = new NUnitLiteOptions("--" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option); } options = new NUnitLiteOptions("/" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option); } } [TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])] [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "Before", "After", "All" }, new string[] { "JUNK" })] [TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])] [TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])] [TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })] public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string option in prototypes) { foreach (string value in goodValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } foreach (string value in badValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue); } } } [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })] public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues) { PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string canonicalValue in canonicalValues) { string lowercaseValue = canonicalValue.ToLowerInvariant(); string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } } #if !NETCOREAPP1_1 [TestCase("DefaultTimeout", "timeout")] #endif [TestCase("RandomSeed", "seed")] #if PARALLEL [TestCase("NumberOfTestWorkers", "workers")] #endif public void CanRecognizeIntOptions(string propertyName, string pattern) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(int), property.PropertyType); foreach (string option in prototypes) { var options = new NUnitLiteOptions("--" + option + ":42"); Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text"); } } // [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))] // public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType) // { // string[] prototypes = pattern.Split('|'); // PropertyInfo property = GetPropertyInfo(propertyName); // Assert.IsNotNull(property, "Property {0} not found", propertyName); // Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName); // Assert.AreEqual(enumType, property.PropertyType); // foreach (string option in prototypes) // { // foreach (string name in Enum.GetNames(enumType)) // { // { // ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name); // Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name); // } // } // } // } [TestCase("--where")] [TestCase("--output")] [TestCase("--err")] [TestCase("--work")] [TestCase("--trace")] #if !NETCOREAPP1_1 [TestCase("--timeout")] #endif public void MissingValuesAreReported(string option) { var options = new NUnitLiteOptions(option + "="); Assert.False(options.Validate(), "Missing value should not be valid"); Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]); } [Test] public void AssemblyIsInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); } [Test] public void MultipleAssembliesAreInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); Assert.That(options.ErrorMessages[1], Contains.Substring("Invalid entry: another.dll")); } [Test] public void AssemblyIsValidIfAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); } [Test] public void MultipleAssembliesAreInvalidEvenIfOneIsAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: another.dll")); } [Test] public void InvalidOption() { var options = new NUnitLiteOptions("-asembly:nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]); } [Test] public void InvalidCommandLineParms() { var options = new NUnitLiteOptions("-garbage:TestFixture", "-assembly:Tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]); Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]); } #endregion #region Timeout Option [Test] public void TimeoutIsMinusOneIfNoOptionIsProvided() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #if !NETCOREAPP1_1 [Test] public void TimeoutThrowsExceptionIfOptionHasNoValue() { Assert.Throws<OptionException>(() => new NUnitLiteOptions("-timeout")); } [Test] public void TimeoutParsesIntValueCorrectly() { var options = new NUnitLiteOptions("-timeout:5000"); Assert.True(options.Validate()); Assert.AreEqual(5000, options.DefaultTimeout); } [Test] public void TimeoutCausesErrorIfValueIsNotInteger() { var options = new NUnitLiteOptions("-timeout:abc"); Assert.False(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #endif #endregion #region EngineResult Option [Test] public void FileNameWithoutResultOptionLooksLikeParameter() { var options = new NUnitLiteOptions(true, "results.xml"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); //Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: results.xml")); Assert.AreEqual("results.xml", options.InputFile); } [Test] public void ResultOptionWithFilePath() { var options = new NUnitLiteOptions("-result:results.xml"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ResultOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-result:results.xml;format=nunit2"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit2", spec.Format); } [Test] public void ResultOptionWithoutFileNameIsInvalid() { var options = new NUnitLiteOptions("-result:"); Assert.False(options.Validate(), "Should not be valid"); Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected"); } [Test] public void ResultOptionMayBeRepeated() { var options = new NUnitLiteOptions("-result:results.xml", "-result:nunit2results.xml;format=nunit2"); Assert.True(options.Validate(), "Should be valid"); var specs = options.ResultOutputSpecifications; Assert.That(specs, Has.Count.EqualTo(2)); var spec1 = specs[0]; Assert.AreEqual("results.xml", spec1.OutputPath); Assert.AreEqual("nunit3", spec1.Format); var spec2 = specs[1]; Assert.AreEqual("nunit2results.xml", spec2.OutputPath); Assert.AreEqual("nunit2", spec2.Format); } [Test] public void DefaultResultSpecification() { var options = new NUnitLiteOptions(); Assert.AreEqual(1, options.ResultOutputSpecifications.Count); var spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("TestResult.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void NoResultSuppressesDefaultResultSpecification() { var options = new NUnitLiteOptions("-noresult"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void NoResultSuppressesAllResultSpecifications() { var options = new NUnitLiteOptions("-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void InvalidResultSpecRecordsError() { var options = new NUnitLiteOptions("test.dll", "-result:userspecifed.xml;format=nunit2;format=nunit3"); Assert.That(options.ResultOutputSpecifications, Has.Exactly(1).Items .And.Exactly(1).Property(nameof(OutputSpecification.OutputPath)).EqualTo("TestResult.xml")); Assert.That(options.ErrorMessages, Has.Exactly(1).Contains("invalid output spec").IgnoreCase); } #endregion #region Explore Option [Test] public void ExploreOptionWithoutPath() { var options = new NUnitLiteOptions("-explore"); Assert.True(options.Validate()); Assert.True(options.Explore); } [Test] public void ExploreOptionWithFilePath() { var options = new NUnitLiteOptions("-explore:results.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ExploreOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-explore:results.xml;format=cases"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("cases", spec.Format); } [Test] public void ExploreOptionWithFilePathUsingEqualSign() { var options = new NUnitLiteOptions("-explore=C:/nunit/tests/bin/Debug/console-test.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath); } [TestCase(true, null, true)] [TestCase(false, null, false)] [TestCase(true, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(false, true, true)] public void ShouldSetTeamCityFlagAccordingToArgsAndDefaults(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity) { // Given List<string> args = new List<string> { "tests.dll" }; if (hasTeamcityInCmd) { args.Add("--teamcity"); } CommandLineOptions options; if (defaultTeamcity.HasValue) { options = new NUnitLiteOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray()); } else { options = new NUnitLiteOptions(args.ToArray()); } // When var actualTeamCity = options.TeamCity; // Then Assert.AreEqual(actualTeamCity, expectedTeamCity); } #endregion #region Test Parameters [Test] public void SingleTestParameter() { var options = new NUnitLiteOptions("--params=X=5"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { {"X", "5" } })); } [Test] public void TwoTestParametersInOneOption() { var options = new NUnitLiteOptions("--params:X=5;Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void TwoTestParametersInSeparateOptions() { var options = new NUnitLiteOptions("-p:X=5", "-p:Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void ThreeTestParametersInTwoOptions() { var options = new NUnitLiteOptions("--params:X=5;Y=7", "-p:Z=3"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" }, { "Z", "3" } })); } [Test] public void ParameterWithoutEqualSignIsInvalid() { var options = new NUnitLiteOptions("--params=X5"); Assert.That(options.ErrorMessages.Count, Is.EqualTo(1)); } [Test] public void DisplayTestParameters() { if (TestContext.Parameters.Count == 0) { Console.WriteLine("No Test Parameters were passed"); return; } Console.WriteLine("Test Parameters---"); foreach (var name in TestContext.Parameters.Names) Console.WriteLine(" Name: {0} Value: {1}", name, TestContext.Parameters[name]); } #endregion #region Helper Methods //private static FieldInfo GetFieldInfo(string fieldName) //{ // FieldInfo field = typeof(NUnitLiteOptions).GetField(fieldName); // Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName); // return field; //} private static PropertyInfo GetPropertyInfo(string propertyName) { PropertyInfo property = typeof(NUnitLiteOptions).GetProperty(propertyName); Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName); return property; } #endregion internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider { public DefaultOptionsProviderStub(bool teamCity) { TeamCity = teamCity; } public bool TeamCity { get; private set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Reflection.Runtime.TypeInfos; using Internal.Reflection.Core.Execution; using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType; namespace System.Reflection.Runtime.BindingFlagSupport { // // Stores the result of a member filtering that's filtered by name and visibility from base class (as defined by the Type.Get*() family of apis). // // The results are as if you'd passed in a bindingFlags value of "Public | NonPublic | Instance | Static | FlattenHierarchy" // In addition, if "ignoreCase" was passed to Create(), BindingFlags.IgnoreCase is also in effect. // // Results are sorted by declaring type. The members declared by the most derived type appear first, then those declared by his base class, and so on. // The Disambiguation logic takes advantage of this. // // This object is a good candidate for long term caching. // // QueryMemberList's come in two flavors: ImmediateTypeOnly and full. The immediateTypeOnly only holds the results for one type, not any of its // base types. This is used when the binding flags passed to a Get() api limit the search to the immediate type only in order to avoid triggering // unnecessary Resolving events and a lot of unnecessary ParameterInfo creation and comparison checks. // internal sealed class QueriedMemberList<M> where M : MemberInfo { private QueriedMemberList(bool immediateTypeOnly) { _members = new M[Grow]; _allFlagsThatMustMatch = new BindingFlags[Grow]; ImmediateTypeOnly = immediateTypeOnly; } private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowsing) { _totalCount = totalCount; _declaredOnlyCount = declaredOnlyCount; _members = members; _allFlagsThatMustMatch = allFlagsThatMustMatch; _typeThatBlockedBrowsing = typeThatBlockedBrowsing; } /// <summary> /// Returns the # of candidates for a non-DeclaredOnly search. Caution: Can throw MissingMetadataException. Use DeclaredOnlyCount if you don't want to search base classes. /// </summary> public int TotalCount { get { if (_typeThatBlockedBrowsing != null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(_typeThatBlockedBrowsing); return _totalCount; } } /// <summary> /// Returns the # of candidates for a DeclaredOnly search /// </summary> public int DeclaredOnlyCount => _declaredOnlyCount; public bool ImmediateTypeOnly { get; } public M this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert(index >= 0 && index < _totalCount); return _members[index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Matches(int index, BindingFlags bindingAttr) { Debug.Assert(index >= 0 && index < _totalCount); BindingFlags allFlagsThatMustMatch = _allFlagsThatMustMatch[index]; return ((bindingAttr & allFlagsThatMustMatch) == allFlagsThatMustMatch); } public QueriedMemberList<M> Filter(Func<M, bool> predicate) { BindingFlags[] newAllFlagsThatMustMatch = new BindingFlags[_totalCount]; M[] newMembers = new M[_totalCount]; int newDeclaredOnlyCount = 0; int newTotalCount = 0; for (int i = 0; i < _totalCount; i++) { M member = _members[i]; if (predicate(member)) { newMembers[newTotalCount] = member; newAllFlagsThatMustMatch[newTotalCount] = _allFlagsThatMustMatch[i]; newTotalCount++; if (i < _declaredOnlyCount) newDeclaredOnlyCount++; } } return new QueriedMemberList<M>(newTotalCount, newDeclaredOnlyCount, newMembers, newAllFlagsThatMustMatch, _typeThatBlockedBrowsing); } // // Filter by name and visibility from the ReflectedType. // public static QueriedMemberList<M> Create(RuntimeTypeInfo type, string filter, bool ignoreCase, bool immediateTypeOnly) { RuntimeTypeInfo reflectedType = type; MemberPolicies<M> policies = MemberPolicies<M>.Default; NameFilter nameFilter; if (filter == null) nameFilter = null; else if (ignoreCase) nameFilter = new NameFilterCaseInsensitive(filter); else nameFilter = new NameFilterCaseSensitive(filter); bool inBaseClass = false; QueriedMemberList<M> queriedMembers = new QueriedMemberList<M>(immediateTypeOnly); while (type != null) { int numCandidatesInDerivedTypes = queriedMembers._totalCount; foreach (M member in policies.CoreGetDeclaredMembers(type, nameFilter, reflectedType)) { MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); if (inBaseClass && visibility == MethodAttributes.Private) continue; if (numCandidatesInDerivedTypes != 0 && policies.IsSuppressedByMoreDerivedMember(member, queriedMembers._members, startIndex: 0, endIndex: numCandidatesInDerivedTypes)) continue; BindingFlags allFlagsThatMustMatch = default(BindingFlags); allFlagsThatMustMatch |= (isStatic ? BindingFlags.Static : BindingFlags.Instance); if (isStatic && inBaseClass) allFlagsThatMustMatch |= BindingFlags.FlattenHierarchy; allFlagsThatMustMatch |= ((visibility == MethodAttributes.Public) ? BindingFlags.Public : BindingFlags.NonPublic); queriedMembers.Add(member, allFlagsThatMustMatch); } if (!inBaseClass) { queriedMembers._declaredOnlyCount = queriedMembers._totalCount; if (immediateTypeOnly) break; if (policies.AlwaysTreatAsDeclaredOnly) break; inBaseClass = true; } type = type.BaseType.CastToRuntimeTypeInfo(); if (type != null && !type.CanBrowseWithoutMissingMetadataExceptions()) { // If we got here, one of the base classes is missing metadata. We don't want to throw a MissingMetadataException now because we may be // building a cached result for a caller who passed BindingFlags.DeclaredOnly. So we'll mark the results in a way that // it will throw a MissingMetadataException if a caller attempts to iterate past the declared-only subset. queriedMembers._typeThatBlockedBrowsing = type; queriedMembers._totalCount = queriedMembers._declaredOnlyCount; break; } } return queriedMembers; } public void Compact() { Array.Resize(ref _members, _totalCount); Array.Resize(ref _allFlagsThatMustMatch, _totalCount); } private void Add(M member, BindingFlags allFlagsThatMustMatch) { const BindingFlags validBits = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; Debug.Assert((allFlagsThatMustMatch & ~validBits) == 0); Debug.Assert(((allFlagsThatMustMatch & BindingFlags.Public) == 0) != ((allFlagsThatMustMatch & BindingFlags.NonPublic) == 0)); Debug.Assert(((allFlagsThatMustMatch & BindingFlags.Instance) == 0) != ((allFlagsThatMustMatch & BindingFlags.Static) == 0)); Debug.Assert((allFlagsThatMustMatch & BindingFlags.FlattenHierarchy) == 0 || (allFlagsThatMustMatch & BindingFlags.Static) != 0); int count = _totalCount; if (count == _members.Length) { Array.Resize(ref _members, count + Grow); Array.Resize(ref _allFlagsThatMustMatch, count + Grow); } _members[count] = member; _allFlagsThatMustMatch[count] = allFlagsThatMustMatch; _totalCount++; } private int _totalCount; // # of entries including members in base classes. private int _declaredOnlyCount; // # of entries for members only in the most derived class. private M[] _members; // Length is equal to or greater than _totalCount. Entries beyond _totalCount contain null or garbage and should be read. private BindingFlags[] _allFlagsThatMustMatch; // Length will be equal to _members.Length private RuntimeTypeInfo _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata. private const int Grow = 64; } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : mpegheader.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Ogg { public class PageHeader { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private bool is_valid; private ArrayList packet_sizes; private bool first_packet_continued; private bool last_packet_completed; private bool first_page_of_stream; private bool last_page_of_stream; private long absolute_granular_position; private uint stream_serial_number; private int page_sequence_number; private int size; private int data_size; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public PageHeader (File file, long page_offset) { is_valid = false; packet_sizes = new ArrayList (); first_packet_continued = false; last_packet_completed = false; first_page_of_stream = false; last_page_of_stream = false; absolute_granular_position = 0; stream_serial_number = 0; page_sequence_number = -1; size = 0; data_size = 0; if (file != null && page_offset >= 0) Read (file, page_offset); } public PageHeader () : this (null, -1) { } public ByteVector Render () { ByteVector data = new ByteVector (); // capture patern data.Add ("OggS"); // stream structure version data.Add ((byte) 0); // header type flag byte flags = 0; if (first_packet_continued) flags |= 1; if (page_sequence_number == 0) flags |= 2; if (last_page_of_stream) flags |= 4; data.Add (flags); // absolute granular position data.Add (ByteVector.FromLong (absolute_granular_position, false)); // stream serial number data.Add (ByteVector.FromUInt (stream_serial_number, false)); // page sequence number data.Add (ByteVector.FromUInt ((uint) page_sequence_number, false)); // checksum -- this is left empty and should be filled in by the Ogg::Page // class data.Add (new ByteVector (4, 0)); // page segment count and page segment table ByteVector page_segments = LacingValues; data.Add ((byte) page_segments.Count); data.Add (page_segments); return data; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public bool IsValid { get {return is_valid;} } public int [] PacketSizes { get {return (int []) packet_sizes.ToArray (typeof (int));} set {packet_sizes = new ArrayList (value);} } public bool FirstPacketContinued { get {return first_packet_continued;} set {first_packet_continued = value;} } public bool LastPacketCompleted { get {return last_packet_completed;} set {last_packet_completed = value;} } public bool FirstPageOfStream { get {return first_page_of_stream;} set {first_page_of_stream = value;} } public bool LastPageOfStream { get {return last_page_of_stream;} set {last_page_of_stream = value;} } public long AbsoluteGranularPosition { get {return absolute_granular_position;} set {absolute_granular_position = value;} } public int PageSequenceNumber { get {return page_sequence_number;} set {page_sequence_number = value;} } public uint StreamSerialNumber { get {return stream_serial_number;} set {stream_serial_number = value;} } public int Size {get {return size;}} public int DataSize {get {return data_size;}} ////////////////////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////////////////////// private void Read (File file, long file_offset) { file.Seek (file_offset); // An Ogg page header is at least 27 bytes, so we'll go ahead and read that // much and then get the rest when we're ready for it. ByteVector data = file.ReadBlock (27); // Sanity check -- make sure that we were in fact able to read as much data as // we asked for and that the page begins with "OggS". if (data.Count != 27 || !data.StartsWith ("OggS")) { Debugger.Debug ("Ogg.PageHeader.Read() -- error reading page header"); return; } byte flags = data [5]; first_packet_continued = (flags & 1) != 0; first_page_of_stream = ((flags >> 1) & 1) != 0; last_page_of_stream = ((flags >> 2) & 1) != 0; absolute_granular_position = data.Mid( 6, 8).ToLong (false); stream_serial_number = data.Mid(14, 4).ToUInt (false); page_sequence_number = (int) data.Mid(18, 4).ToUInt (false); // Byte number 27 is the number of page segments, which is the only variable // length portion of the page header. After reading the number of page // segments we'll then read in the coresponding data for this count. int page_segment_count = data [26]; ByteVector page_segments = file.ReadBlock (page_segment_count); // Another sanity check. if(page_segment_count < 1 || page_segments.Count != page_segment_count) return; // The base size of an Ogg page 27 bytes plus the number of lacing values. size = 27 + page_segment_count; int packet_size = 0; for (int i = 0; i < page_segment_count; i++) { data_size += page_segments [i]; packet_size += page_segments [i]; if (page_segments [i] < 255) { packet_sizes.Add (packet_size); packet_size = 0; } } if (packet_size > 0) { packet_sizes.Add (packet_size); last_packet_completed = false; } else last_packet_completed = true; is_valid = true; } ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private ByteVector LacingValues { get { ByteVector data = new ByteVector (); int [] sizes = PacketSizes; for (int i = 0; i < sizes.Length; i ++) { // The size of a packet in an Ogg page is indicated by a series of "lacing // values" where the sum of the values is the packet size in bytes. Each of // these values is a byte. A value of less than 255 (0xff) indicates the end // of the packet. int quot = sizes [i] / 255; int rem = sizes [i] % 255; for (int j = 0; j < quot; j++) data.Add ((byte) 255); if (i < sizes.Length - 1 || last_packet_completed) data.Add ((byte) rem); } return data; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO.Ports; using System.Windows.Forms; using gView.GPS.UI.Properties; namespace gView.Framework.GPS.UI { public partial class FormGPS : Form { private static GPSDevice _device = null; private Dictionary<int, Satellite> _satellites; public FormGPS() { InitializeComponent(); InitialiseControlValues(); _satellites = new Dictionary<int, Satellite>(); if (_device != null) { _device.PositionReceived -= new GPSDevice.PositionReceivedEventHandler(device_PositionReceived); _device.PDOPReceived -= new GPSDevice.PDOPReceivedEventHandler(device_PDOPReceived); _device.VDOPReceived -= new GPSDevice.VDOPReceivedEventHandler(device_VDOPReceived); _device.HDOPReceived -= new GPSDevice.HDOPReceivedEventHandler(device_HDOPReceived); _device.SatelliteReceived -= new GPSDevice.SatelliteReceivedEventHandler(device_SatelliteReceived); _device.DateTimeChanged -= new GPSDevice.DateTimeChangedEventHandler(device_DateTimeChanged); _device.PositionReceived += new GPSDevice.PositionReceivedEventHandler(device_PositionReceived); _device.PDOPReceived += new GPSDevice.PDOPReceivedEventHandler(device_PDOPReceived); _device.VDOPReceived += new GPSDevice.VDOPReceivedEventHandler(device_VDOPReceived); _device.HDOPReceived += new GPSDevice.HDOPReceivedEventHandler(device_HDOPReceived); _device.SatelliteReceived += new GPSDevice.SatelliteReceivedEventHandler(device_SatelliteReceived); _device.DateTimeChanged += new GPSDevice.DateTimeChangedEventHandler(device_DateTimeChanged); } } private void InitialiseControlValues() { cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity))); cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits))); cmbParity.Text = Settings.Default.Parity.ToString(); cmbStopBits.Text = Settings.Default.StopBits.ToString(); cmbDataBits.Text = Settings.Default.DataBits.ToString(); cmbBaudRate.Text = Settings.Default.BaudRate.ToString(); cmbPortName.Items.Clear(); foreach (string s in SerialPort.GetPortNames()) cmbPortName.Items.Add(s); if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = 0; else { MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } } public GPSDevice Device { get { return _device; } set { _device = value; if (_device != null && _device.SerialPort != null) { SerialPort comport = _device.SerialPort; btnStart.Text = (comport.IsOpen ? "Stop" : "Start"); cmbParity.Text = comport.Parity.ToString(); cmbStopBits.Text = comport.StopBits.ToString(); cmbDataBits.Text = comport.DataBits.ToString(); cmbBaudRate.Text = comport.BaudRate.ToString(); cmbPortName.Text = comport.PortName; } } } private void btnStart_Click(object sender, EventArgs e) { if (_device != null) { _device.Dispose(); _device = null; } if (btnStart.Text == "Start") { _device = new GPSDevice( cmbPortName.Text, int.Parse(cmbBaudRate.Text), (Parity)Enum.Parse(typeof(Parity), cmbParity.Text), int.Parse(cmbDataBits.Text), (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text)); _device.PositionReceived -= new GPSDevice.PositionReceivedEventHandler(device_PositionReceived); _device.PDOPReceived -= new GPSDevice.PDOPReceivedEventHandler(device_PDOPReceived); _device.VDOPReceived -= new GPSDevice.VDOPReceivedEventHandler(device_VDOPReceived); _device.HDOPReceived -= new GPSDevice.HDOPReceivedEventHandler(device_HDOPReceived); _device.SatelliteReceived -= new GPSDevice.SatelliteReceivedEventHandler(device_SatelliteReceived); _device.DateTimeChanged -= new GPSDevice.DateTimeChangedEventHandler(device_DateTimeChanged); _device.PositionReceived+=new GPSDevice.PositionReceivedEventHandler(device_PositionReceived); _device.PDOPReceived+=new GPSDevice.PDOPReceivedEventHandler(device_PDOPReceived); _device.VDOPReceived+=new GPSDevice.VDOPReceivedEventHandler(device_VDOPReceived); _device.HDOPReceived += new GPSDevice.HDOPReceivedEventHandler(device_HDOPReceived); _device.SatelliteReceived += new GPSDevice.SatelliteReceivedEventHandler(device_SatelliteReceived); _device.DateTimeChanged += new GPSDevice.DateTimeChangedEventHandler(device_DateTimeChanged); if (_device.Start()) { btnStart.Text = "Stop"; } else { MessageBox.Show("Can't connect to port...\n"+_device.ErrorMessage); } } else { btnStart.Text = "Start"; } } private delegate void device_DateTimeChangedCallback(GPSDevice sender, DateTime dateTime); void device_DateTimeChanged(GPSDevice sender, DateTime dateTime) { if (this.InvokeRequired) { device_DateTimeChangedCallback d = new device_DateTimeChangedCallback(device_DateTimeChanged); this.Invoke(d, new object[] {sender,dateTime}); } else { txtTime.Text = dateTime.ToLongTimeString(); } } private delegate void device_SatelliteReceivedCallback(GPSDevice sender, int pseudoRandomCode, int azimuth, int elevation, int signalToNoiseRatio); void device_SatelliteReceived(GPSDevice sender, int pseudoRandomCode, int azimuth, int elevation, int signalToNoiseRatio) { if (this.InvokeRequired) { device_SatelliteReceivedCallback d = new device_SatelliteReceivedCallback(device_SatelliteReceived); this.Invoke(d, new object[] { sender, pseudoRandomCode, azimuth, elevation, signalToNoiseRatio }); } else { if (!_satellites.ContainsKey(pseudoRandomCode)) { _satellites.Add(pseudoRandomCode, new Satellite(pseudoRandomCode, azimuth, elevation, signalToNoiseRatio)); } else { Satellite sat = _satellites[pseudoRandomCode]; sat.pseudoRandomCode = pseudoRandomCode; sat.azimuth = azimuth; sat.elevation = elevation; sat.signalToNoiseRatio = signalToNoiseRatio; } panelSatellites.Refresh(); } } private delegate void device_Callback(GPSDevice sender, double value); void device_HDOPReceived(GPSDevice sender, double value) { if (this.InvokeRequired) { device_Callback d = new device_Callback(device_HDOPReceived); this.Invoke(d, new object[] { sender, value }); } else { txtHDOP.Text = value.ToString(); } } void device_VDOPReceived(GPSDevice sender, double value) { if (this.InvokeRequired) { device_Callback d = new device_Callback(device_VDOPReceived); this.Invoke(d, new object[] { sender, value }); } else { txtVDOP.Text = value.ToString(); } } void device_PDOPReceived(GPSDevice sender, double value) { if (this.InvokeRequired) { device_Callback d = new device_Callback(device_PDOPReceived); this.Invoke(d, new object[] { sender, value }); } else { txtPDOP.Text = value.ToString(); } } private delegate void device_PositionReceivedCallback(GPSDevice sender, string Lon, string Lat, double deciLon, double deciLat); private void device_PositionReceived(GPSDevice sender, string Lon, string Lat, double deciLon, double deciLat) { if (this.InvokeRequired) { device_PositionReceivedCallback d = new device_PositionReceivedCallback(device_PositionReceived); this.Invoke(d, new object[] { sender, Lon, Lat, deciLon, deciLat }); } else { txtLon.Text = Lon; txtLat.Text = Lat; txtDLon.Text = deciLon.ToString(); txtDLat.Text = deciLat.ToString(); } } private void panelSatellites_Paint(object sender, PaintEventArgs e) { int r = Math.Min(panelSatellites.Width, panelSatellites.Height)/2; int cx = 0, cy = 0; if (r == panelSatellites.Height / 2) { e.Graphics.TranslateTransform(cx = r + panelSatellites.Width / 2 - r, cy = r); } else { e.Graphics.TranslateTransform(cx = r, cy = r + panelSatellites.Height / 2 - r); } using (SolidBrush brush = new SolidBrush(Color.White)) { e.Graphics.FillEllipse(brush, -r, -r, 2 * r, 2 * r); using (Pen pen = new Pen(Color.Gray)) { for (int R = r; R > 0; R -= r/3) { e.Graphics.DrawEllipse(pen, -R, -R, 2 * R, 2 * R); } e.Graphics.DrawLine(pen, 0, r, 0, -r); e.Graphics.DrawLine(pen, r, 0, -r, 0); } brush.Color = Color.Red; double azi = 0.0; foreach (Satellite sat in _satellites.Values) { azi = -sat.azimuth; e.Graphics.ResetTransform(); e.Graphics.TranslateTransform(cx, cy); e.Graphics.RotateTransform((float)azi); int ele = (int)(sat.elevation * ((double)r / 90.0)); e.Graphics.FillEllipse(brush, -3, ele, 6, 6); } } e.Graphics.ResetTransform(); } } internal class Satellite { public int pseudoRandomCode; public int azimuth; public int elevation; public int signalToNoiseRatio; public Satellite(int pseudocode, int azi, int ele, int signal) { pseudoRandomCode = pseudocode; azimuth = azi; elevation = ele; signalToNoiseRatio = signal; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate001.dlgate001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate001.dlgate001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression : with event accessor and rhs inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public C() { E += C.Foo1; E += C.Foo2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E -= (Dele)C.Foo2; var length = c.E.GetInvocationList().Length; var result = c.DoEvent(9); if (result != 10 && length != 1) return 1; c.E -= new Dele(C.Foo1); if (c.E != null) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate002.dlgate002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate002.dlgate002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression : without event accessor and rhs inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public C() { E += C.Foo1; E += C.Foo2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E -= (Dele)C.Foo2; var length = c.E.GetInvocationList().Length; var result = c.DoEvent(9); if (result != 10 && length != 1) return 1; c.E -= new Dele(C.Foo1); if (c.E != null) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate003.dlgate003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate003.dlgate003; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression : with event accessor and rhs inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public C() { E += C.Foo1; E += C.Foo2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E -= (Dele)C.Foo3; var length = c.E.GetInvocationList().Length; var result = c.DoEvent(9); if (result != 11 && length != 2) return 1; c.E -= new Dele(delegate (int i) { return i + 2; } ); length = c.E.GetInvocationList().Length; result = c.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate004.dlgate004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dlgate004.dlgate004; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression : without event accessor and rhs outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public C() { E += C.Foo1; E += C.Foo2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E -= (Dele)C.Foo3; var length = c.E.GetInvocationList().Length; var result = c.DoEvent(9); if (result != 11 && length != 2) return 1; c.E -= new Dele(x => x + 2); length = c.E.GetInvocationList().Length; result = c.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic001.dynamic001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic001.dynamic001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: with event accessor and rhs is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; dynamic c = new C(); c.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic002.dynamic002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic002.dynamic002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: without event accessor and rhs is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; dynamic c = new C(); c.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic003.dynamic003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic003.dynamic003; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: with event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; dynamic c = new C(); c.E += (Dele)C.Foo3; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic004.dynamic004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic004.dynamic004; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: without event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; dynamic c = new C(); c.E += (Dele)C.Foo3; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic005.dynamic005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic005.dynamic005; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: with event accessor and rhs is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo2; d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic006.dynamic006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic006.dynamic006; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: without event accessor and rhs is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo2; d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic007.dynamic007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic007.dynamic007; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: with event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo3; d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic008.dynamic008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.dynamic008.dynamic008; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: without event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 2; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo3; d.E += (Dele)C.Foo1; d.E += (Dele)C.Foo2; d.E -= c.E; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty001.fieldproperty001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty001.fieldproperty001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : with event accessor and field/property is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public event Dele E; public C() { field = C.Foo1; E += C.Foo1; E += C.Foo2; } public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static int Foo(int i) { return i; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); C c = new C(); d.E -= c.field; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 1) return 1; c.field = C.Foo2; d.E -= c.Field; if (d.E != null) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty002.fieldproperty002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty002.fieldproperty002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : without event accessor and field/property is inside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public Dele E; public C() { field = C.Foo1; E += C.Foo1; E += C.Foo2; } public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); C c = new C(); d.E -= c.field; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 1) return 1; c.field = C.Foo2; d.E -= c.Field; if (d.E != null) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty003.fieldproperty003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty003.fieldproperty003; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : with event accessor and field/property is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public event Dele E; public C() { field = C.Foo3; E += C.Foo1; E += C.Foo2; } public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static int Foo(int i) { return i; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); C c = new C(); d.E -= c.field; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; c.field = new Dele(x => x + 2); d.E -= c.Field; length = d.E.GetInvocationList().Length; if (length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty004.fieldproperty004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.fieldproperty004.fieldproperty004; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : without event accessor and field/property is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public Dele E; public C() { field = C.Foo3; E += C.Foo1; E += C.Foo2; } public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); C c = new C(); d.E -= c.field; var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; c.field = new Dele(x => x + 2); d.E -= c.Field; length = d.E.GetInvocationList().Length; if (length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.null001.null001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.null001.null001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // Negtive: rhs is null literal: lhs is not runtime null. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += (Dele)C.Foo; int result = 0; try { d.E -= null; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) // should not { result += 1; } return result; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.null002.null002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.null002.null002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // Negtive: rhs is null literal: lhs is runtime null. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); int result = 0; try { d.E -= null; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) // should not { result += 1; } return result; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return001.return001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return001.return001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : with event accessor and rhs is in invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static Dele Bar() { return C.Foo2; } public C() { E += C.Foo1; E += C.Foo2; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E -= C.Bar(); var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return002.return002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return002.return002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : without event accessor and rhs is in invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static Dele Bar() { return C.Foo2; } public C() { E += C.Foo1; E += C.Foo2; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E -= C.Bar(); var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 10 && length != 1) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return003.return003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return003.return003; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : with event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static Dele Bar() { return C.Foo3; } public C() { E += C.Foo1; E += C.Foo2; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E -= C.Bar(); var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return004.return004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return004.return004; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : without event accessor and rhs is outside the invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static Dele Bar() { return C.Foo3; } public C() { E += C.Foo1; E += C.Foo2; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E -= C.Bar(); var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return005.return005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.minuseql.return005.return005; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : with event accessor and rhs is in invocation list // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo1(int i) { return i + 1; } public static int Foo2(int i) { return i + 2; } public static int Foo3(int i) { return i + 3; } public static Dele Bar() { return new Dele(x => x + 2); } public C() { E += C.Foo1; E += C.Foo2; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E -= C.Bar(); var length = d.E.GetInvocationList().Length; var result = d.DoEvent(9); if (result != 11 && length != 2) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> }
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections; using System.Linq; using EnvDTE; using EnvDTE80; using FluentAssertions; namespace SonarLint.VisualStudio.Integration.UnitTests { /// <summary> /// EnvDTE implementation of <see cref="Solution"/> and <see cref="Solution2"/> /// </summary> public partial class SolutionMock : Solution, Solution2 { public SolutionMock(DTEMock dte, string solutionFile) : base(solutionFile) { this.dte = dte; if (this.dte != null) { this.dte.Solution = this; } } DTE Solution2.DTE { get { return this.dte; } } DTE Solution2.Parent { get { return this.dte; } } int Solution2.Count { get { throw new NotImplementedException(); } } string Solution2.FileName { get { throw new NotImplementedException(); } } Properties Solution2.Properties { get { throw new NotImplementedException(); } } bool Solution2.IsDirty { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string Solution2.FullName { get { return this.FilePath; } } bool Solution2.Saved { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } Globals Solution2.Globals { get { throw new NotImplementedException(); } } AddIns Solution2.AddIns { get { throw new NotImplementedException(); } } dynamic Solution2.ExtenderNames { get { throw new NotImplementedException(); } } string Solution2.ExtenderCATID { get { throw new NotImplementedException(); } } bool Solution2.IsOpen { get { throw new NotImplementedException(); } } SolutionBuild Solution2.SolutionBuild { get { throw new NotImplementedException(); } } Projects Solution2.Projects { get { return ((_Solution)this).Projects; } } DTE _Solution.DTE { get { return this.dte; } } DTE _Solution.Parent { get { return this.dte; } } int _Solution.Count { get { throw new NotImplementedException(); } } string _Solution.FileName { get { throw new NotImplementedException(); } } Properties _Solution.Properties { get { throw new NotImplementedException(); } } bool _Solution.IsDirty { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string _Solution.FullName { get { return this.FilePath; } } bool _Solution.Saved { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } Globals _Solution.Globals { get { throw new NotImplementedException(); } } AddIns _Solution.AddIns { get { throw new NotImplementedException(); } } object _Solution.ExtenderNames { get { throw new NotImplementedException(); } } string _Solution.ExtenderCATID { get { throw new NotImplementedException(); } } bool _Solution.IsOpen { get { throw new NotImplementedException(); } } SolutionBuild _Solution.SolutionBuild { get { throw new NotImplementedException(); } } Projects _Solution.Projects { get { return new _ProjectsMock(this); } } Project _Solution.Item(object index) { throw new NotImplementedException(); } IEnumerator _Solution.GetEnumerator() { throw new NotImplementedException(); } void _Solution.SaveAs(string FileName) { throw new NotImplementedException(); } Project _Solution.AddFromTemplate(string FileName, string Destination, string ProjectName, bool Exclusive) { throw new NotImplementedException(); } Project _Solution.AddFromFile(string FileName, bool Exclusive) { throw new NotImplementedException(); } void _Solution.Open(string FileName) { throw new NotImplementedException(); } void _Solution.Close(bool SaveFirst) { throw new NotImplementedException(); } void _Solution.Remove(Project proj) { throw new NotImplementedException(); } void _Solution.Create(string Destination, string Name) { throw new NotImplementedException(); } ProjectItem _Solution.FindProjectItem(string FileName) { throw new NotImplementedException(); } string _Solution.ProjectItemsTemplatePath(string ProjectKind) { throw new NotImplementedException(); } string _Solution.get_TemplatePath(string ProjectType) { throw new NotImplementedException(); } object _Solution.get_Extender(string ExtenderName) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } Project Solution2.Item(object index) { throw new NotImplementedException(); } IEnumerator Solution2.GetEnumerator() { throw new NotImplementedException(); } void Solution2.SaveAs(string FileName) { throw new NotImplementedException(); } Project Solution2.AddFromTemplate(string FileName, string Destination, string ProjectName, bool Exclusive) { throw new NotImplementedException(); } Project Solution2.AddFromFile(string FileName, bool Exclusive) { throw new NotImplementedException(); } void Solution2.Open(string FileName) { throw new NotImplementedException(); } void Solution2.Close(bool SaveFirst) { throw new NotImplementedException(); } void Solution2.Remove(Project proj) { var projectMock = proj as ProjectMock; if (projectMock == null) return; this.RemoveProject(projectMock); } void Solution2.Create(string Destination, string Name) { throw new NotImplementedException(); } ProjectItem Solution2.FindProjectItem(string FileName) { throw new NotImplementedException(); } string Solution2.ProjectItemsTemplatePath(string ProjectKind) { throw new NotImplementedException(); } Project Solution2.AddSolutionFolder(string Name) { this.projects.Should().NotContainKey(Name, "Solution folder already exists"); var solutionFolder = this.AddOrGetProject(Name); solutionFolder.ProjectKind = ProjectSystemHelper.VsProjectItemKindSolutionFolder; return solutionFolder; } string Solution2.GetProjectTemplate(string TemplateName, string Language) { throw new NotImplementedException(); } string Solution2.GetProjectItemTemplate(string TemplateName, string Language) { throw new NotImplementedException(); } string Solution2.get_TemplatePath(string ProjectType) { throw new NotImplementedException(); } dynamic Solution2.get_Extender(string ExtenderName) { throw new NotImplementedException(); } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } #region Projects mock private class _ProjectsMock : Projects { private readonly SolutionMock parent; public _ProjectsMock(SolutionMock parent) { this.parent = parent; } public int Count { get { return this.parent.Projects.Count(); } } public DTE DTE { get { throw new NotImplementedException(); } } public string Kind { get { throw new NotImplementedException(); } } public DTE Parent { get { throw new NotImplementedException(); } } public Properties Properties { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { return this.parent.Projects.GetEnumerator(); } public Project Item(object index) { throw new NotImplementedException(); } } #endregion Projects mock } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using lst.Areas.HelpPage.ModelDescriptions; using lst.Areas.HelpPage.Models; using lst.Areas.HelpPage.SampleGeneration; namespace lst.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//This is UnityEditor only for the time being... #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.IO; using UMA; using UMACharacterSystem; //UPDATED For CharacterSystem. //Takes photos of the character based on the Wardrobe slots. //HUGE MemoryLeak or infinite loop in this somewhere... public class PhotoBooth : MonoBehaviour { public RenderTexture bodyRenderTexture; public RenderTexture outfitRenderTexture; public RenderTexture headRenderTexture; public RenderTexture chestRenderTexture; public RenderTexture handsRenderTexture; public RenderTexture legsRenderTexture; public RenderTexture feetRenderTexture; public DynamicCharacterAvatar avatarToPhoto; public enum renderTextureOpts { BodyRenderTexture, OutfitRenderTexture, HeadRenderTexture, ChestRenderTexture, HandsRenderTexture, LegsRenderTexture, FeetRenderTexture }; public string photoName; public bool freezeAnimation; public float animationFreezeFrame = 1.8f; public string destinationFolder;//non-serialized? [Tooltip("If true will automatically take all possible wardrobe photos for the current character. Otherwise photographs character in its current state.")] public bool autoPhotosEnabled = true; [Tooltip("In mnual mode use this to select the RenderTexture you wish to Photo")] public renderTextureOpts textureToPhoto = renderTextureOpts.BodyRenderTexture; [Tooltip("If true will dim everything but the target wardrobe recipe (AutoPhotosEnabled only)")] public bool dimAllButTarget = false; public Color dimToColor = new Color(0, 0, 0, 1); public Color dimToMetallic = new Color(0, 0, 0, 1); [Tooltip("If true will set the colors for the target wardrobe recipe to the neuttal color (AutoPhotosEnabled only)")] public bool neutralizeTargetColors = false; public Color neutralizeToColor = new Color(1, 1, 1, 1); public Color neutralizeToMetallic = new Color(0, 0, 0, 1); [Tooltip("If true will attempt to find an underwear wardrobe slot to apply when taking the base race photo (AutoPhotosEnabled only)")] public bool addUnderwearToBasePhoto = true; public bool overwriteExistingPhotos = true; public bool doingTakePhoto = false; bool canTakePhoto = true; RenderTexture renderTextureToUse; UMATextRecipe wardrobeRecipeToPhoto; Dictionary<int, Dictionary<int, Color>> originalColors = new Dictionary<int, Dictionary<int, Color>>(); DynamicCharacterSystem dcs; bool basePhotoTaken; public void TakePhotos() { if (doingTakePhoto == false) { doingTakePhoto = true; if (avatarToPhoto == null) { Debug.Log("You need to set the Avatar to photo in the inspector!"); doingTakePhoto = false; return; } if (destinationFolder == "") { Debug.Log("You need to set a DestinationFolder in the inspector!"); doingTakePhoto = false; return; } dcs = UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem; if (!autoPhotosEnabled) { bool canPhoto = SetBestRenderTexture(); if (canPhoto) { photoName = photoName == "" ? avatarToPhoto.activeRace.name + Path.GetRandomFileName().Replace(".", "") : photoName; StartCoroutine(TakePhotoCoroutine()); } else { Debug.Log("Unknown RenderTexture Error..."); doingTakePhoto = false; return; } } else { Dictionary<string, List<UMATextRecipe>> recipesToPhoto = dcs.Recipes[avatarToPhoto.activeRace.name]; basePhotoTaken = false; StartCoroutine(TakePhotosCoroutine(recipesToPhoto)); } } } IEnumerator TakePhotosCoroutine(Dictionary<string, List<UMATextRecipe>> recipesToPhoto) { yield return null; wardrobeRecipeToPhoto = null; if (!basePhotoTaken) { Debug.Log("Gonna take base Photo..."); avatarToPhoto.ClearSlots(); if (addUnderwearToBasePhoto) { foreach (KeyValuePair<string, List<UMATextRecipe>> kp in recipesToPhoto) { if (kp.Key.IndexOf("Underwear") > -1 || kp.Key.IndexOf("underwear") > -1) { avatarToPhoto.SetSlot(kp.Value[0]); } } } bool renderTextureFound = SetBestRenderTexture("Body"); if (!renderTextureFound) { Debug.Log("No suitable RenderTexture found for Base Photo.."); doingTakePhoto = false; yield break; } photoName = avatarToPhoto.activeRace.name; canTakePhoto = false; avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReady); avatarToPhoto.BuildCharacter(true); while (!canTakePhoto) { yield return new WaitForSeconds(1f); } yield return StartCoroutine("TakePhotoCoroutine"); Debug.Log("Took base Photo..."); StopCoroutine("TakePhotoCoroutine"); //really we need photos for each area of the body (i.e. from each renderTexture/Cam) with no clothes on so we can have a 'None' image //so we'll need head, chest, hands, legs, feet, full outfit... Debug.Log("Now taking the Base Photos for body parts..."); List<string> emptySlotsToPhoto = new List<string> { "Head", "Chest", "Hands", "Legs", "Feet", "Outfit" }; //if dimming and neutralizing is on do it if (dimAllButTarget && neutralizeTargetColors) { canTakePhoto = false; avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReadyAfterColorChange); DoDimmingAndNeutralizing(); while (!canTakePhoto) { yield return new WaitForSeconds(1f); } } foreach (string emptySlotToPhoto in emptySlotsToPhoto) { photoName = avatarToPhoto.activeRace.name + emptySlotToPhoto + "None"; renderTextureFound = SetBestRenderTexture(emptySlotToPhoto); if (!renderTextureFound) { Debug.Log("No suitable RenderTexture found for " + emptySlotToPhoto + " Photo.."); continue; } yield return StartCoroutine("TakePhotoCoroutine"); Debug.Log("Took base " + emptySlotToPhoto + " Photo..."); StopCoroutine("TakePhotoCoroutine"); } basePhotoTaken = true; Debug.Log("Now taking the rest..."); StartCoroutine(TakePhotosCoroutine(recipesToPhoto)); yield break; } else { Debug.Log("Gonna take other wardrobe photos..."); if (originalColors.Count > 0) { avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange); UndoDimmingAnNeutralizing(); } var numKeys = recipesToPhoto.Count; int slotsDone = 0; foreach (string wardrobeSlot in recipesToPhoto.Keys) { Debug.Log("Gonna take photos for " + wardrobeSlot); bool renderTextureFound = SetBestRenderTexture(wardrobeSlot); if (!renderTextureFound) { Debug.Log("No suitable RenderTexture found for " + wardrobeSlot + " Photo.."); doingTakePhoto = false; yield break; } foreach (UMATextRecipe wardrobeRecipe in recipesToPhoto[wardrobeSlot]) { Debug.Log("Gonna take photos for " + wardrobeRecipe.name + " in " + wardrobeSlot); photoName = wardrobeRecipe.name; var path = destinationFolder + "/" + photoName + ".png"; if (!overwriteExistingPhotos && File.Exists(Application.dataPath + "/" + path)) { Debug.Log("Photo already existed for " + photoName + ". Turn on overwrite photos to replace existig ones"); continue; } wardrobeRecipeToPhoto = wardrobeRecipe; avatarToPhoto.ClearSlots(); if (addUnderwearToBasePhoto) { foreach (KeyValuePair<string, List<UMATextRecipe>> kp in recipesToPhoto) { if (kp.Key.IndexOf("Underwear") > -1 || kp.Key.IndexOf("underwear") > -1) { avatarToPhoto.SetSlot(kp.Value[0]); break; } } } avatarToPhoto.SetSlot(wardrobeRecipe); canTakePhoto = false; avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReady); avatarToPhoto.BuildCharacter(true); while (!canTakePhoto) { Debug.Log("Waiting to take photo..."); yield return new WaitForSeconds(1f); } yield return StartCoroutine("TakePhotoCoroutine"); StopCoroutine("TakePhotoCoroutine"); } slotsDone++; if (slotsDone == numKeys) { Debug.Log("Doing Final Reset"); if (originalColors.Count > 0) { avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange); UndoDimmingAnNeutralizing(); } if (freezeAnimation) { avatarToPhoto.umaData.animator.speed = 1f; avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableBlinking = true; avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableSaccades = true; } avatarToPhoto.LoadDefaultWardrobe(); avatarToPhoto.BuildCharacter(true); doingTakePhoto = false; StopAllCoroutines(); yield break; } } } } public void SetCharacterReady(UMAData umaData) { avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReady); if ((dimAllButTarget || neutralizeTargetColors) /*&& wardrobeRecipeToPhoto != null*/)//should we be making it possible to dim the base slot photos too? { if (originalColors.Count > 0) { avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange); UndoDimmingAnNeutralizing();//I think this is causing character updates maybe? } avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReadyAfterColorChange); DoDimmingAndNeutralizing(); } else { if (freezeAnimation) { SetAnimationFrame(); } canTakePhoto = true; } } public void SetCharacterReadyAfterColorChange(UMAData umaData) { avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange); if (freezeAnimation) { SetAnimationFrame(); } canTakePhoto = true; } public void SetAnimationFrame() { var thisAnimatonClip = avatarToPhoto.umaData.animationController.animationClips[0]; avatarToPhoto.umaData.animator.Play(thisAnimatonClip.name, 0, animationFreezeFrame); avatarToPhoto.umaData.animator.speed = 0f; avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableBlinking = false; avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableSaccades = false; } IEnumerator TakePhotoCoroutine() { canTakePhoto = false; Debug.Log("Taking Photo..."); var path = destinationFolder + "/" + photoName + ".png"; if (!overwriteExistingPhotos && File.Exists(Application.dataPath + "/" + path)) { Debug.Log("could not overwrite existing Photo. Turn on Overwrite Existing Photos if you want to allow this"); canTakePhoto = true; yield return true; } else { Texture2D texToSave = new Texture2D(renderTextureToUse.width, renderTextureToUse.height); RenderTexture prev = RenderTexture.active; RenderTexture.active = renderTextureToUse; texToSave.ReadPixels(new Rect(0, 0, renderTextureToUse.width, renderTextureToUse.height), 0, 0, true); texToSave.Apply(); byte[] texToSavePNG = texToSave.EncodeToPNG(); //path must be inside assets File.WriteAllBytes(Application.dataPath + "/" + path, texToSavePNG); RenderTexture.active = prev; AssetDatabase.ImportAsset("Assets/" + path, ImportAssetOptions.ForceUncompressedImport); TextureImporter textureImporter = AssetImporter.GetAtPath("Assets/" + path) as TextureImporter; textureImporter.textureType = TextureImporterType.Sprite; textureImporter.mipmapEnabled = false; textureImporter.maxTextureSize = 256; AssetDatabase.ImportAsset("Assets/" + path, ImportAssetOptions.ForceUpdate); canTakePhoto = true; yield return true; } } public void UndoDimmingAnNeutralizing() { int numSlots = avatarToPhoto.umaData.GetSlotArraySize(); for (int i = 0; i < numSlots; i++) { if (avatarToPhoto.umaData.GetSlot(i)) { var thisSlot = avatarToPhoto.umaData.GetSlot(i); var thisSlotOverlays = thisSlot.GetOverlayList(); for (int ii = 0; ii < thisSlotOverlays.Count; ii++) { if (originalColors.ContainsKey(i)) { if (originalColors[i].ContainsKey(ii)) { thisSlotOverlays[ii].SetColor(0, originalColors[i][ii]); } } } } } } public void DoDimmingAndNeutralizing() { if (wardrobeRecipeToPhoto != null) Debug.Log("Doing Dimming And Neutralizing for " + wardrobeRecipeToPhoto.name); else Debug.Log("Doing Dimming And Neutralizing for Body shots"); int numAvatarSlots = avatarToPhoto.umaData.GetSlotArraySize(); UMAData.UMARecipe tempLoadedRecipe = new UMAData.UMARecipe(); if (wardrobeRecipeToPhoto != null) wardrobeRecipeToPhoto.Load(tempLoadedRecipe, avatarToPhoto.context); originalColors.Clear(); List<string> slotsInRecipe = new List<string>(); List<string> overlaysInRecipe = new List<string>(); if (wardrobeRecipeToPhoto != null) foreach (SlotData slot in tempLoadedRecipe.slotDataList) { if (slot != null) { slotsInRecipe.Add(slot.asset.name); foreach (OverlayData wOverlay in slot.GetOverlayList()) { if (!overlaysInRecipe.Contains(wOverlay.asset.name)) overlaysInRecipe.Add(wOverlay.asset.name); } } } //Deal with skin color first if we are dimming if (dimAllButTarget) { OverlayColorData[] sharedColors = avatarToPhoto.umaData.umaRecipe.sharedColors; for (int i = 0; i < sharedColors.Length; i++) { if (sharedColors[i].name == "Skin" || sharedColors[i].name == "skin") { sharedColors[i].color = dimToColor; if (sharedColors[i].channelAdditiveMask.Length >= 3) { sharedColors[i].channelAdditiveMask[2] = dimToMetallic; } } } } for (int i = 0; i < numAvatarSlots; i++) { if (avatarToPhoto.umaData.GetSlot(i) != null) { var overlaysInAvatarSlot = avatarToPhoto.umaData.GetSlot(i).GetOverlayList(); if (slotsInRecipe.Contains(avatarToPhoto.umaData.GetSlot(i).asset.name)) { if (neutralizeTargetColors || dimAllButTarget) { for (int ii = 0; ii < overlaysInAvatarSlot.Count; ii++) { //there is a problem here where if the recipe also contains replacement body slots (like my toon CapriPants_LEGS) these also get set to white //so we need to check if the overlay contains any body part names I think bool overlayIsBody = false; var thisOverlayName = overlaysInAvatarSlot[ii].asset.name; if (thisOverlayName.IndexOf("Face", StringComparison.OrdinalIgnoreCase) > -1 // || thisOverlayName.IndexOf("Torso", StringComparison.OrdinalIgnoreCase) > -1 || thisOverlayName.IndexOf("Arms", StringComparison.OrdinalIgnoreCase) > -1 || thisOverlayName.IndexOf("Hands", StringComparison.OrdinalIgnoreCase) > -1 || thisOverlayName.IndexOf("Legs", StringComparison.OrdinalIgnoreCase) > -1 || thisOverlayName.IndexOf("Feet", StringComparison.OrdinalIgnoreCase) > -1 || thisOverlayName.IndexOf("Body", StringComparison.OrdinalIgnoreCase) > -1) { overlayIsBody = true; } if (overlaysInRecipe.Contains(overlaysInAvatarSlot[ii].asset.name) && overlayIsBody == false) { if (!originalColors.ContainsKey(i)) { originalColors.Add(i, new Dictionary<int, Color>()); } if (!originalColors[i].ContainsKey(ii)) originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color); overlaysInAvatarSlot[ii].colorData.color = neutralizeToColor; if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3) { overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = neutralizeToMetallic; } } else { if (dimAllButTarget) { if (!originalColors.ContainsKey(i)) { originalColors.Add(i, new Dictionary<int, Color>()); } if (!originalColors[i].ContainsKey(ii)) originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color); overlaysInAvatarSlot[ii].colorData.color = dimToColor; if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3) { overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = dimToMetallic; } } } } } } else { if (dimAllButTarget) { for (int ii = 0; ii < overlaysInAvatarSlot.Count; ii++) { if (!overlaysInRecipe.Contains(overlaysInAvatarSlot[ii].asset.name)) { if (!originalColors.ContainsKey(i)) { originalColors.Add(i, new Dictionary<int, Color>()); } if (!originalColors[i].ContainsKey(ii)) originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color); overlaysInAvatarSlot[ii].colorData.color = dimToColor; if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3) { overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = dimToMetallic; } } } } } } } tempLoadedRecipe = null; avatarToPhoto.umaData.dirty = false; avatarToPhoto.umaData.Dirty(false, true, false); } public bool SetBestRenderTexture(string wardrobeSlot = "") { if (wardrobeSlot == "Body" || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.BodyRenderTexture)) { if (bodyRenderTexture == null) { Debug.Log("You need to set the Body Render Texture in the inspector!"); return false; } else { renderTextureToUse = bodyRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Hair", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Face", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Head", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Helmet", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Complexion", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Eyebrows", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Beard", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Ears", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.HeadRenderTexture)) { if (headRenderTexture == null) { Debug.Log("You need to set the Head Render Texture in the inspector!"); return false; } else { renderTextureToUse = headRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Shoulders", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Chest", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Arms", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.ChestRenderTexture) ) { if (chestRenderTexture == null) { Debug.Log("You need to set the Chest Render Texture in the inspector!"); return false; } else { renderTextureToUse = chestRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Hands", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.HandsRenderTexture)) { if (handsRenderTexture == null) { Debug.Log("You need to set the Hands Render Texture in the inspector!"); return false; } else { renderTextureToUse = handsRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Waist", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Legs", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.LegsRenderTexture)) { if (legsRenderTexture == null) { Debug.Log("You need to set the Legs Render Texture in the inspector!"); return false; } else { renderTextureToUse = legsRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Feet", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.FeetRenderTexture)) { if (feetRenderTexture == null) { Debug.Log("You need to set the Feet Render Texture in the inspector!"); return false; } else { renderTextureToUse = feetRenderTexture; return true; } } else if (wardrobeSlot.IndexOf("Outfit", StringComparison.OrdinalIgnoreCase) > -1 || wardrobeSlot.IndexOf("Underwear", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.OutfitRenderTexture)) { if (outfitRenderTexture == null) { Debug.Log("You need to set the Outfit Render Texture in the inspector!"); return false; } else { renderTextureToUse = outfitRenderTexture; return true; } } else { if (!autoPhotosEnabled && bodyRenderTexture != null) { renderTextureToUse = bodyRenderTexture; return true; } else { Debug.Log("No appropriate RenderTexture found for " + wardrobeSlot); return false; } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Security.Principal; namespace System.Security.Claims { /// <summary> /// An Identity that is represented by a set of claims. /// </summary> public class ClaimsIdentity : IIdentity { private const string PreFix = "System.Security.ClaimsIdentity."; private const string AuthenticationTypeKey = PreFix + "authenticationType"; private const string LabelKey = PreFix + "label"; private const string NameClaimTypeKey = PreFix + "nameClaimType"; private const string RoleClaimTypeKey = PreFix + "roleClaimType"; private const string VersionKey = PreFix + "version"; private enum SerializationMask { None = 0, AuthenticationType = 1, BootstrapConext = 2, NameClaimType = 4, RoleClaimType = 8, HasClaims = 16, HasLabel = 32, Actor = 64, UserData = 128, } private byte[] _userSerializationData; private ClaimsIdentity _actor; private string _authenticationType; private object _bootstrapContext; private List<List<Claim>> _externalClaims; private string _label; private List<Claim> _instanceClaims = new List<Claim>(); private string _nameClaimType = DefaultNameClaimType; private string _roleClaimType = DefaultRoleClaimType; public const string DefaultIssuer = @"LOCAL AUTHORITY"; public const string DefaultNameClaimType = ClaimTypes.Name; public const string DefaultRoleClaimType = ClaimTypes.Role; // NOTE about _externalClaims. // GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal. // _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone(). // Access through public method: ClaimProviders. /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> public ClaimsIdentity() : this((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity identity) : this(identity, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> /// </remarks> public ClaimsIdentity(IEnumerable<Claim> claims) : this((IIdentity)null, claims, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The authentication method used to establish this identity.</param> public ClaimsIdentity(string authenticationType) : this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The authentication method used to establish this identity.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType) : this((IIdentity)null, claims, authenticationType, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims) : this(identity, claims, (string)null, (string)null, (string)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(string authenticationType, string nameType, string roleType) : this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType) : this((IIdentity)null, claims, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType. /// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para> /// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para> /// <para>Any 'External' claims are ignored.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular reference back to 'this'.</exception> public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType) { ClaimsIdentity claimsIdentity = identity as ClaimsIdentity; _authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType); _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); if (claimsIdentity != null) { _label = claimsIdentity._label; _bootstrapContext = claimsIdentity._bootstrapContext; if (claimsIdentity.Actor != null) { // // Check if the Actor is circular before copying. That check is done while setting // the Actor property and so not really needed here. But checking just for sanity sake // if (!IsCircular(claimsIdentity.Actor)) { _actor = claimsIdentity.Actor; } else { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } SafeAddClaims(claimsIdentity._instanceClaims); } else { if (identity != null && !string.IsNullOrEmpty(identity.Name)) { SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this)); } } if (claims != null) { SafeAddClaims(claims); } } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public ClaimsIdentity(BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Initialize(reader); } /// <summary> /// Copy constructor. /// </summary> /// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected ClaimsIdentity(ClaimsIdentity other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } if (other._actor != null) { _actor = other._actor.Clone(); } _authenticationType = other._authenticationType; _bootstrapContext = other._bootstrapContext; _label = other._label; _nameClaimType = other._nameClaimType; _roleClaimType = other._roleClaimType; if (other._userSerializationData != null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } SafeAddClaims(other._instanceClaims); } protected ClaimsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via /// <see cref="ISerializable"/>. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> to read from. /// </param> /// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception> protected ClaimsIdentity(SerializationInfo info) { throw new PlatformNotSupportedException(); } /// <summary> /// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority. /// </summary> public virtual string AuthenticationType { get { return _authenticationType; } } /// <summary> /// Gets a value that indicates if the user has been authenticated. /// </summary> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(_authenticationType); } } /// <summary> /// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights. /// </summary> /// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception> public ClaimsIdentity Actor { get { return _actor; } set { if (value != null) { if (IsCircular(value)) { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } _actor = value; } } /// <summary> /// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>. /// </summary> public object BootstrapContext { get { return _bootstrapContext; } set { _bootstrapContext = value; } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>May contain nulls.</remarks> public virtual IEnumerable<Claim> Claims { get { if (_externalClaims == null) { return _instanceClaims; } return CombinedClaimsIterator(); } } private IEnumerable<Claim> CombinedClaimsIterator() { for (int i = 0; i < _instanceClaims.Count; i++) { yield return _instanceClaims[i]; } for (int j = 0; j < _externalClaims.Count; j++) { if (_externalClaims[j] != null) { foreach (Claim claim in _externalClaims[j]) { yield return claim; } } } } /// <summary> /// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>. /// </summary> protected virtual byte[] CustomSerializationData { get { return _userSerializationData; } } /// <summary> /// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>. /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>. /// </summary> internal List<List<Claim>> ExternalClaims { get { if (_externalClaims == null) { _externalClaims = new List<List<Claim>>(); } return _externalClaims; } } /// <summary> /// Gets or sets the label for this <see cref="ClaimsIdentity"/> /// </summary> public string Label { get { return _label; } set { _label = value; } } /// <summary> /// Gets the Name of this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks> public virtual string Name { // just an accessor for getting the name claim get { Claim claim = FindFirst(_nameClaimType); if (claim != null) { return claim.Value; } return null; } } /// <summary> /// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>. /// </summary> public string NameClaimType { get { return _nameClaimType; } } /// <summary> /// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>. /// </summary> public string RoleClaimType { get { return _roleClaimType; } } /// <summary> /// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object. /// </summary> public virtual ClaimsIdentity Clone() { return new ClaimsIdentity(this); } /// <summary> /// Adds a single <see cref="Claim"/> to an internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/>add.</param> /// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claim' is null.</exception> public virtual void AddClaim(Claim claim) { if (claim == null) { throw new ArgumentNullException(nameof(claim)); } if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Adds a <see cref="IEnumerable{Claim}"/> to the internal list. /// </summary> /// <param name="claims">Enumeration of claims to add.</param> /// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claims' is null.</exception> public virtual void AddClaims(IEnumerable<Claim> claims) { if (claims == null) { throw new ArgumentNullException(nameof(claims)); } foreach (Claim claim in claims) { if (claim == null) { continue; } if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Attempts to remove a <see cref="Claim"/> the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> public virtual bool TryRemoveClaim(Claim claim) { if (claim == null) { return false; } bool removed = false; for (int i = 0; i < _instanceClaims.Count; i++) { if (object.ReferenceEquals(_instanceClaims[i], claim)) { _instanceClaims.RemoveAt(i); removed = true; break; } } return removed; } /// <summary> /// Removes a <see cref="Claim"/> from the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception> public virtual void RemoveClaim(Claim claim) { if (!TryRemoveClaim(claim)) { throw new InvalidOperationException(string.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim)); } } /// <summary> /// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaims(IEnumerable<Claim> claims) { foreach (Claim claim in claims) { if (claim == null) continue; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaim(Claim claim) { if (claim == null) return; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } foreach (Claim claim in Claims) { if (match(claim)) { yield return claim; } } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual IEnumerable<Claim> FindAll(string type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { yield return claim; } } } } /// <summary> /// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual Claim FindFirst(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } foreach (Claim claim in Claims) { if (match(claim)) { return claim; } } return null; } /// <summary> /// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual Claim FindFirst(string type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { return claim; } } } return null; } /// <summary> /// Determines if a claim is contained within this ClaimsIdentity. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>true if a claim is found, false otherwise.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual bool HasClaim(Predicate<Claim> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } foreach (Claim claim in Claims) { if (match(claim)) { return true; } } return false; } /// <summary> /// Determines if a claim with type AND value is contained within this ClaimsIdentity. /// </summary> /// <param name="type">the type of the claim to match.</param> /// <param name="value">the value of the claim to match.</param> /// <returns>true if a claim is matched, false otherwise.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception> public virtual bool HasClaim(string type, string value) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } foreach (Claim claim in Claims) { if (claim != null && string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { return true; } } return false; } /// <summary> /// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/> /// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> private void Initialize(BinaryReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { _authenticationType = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { _bootstrapContext = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { _nameClaimType = reader.ReadString(); numPropertiesRead++; } else { _nameClaimType = ClaimsIdentity.DefaultNameClaimType; } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { _roleClaimType = reader.ReadString(); numPropertiesRead++; } else { _roleClaimType = ClaimsIdentity.DefaultRoleClaimType; } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { _label = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { int numberOfClaims = reader.ReadInt32(); for (int index = 0; index < numberOfClaims; index++) { _instanceClaims.Add(CreateClaim(reader)); } numPropertiesRead++; } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor = new ClaimsIdentity(reader); numPropertiesRead++; } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { int cb = reader.ReadInt32(); _userSerializationData = reader.ReadBytes(cb); numPropertiesRead++; } for (int i = numPropertiesRead; i < numPropertiesToRead; i++) { reader.ReadString(); } } /// <summary> /// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>. /// </summary> /// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param> /// <returns>a new <see cref="Claim"/>.</returns> protected virtual Claim CreateClaim(BinaryReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return new Claim(reader, this); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> public virtual void WriteTo(BinaryWriter writer) { WriteTo(writer, null); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <param name="userData">additional data provided by derived type.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> protected virtual void WriteTo(BinaryWriter writer, byte[] userData) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_authenticationType != null) { mask |= SerializationMask.AuthenticationType; numberOfPropertiesWritten++; } if (_bootstrapContext != null) { string rawData = _bootstrapContext as string; if (rawData != null) { mask |= SerializationMask.BootstrapConext; numberOfPropertiesWritten++; } } if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.NameClaimType; numberOfPropertiesWritten++; } if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.RoleClaimType; numberOfPropertiesWritten++; } if (!string.IsNullOrWhiteSpace(_label)) { mask |= SerializationMask.HasLabel; numberOfPropertiesWritten++; } if (_instanceClaims.Count > 0) { mask |= SerializationMask.HasClaims; numberOfPropertiesWritten++; } if (_actor != null) { mask |= SerializationMask.Actor; numberOfPropertiesWritten++; } if (userData != null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; } writer.Write((int)mask); writer.Write(numberOfPropertiesWritten); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { writer.Write(_authenticationType); } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { writer.Write(_bootstrapContext as string); } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { writer.Write(_nameClaimType); } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { writer.Write(_roleClaimType); } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { writer.Write(_label); } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { writer.Write(_instanceClaims.Count); foreach (var claim in _instanceClaims) { claim.WriteTo(writer); } } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor.WriteTo(writer); } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { writer.Write(userData.Length); writer.Write(userData); } writer.Flush(); } /// <summary> /// Checks if a circular reference exists to 'this' /// </summary> /// <param name="subject"></param> /// <returns></returns> private bool IsCircular(ClaimsIdentity subject) { if (ReferenceEquals(this, subject)) { return true; } ClaimsIdentity currSubject = subject; while (currSubject.Actor != null) { if (ReferenceEquals(this, currSubject.Actor)) { return true; } currSubject = currSubject.Actor; } return false; } /// <summary> /// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity /// </summary> /// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param> /// <param name="context">Context for serialization. Can be null.</param> /// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception> protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
using System; using System.Collections.Generic; using IdmNet.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; // ReSharper disable ObjectCreationAsStatement // ReSharper disable UseObjectOrCollectionInitializer namespace IdmNet.Models.Tests { [TestClass] public class msidmPamRoleTests { private msidmPamRole _it; public msidmPamRoleTests() { _it = new msidmPamRole(); } [TestMethod] public void It_has_a_paremeterless_constructor() { Assert.AreEqual("msidmPamRole", _it.ObjectType); } [TestMethod] public void It_has_a_constructor_that_takes_an_IdmResource() { var resource = new IdmResource { DisplayName = "My Display Name", Creator = new Person { DisplayName = "Creator Display Name", ObjectID = "Creator ObjectID"}, }; var it = new msidmPamRole(resource); Assert.AreEqual("msidmPamRole", it.ObjectType); Assert.AreEqual("My Display Name", it.DisplayName); Assert.AreEqual("Creator Display Name", it.Creator.DisplayName); } [TestMethod] public void It_has_a_constructor_that_takes_an_IdmResource_without_Creator() { var resource = new IdmResource { DisplayName = "My Display Name", }; var it = new msidmPamRole(resource); Assert.AreEqual("My Display Name", it.DisplayName); Assert.IsNull(it.Creator); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void It_throws_when_you_try_to_set_ObjectType_to_anything_other_than_its_primary_ObjectType() { _it.ObjectType = "Invalid Object Type"; } [TestMethod] public void It_has_msidmPamIsRoleApprovalNeeded_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamIsRoleApprovalNeeded); } [TestMethod] public void It_has_msidmPamIsRoleApprovalNeeded_which_can_be_set_back_to_null() { // Arrange _it.msidmPamIsRoleApprovalNeeded = true; // Act _it.msidmPamIsRoleApprovalNeeded = null; // Assert Assert.IsNull(_it.msidmPamIsRoleApprovalNeeded); } [TestMethod] public void It_can_get_and_set_msidmPamIsRoleApprovalNeeded() { // Act _it.msidmPamIsRoleApprovalNeeded = true; // Assert Assert.AreEqual(true, _it.msidmPamIsRoleApprovalNeeded); } [TestMethod] public void It_has_msidmPamRoleAvailabilityWindowEnabled_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamRoleAvailabilityWindowEnabled); } [TestMethod] public void It_has_msidmPamRoleAvailabilityWindowEnabled_which_can_be_set_back_to_null() { // Arrange _it.msidmPamRoleAvailabilityWindowEnabled = true; // Act _it.msidmPamRoleAvailabilityWindowEnabled = null; // Assert Assert.IsNull(_it.msidmPamRoleAvailabilityWindowEnabled); } [TestMethod] public void It_can_get_and_set_msidmPamRoleAvailabilityWindowEnabled() { // Act _it.msidmPamRoleAvailabilityWindowEnabled = true; // Assert Assert.AreEqual(true, _it.msidmPamRoleAvailabilityWindowEnabled); } [TestMethod] public void It_has_msidmPamRoleAvailableFrom_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamRoleAvailableFrom); } [TestMethod] public void It_has_msidmPamRoleAvailableFrom_which_can_be_set_back_to_null() { // Arrange var now = DateTime.Now; var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); _it.msidmPamRoleAvailableFrom = testTime; // Act _it.msidmPamRoleAvailableFrom = null; // Assert Assert.IsNull(_it.msidmPamRoleAvailableFrom); } [TestMethod] public void It_can_get_and_set_msidmPamRoleAvailableFrom() { // Act var now = DateTime.Now; var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); _it.msidmPamRoleAvailableFrom = testTime; // Assert Assert.AreEqual(testTime, _it.msidmPamRoleAvailableFrom); } [TestMethod] public void It_has_msidmPamRoleAvailableTo_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamRoleAvailableTo); } [TestMethod] public void It_has_msidmPamRoleAvailableTo_which_can_be_set_back_to_null() { // Arrange var now = DateTime.Now; var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); _it.msidmPamRoleAvailableTo = testTime; // Act _it.msidmPamRoleAvailableTo = null; // Assert Assert.IsNull(_it.msidmPamRoleAvailableTo); } [TestMethod] public void It_can_get_and_set_msidmPamRoleAvailableTo() { // Act var now = DateTime.Now; var testTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); _it.msidmPamRoleAvailableTo = testTime; // Assert Assert.AreEqual(testTime, _it.msidmPamRoleAvailableTo); } [TestMethod] public void It_has_msidmPamRoleMfaEnabled_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamRoleMfaEnabled); } [TestMethod] public void It_has_msidmPamRoleMfaEnabled_which_can_be_set_back_to_null() { // Arrange _it.msidmPamRoleMfaEnabled = true; // Act _it.msidmPamRoleMfaEnabled = null; // Assert Assert.IsNull(_it.msidmPamRoleMfaEnabled); } [TestMethod] public void It_can_get_and_set_msidmPamRoleMfaEnabled() { // Act _it.msidmPamRoleMfaEnabled = true; // Assert Assert.AreEqual(true, _it.msidmPamRoleMfaEnabled); } [TestMethod] public void It_has_Owner_which_is_null_by_default() { // Assert Assert.IsNull(_it.Owner); } [TestMethod] public void It_has_Owner_which_can_be_set_back_to_null() { // Arrange var list = new List<Person> { new Person { DisplayName = "Test Person1", ObjectID = "guid1" }, new Person { DisplayName = "Test Person2", ObjectID = "guid2" } }; _it.Owner = list; // Act _it.Owner = null; // Assert Assert.IsNull(_it.Owner); } [TestMethod] public void It_can_get_and_set_Owner() { // Arrange var list = new List<Person> { new Person { DisplayName = "Test Person1", ObjectID = "guid1" }, new Person { DisplayName = "Test Person2", ObjectID = "guid2" } }; // Act _it.Owner = list; // Assert Assert.AreEqual(list[0].DisplayName, _it.Owner[0].DisplayName); Assert.AreEqual(list[1].DisplayName, _it.Owner[1].DisplayName); } [TestMethod] public void It_has_msidmPamCandidates_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamCandidates); } [TestMethod] public void It_has_msidmPamCandidates_which_can_be_set_back_to_null() { // Arrange var list = new List<IdmResource> { new IdmResource { DisplayName = "Test IdmResource1", ObjectID = "guid1" }, new IdmResource { DisplayName = "Test IdmResource2", ObjectID = "guid2" } }; _it.msidmPamCandidates = list; // Act _it.msidmPamCandidates = null; // Assert Assert.IsNull(_it.msidmPamCandidates); } [TestMethod] public void It_can_get_and_set_msidmPamCandidates() { // Arrange var list = new List<IdmResource> { new IdmResource { DisplayName = "Test IdmResource1", ObjectID = "guid1" }, new IdmResource { DisplayName = "Test IdmResource2", ObjectID = "guid2" } }; // Act _it.msidmPamCandidates = list; // Assert Assert.AreEqual(list[0].DisplayName, _it.msidmPamCandidates[0].DisplayName); Assert.AreEqual(list[1].DisplayName, _it.msidmPamCandidates[1].DisplayName); } [TestMethod] public void It_has_msidmPamPrivileges_which_is_null_by_default() { // Assert Assert.IsNull(_it.msidmPamPrivileges); } [TestMethod] public void It_has_msidmPamPrivileges_which_can_be_set_back_to_null() { // Arrange var list = new List<IdmResource> { new IdmResource { DisplayName = "Test IdmResource1", ObjectID = "guid1" }, new IdmResource { DisplayName = "Test IdmResource2", ObjectID = "guid2" } }; _it.msidmPamPrivileges = list; // Act _it.msidmPamPrivileges = null; // Assert Assert.IsNull(_it.msidmPamPrivileges); } [TestMethod] public void It_can_get_and_set_msidmPamPrivileges() { // Arrange var list = new List<IdmResource> { new IdmResource { DisplayName = "Test IdmResource1", ObjectID = "guid1" }, new IdmResource { DisplayName = "Test IdmResource2", ObjectID = "guid2" } }; // Act _it.msidmPamPrivileges = list; // Assert Assert.AreEqual(list[0].DisplayName, _it.msidmPamPrivileges[0].DisplayName); Assert.AreEqual(list[1].DisplayName, _it.msidmPamPrivileges[1].DisplayName); } [TestMethod] public void It_can_get_and_set_msidmPamRoleTTL() { // Act _it.msidmPamRoleTTL = 123; // Assert Assert.AreEqual(123, _it.msidmPamRoleTTL); } } }
// 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.CognitiveServices.Vision.Face { using Microsoft.Azure; using Microsoft.Azure.CognitiveServices; using Microsoft.Azure.CognitiveServices.Vision; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for FaceList. /// </summary> public static partial class FaceListExtensions { /// <summary> /// Create an empty face list. Up to 64 face lists are allowed to exist in one /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a particular face list. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> public static void Create(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string)) { operations.CreateAsync(faceListId, name, userData).GetAwaiter().GetResult(); } /// <summary> /// Create an empty face list. Up to 64 face lists are allowed to exist in one /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a particular face list. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateAsync(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.CreateWithHttpMessagesAsync(faceListId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve a face list's information. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> public static GetFaceListResult Get(this IFaceList operations, string faceListId) { return operations.GetAsync(faceListId).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a face list's information. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GetFaceListResult> GetAsync(this IFaceList operations, string faceListId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(faceListId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update information of a face list. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> public static void Update(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string)) { operations.UpdateAsync(faceListId, name, userData).GetAwaiter().GetResult(); } /// <summary> /// Update information of a face list. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IFaceList operations, string faceListId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(faceListId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Delete an existing face list according to faceListId. Persisted face images /// in the face list will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> public static void Delete(this IFaceList operations, string faceListId) { operations.DeleteAsync(faceListId).GetAwaiter().GetResult(); } /// <summary> /// Delete an existing face list according to faceListId. Persisted face images /// in the face list will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IFaceList operations, string faceListId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(faceListId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve information about all existing face lists. Only faceListId, name /// and userData will be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IList<GetFaceListResult> List(this IFaceList operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Retrieve information about all existing face lists. Only faceListId, name /// and userData will be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<GetFaceListResult>> ListAsync(this IFaceList operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete an existing face from a face list (given by a persisitedFaceId and a /// faceListId). Persisted image related to the face will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// faceListId of an existing face list. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of an existing face. /// </param> public static void DeleteFace(this IFaceList operations, string faceListId, string persistedFaceId) { operations.DeleteFaceAsync(faceListId, persistedFaceId).GetAwaiter().GetResult(); } /// <summary> /// Delete an existing face from a face list (given by a persisitedFaceId and a /// faceListId). Persisted image related to the face will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// faceListId of an existing face list. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of an existing face. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteFaceAsync(this IFaceList operations, string faceListId, string persistedFaceId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteFaceWithHttpMessagesAsync(faceListId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Add a face to a face list. The input face is specified as an image with a /// targetFace rectangle. It returns a persistedFaceId representing the added /// face, and persistedFaceId will not expire. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The maximum /// length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the face list, /// in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> public static void AddFace(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string)) { operations.AddFaceAsync(faceListId, userData, targetFace).GetAwaiter().GetResult(); } /// <summary> /// Add a face to a face list. The input face is specified as an image with a /// targetFace rectangle. It returns a persistedFaceId representing the added /// face, and persistedFaceId will not expire. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The maximum /// length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the face list, /// in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddFaceAsync(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddFaceWithHttpMessagesAsync(faceListId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Add a face to a face list. The input face is specified as an image with a /// targetFace rectangle. It returns a persistedFaceId representing the added /// face, and persistedFaceId will not expire. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The maximum /// length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the face list, /// in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> public static void AddFaceFromStream(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string)) { operations.AddFaceFromStreamAsync(faceListId, userData, targetFace).GetAwaiter().GetResult(); } /// <summary> /// Add a face to a face list. The input face is specified as an image with a /// targetFace rectangle. It returns a persistedFaceId representing the added /// face, and persistedFaceId will not expire. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The maximum /// length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the face list, /// in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddFaceFromStreamAsync(this IFaceList operations, string faceListId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddFaceFromStreamWithHttpMessagesAsync(faceListId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Xunit; namespace System.Tests { public static class DateTimeTests { [Fact] public static void MaxValue() { VerifyDateTime(DateTime.MaxValue, 9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Unspecified); } [Fact] public static void MinValue() { VerifyDateTime(DateTime.MinValue, 1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified); } [Fact] public static void Ctor_Long() { VerifyDateTime(new DateTime(999999999999999999), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Unspecified); } [Fact] public static void Ctor_Long_InvalidTicks_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MinValue.Ticks - 1)); // Ticks < DateTime.MinValue.Ticks AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MaxValue.Ticks + 1)); // Ticks > DateTime.MaxValue.Ticks } [Fact] public static void Ctor_Long_DateTimeKind() { VerifyDateTime(new DateTime(999999999999999999, DateTimeKind.Utc), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Utc); } [Fact] public static void Ctor_Long_DateTimeKind_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MinValue.Ticks - 1, DateTimeKind.Utc)); // Ticks < DateTime.MinValue.Ticks AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MaxValue.Ticks + 1, DateTimeKind.Utc)); // Ticks > DateTime.MaxValue.Ticks AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, DateTimeKind.Unspecified - 1)); // Invalid date time kind AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, DateTimeKind.Local + 1)); // Invalid date time kind } [Fact] public static void Ctor_Int_Int_Int() { var dateTime = new DateTime(2012, 6, 11); VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified); } [Fact] public static void Ctor_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1)); // Year < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1)); // Year > 9999 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1)); // Month < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1)); // Month > 12 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0)); // Day < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32)); // Day > days in month } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int() { var dateTime = new DateTime(2012, 12, 31, 13, 50, 10); VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1)); // Year < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1)); // Year > 9999 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1)); // Month < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1)); // Month > 12 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1)); // Day < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1)); // Day > days in month AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1)); // Hour < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1)); // Hour > 23 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1)); // Minute < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1)); // Minute > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1)); // Second < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60)); // Second > 59 } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Int_DateTimeKind() { var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local); VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 0, DateTimeKind.Local); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_DateTimeKind_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year > 9999 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, DateTimeKind.Utc)); // Month < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, DateTimeKind.Utc)); // Month > 12 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, DateTimeKind.Utc)); // Day < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, DateTimeKind.Utc)); // Day > days in month AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, DateTimeKind.Utc)); // Hour < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, DateTimeKind.Utc)); // Hour > 23 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, DateTimeKind.Utc)); // Minute < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, DateTimeKind.Utc)); // Minute > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, DateTimeKind.Utc)); // Second < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, DateTimeKind.Utc)); // Second > 59 AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, DateTimeKind.Unspecified - 1)); // Invalid date time kind AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, DateTimeKind.Local + 1)); // Invalid date time kind } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Int() { var dateTime = new DateTime(1973, 10, 6, 14, 30, 0, 500); VerifyDateTime(dateTime, 1973, 10, 6, 14, 30, 0, 500, DateTimeKind.Unspecified); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, 1)); // Year < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, 1)); // Year > 9999 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, 1)); // Month < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, 1)); // Month > 12 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, 1)); // Day < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, 1)); // Day > days in month AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, 1)); // Hour < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, 1)); // Hour > 23 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, 1)); // Minute < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, 1)); // Minute > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, 1)); // Second < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, 1)); // Second > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, -1)); // Milisecond < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, 1000)); // Millisecond > 999 } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_DateTimeKind() { var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, 600, DateTimeKind.Local); VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 600, DateTimeKind.Local); } [Fact] public static void Ctor_Int_Int_Int_Int_Int_Int_Int_DateTimeKind_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year > 9999 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Month < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Month > 12 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, 1, DateTimeKind.Utc)); // Day < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, 1, DateTimeKind.Utc)); // Day > days in month AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, 1, DateTimeKind.Utc)); // Hour < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, 1, DateTimeKind.Utc)); // Hour > 23 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, 1, DateTimeKind.Utc)); // Minute < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, 1, DateTimeKind.Utc)); // Minute > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, 1, DateTimeKind.Utc)); // Second < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, 1, DateTimeKind.Utc)); // Second > 59 AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, -1, DateTimeKind.Utc)); // Millisecond < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, 1000, DateTimeKind.Utc)); // Millisecond > 999 AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, DateTimeKind.Unspecified - 1)); // Invalid date time kind AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, DateTimeKind.Local + 1)); // Invalid date time kind } [Theory] [InlineData(2004, true)] [InlineData(2005, false)] public static void IsLeapYear(int year, bool expected) { Assert.Equal(expected, DateTime.IsLeapYear(year)); } [Fact] public static void IsLeapYear_InvalidYear_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(10000)); } public static IEnumerable<object[]> Add_TimeSpan_TestData() { yield return new object[] { new DateTime(1000), new TimeSpan(10), new DateTime(1010) }; yield return new object[] { new DateTime(1000), TimeSpan.Zero, new DateTime(1000) }; yield return new object[] { new DateTime(1000), new TimeSpan(-10), new DateTime(990) }; } [Theory] [MemberData(nameof(Add_TimeSpan_TestData))] public static void Add_TimeSpan(DateTime dateTime, TimeSpan timeSpan, DateTime expected) { Assert.Equal(expected, dateTime.Add(timeSpan)); } [Fact] public static void Add_TimeSpan_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.Add(TimeSpan.FromTicks(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.Add(TimeSpan.FromTicks(11))); } public static IEnumerable<object[]> AddYears_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1996, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1976, 8, 15, 10, 20, 5, 70) }; } [Theory] [MemberData(nameof(AddYears_TestData))] public static void AddYears(DateTime dateTime, int years, DateTime expected) { Assert.Equal(expected, dateTime.AddYears(years)); } [Fact] public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTime.Now.AddYears(10001)); AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTime.Now.AddYears(-10001)); AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MaxValue.AddYears(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MinValue.AddYears(-1)); } public static IEnumerable<object[]> AddMonths_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 10, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 6, 15, 10, 20, 5, 70) }; } [Theory] [MemberData(nameof(AddMonths_TestData))] public static void AddMonths(DateTime dateTime, int months, DateTime expected) { Assert.Equal(expected, dateTime.AddMonths(months)); } [Fact] public static void AddMonths_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.Now.AddMonths(120001)); AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.Now.AddMonths(-120001)); AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MaxValue.AddMonths(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MinValue.AddMonths(-1)); } public static IEnumerable<object[]> AddDays_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 8, 13, 10, 20, 5, 70) }; } [Theory] [MemberData(nameof(AddDays_TestData))] public static void AddDays(DateTime dateTime, double days, DateTime expected) { Assert.Equal(expected, dateTime.AddDays(days)); } [Fact] public static void AddDays_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddDays(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddDays(-1)); } public static IEnumerable<object[]> AddHours_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 3, new DateTime(1986, 8, 15, 13, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 7, 20, 5, 70) }; } [Theory] [MemberData(nameof(AddHours_TestData))] public static void AddHours(DateTime dateTime, double hours, DateTime expected) { Assert.Equal(expected, dateTime.AddHours(hours)); } [Fact] public static void AddHours_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddHours(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddHours(-1)); } public static IEnumerable<object[]> AddMinutes_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 5, new DateTime(1986, 8, 15, 10, 25, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -5, new DateTime(1986, 8, 15, 10, 15, 5, 70) }; } [Theory] [MemberData(nameof(AddMinutes_TestData))] public static void AddMinutes(DateTime dateTime, double minutes, DateTime expected) { Assert.Equal(expected, dateTime.AddMinutes(minutes)); } [Fact] public static void AddMinutes_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddMinutes(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddMinutes(-1)); } public static IEnumerable<object[]> AddSeconds_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 30, new DateTime(1986, 8, 15, 10, 20, 35, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 10, 20, 2, 70) }; } [Theory] [MemberData(nameof(AddSeconds_TestData))] public static void AddSeconds(DateTime dateTime, double seconds, DateTime expected) { Assert.Equal(expected, dateTime.AddSeconds(seconds)); } [Fact] public static void AddSeconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddSeconds(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddSeconds(-1)); } public static IEnumerable<object[]> AddMilliseconds_TestData() { yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1986, 8, 15, 10, 20, 5, 80) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) }; yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1986, 8, 15, 10, 20, 5, 60) }; } [Theory] [MemberData(nameof(AddMilliseconds_TestData))] public static void AddMilliseconds(DateTime dateTime, double milliseconds, DateTime expected) { Assert.Equal(expected, dateTime.AddMilliseconds(milliseconds)); } [Fact] public static void AddMilliseconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddMilliseconds(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddMilliseconds(-1)); } public static IEnumerable<object[]> AddTicks_TestData() { yield return new object[] { new DateTime(1000), 10, new DateTime(1010) }; yield return new object[] { new DateTime(1000), 0, new DateTime(1000) }; yield return new object[] { new DateTime(1000), -10, new DateTime(990) }; } [Theory] [MemberData(nameof(AddTicks_TestData))] public static void AddTicks(DateTime dateTime, long ticks, DateTime expected) { Assert.Equal(expected, dateTime.AddTicks(ticks)); } [Fact] public static void AddTicks_NewDateOutOfRange_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddTicks(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddTicks(-1)); } [Fact] public static void DayOfWeekTest() { var dateTime = new DateTime(2012, 6, 18); Assert.Equal(DayOfWeek.Monday, dateTime.DayOfWeek); } [Fact] public static void DayOfYear() { var dateTime = new DateTime(2012, 6, 18); Assert.Equal(170, dateTime.DayOfYear); } [Fact] public static void TimeOfDay() { var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0); TimeSpan ts = dateTime.TimeOfDay; DateTime newDate = dateTime.Subtract(ts); Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks); Assert.Equal(dateTime.Ticks, newDate.Add(ts).Ticks); } [Fact] public static void Today() { DateTime today = DateTime.Today; DateTime now = DateTime.Now; VerifyDateTime(today, now.Year, now.Month, now.Day, 0, 0, 0, 0, DateTimeKind.Local); today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc); Assert.Equal(DateTimeKind.Utc, today.Kind); Assert.False(today.IsDaylightSavingTime()); } [Fact] public static void Conversion() { DateTime today = DateTime.Today; long dateTimeRaw = today.ToBinary(); Assert.Equal(today, DateTime.FromBinary(dateTimeRaw)); dateTimeRaw = today.ToUniversalTime().ToBinary(); Assert.Equal(today.ToUniversalTime(), DateTime.FromBinary(dateTimeRaw)); dateTimeRaw = today.ToFileTime(); Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw)); dateTimeRaw = today.ToFileTimeUtc(); Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime()); } public static IEnumerable<object[]> Subtract_TimeSpan_TestData() { var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc); yield return new object[] { dateTime, new TimeSpan(10, 5, 1), new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc) }; yield return new object[] { dateTime, new TimeSpan(-10, -5, -1), new DateTime(2012, 6, 18, 20, 10, 2, 0, DateTimeKind.Utc) }; } [Theory] [MemberData(nameof(Subtract_TimeSpan_TestData))] public static void Subtract_TimeSpan(DateTime dateTime, TimeSpan timeSpan, DateTime expected) { Assert.Equal(expected, dateTime - timeSpan); Assert.Equal(expected, dateTime.Subtract(timeSpan)); } public static IEnumerable<object[]> Subtract_DateTime_TestData() { var dateTime1 = new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc); var dateTime2 = new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc); var dateTime3 = new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc); yield return new object[] { dateTime2, dateTime1, new TimeSpan(185, 14, 47, 0) }; yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) }; yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) }; } [Theory] [MemberData(nameof(Subtract_DateTime_TestData))] public static void Subtract_DateTime(DateTime dateTime1, DateTime dateTime2, TimeSpan expected) { Assert.Equal(expected, dateTime1 - dateTime2); Assert.Equal(expected, dateTime1.Subtract(dateTime2)); } [Fact] public static void Subtract_DateTime_Invalid() { DateTime date1 = DateTime.MinValue.ToLocalTime(); Assert.Throws<ArgumentOutOfRangeException>(() => date1.Subtract(new TimeSpan(365, 0, 0, 0))); DateTime date2 = DateTime.MaxValue.ToLocalTime(); Assert.Throws<ArgumentOutOfRangeException>(() => date2.Subtract(new TimeSpan(-365, 0, 0, 0))); } [Fact] public static void Parse_String() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString(); DateTime result = DateTime.Parse(expectedString); Assert.Equal(expectedString, result.ToString()); } [Fact] public static void Parse_String_FormatProvider() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString(); DateTime result = DateTime.Parse(expectedString, null); Assert.Equal(expectedString, result.ToString()); } [Fact] public static void Parse_String_FormatProvider_DateTimeStyles() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString(); DateTime result = DateTime.Parse(expectedString, null, DateTimeStyles.None); Assert.Equal(expectedString, result.ToString()); } [Fact] public static void Parse_Japanese() { var expected = new DateTime(2012, 12, 21, 10, 8, 6); var cultureInfo = new CultureInfo("ja-JP"); string expectedString = string.Format(cultureInfo, "{0}", expected); Assert.Equal(expected, DateTime.Parse(expectedString, cultureInfo)); } [Fact] public static void Parse_NullString_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault)); } [Fact] public static void TryParse_String() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); DateTime result; Assert.True(DateTime.TryParse(expectedString, out result)); Assert.Equal(expectedString, result.ToString("g")); } [Fact] public static void TryParse_String_FormatProvider_DateTimeStyles_U() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("u"); DateTime result; Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result)); Assert.Equal(expectedString, result.ToString("u")); } [Fact] public static void TryParse_String_FormatProvider_DateTimeStyles_G() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); DateTime result; Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result)); Assert.Equal(expectedString, result.ToString("g")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET framework has a bug and incorrectly parses this date")] public static void TryParse_TimeDesignators_NetCore() { DateTime result; Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(5, result.Hour); Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(17, result.Hour); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr fixed a bug where the .NET framework incorrectly parses this date")] public static void TryParse_TimeDesignators_Netfx() { DateTime result; Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(DateTime.Now.Month, result.Month); Assert.Equal(DateTime.Now.Day, result.Day); Assert.Equal(4, result.Hour); Assert.Equal(0, result.Minute); Assert.Equal(0, result.Second); Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(DateTime.Now.Month, result.Month); Assert.Equal(DateTime.Now.Day, result.Day); Assert.Equal(16, result.Hour); Assert.Equal(0, result.Minute); Assert.Equal(0, result.Second); } [Fact] public static void ParseExact_String_String_FormatProvider() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("G"); DateTime result = DateTime.ParseExact(expectedString, "G", null); Assert.Equal(expectedString, result.ToString("G")); } [Fact] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_U() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("u"); DateTime result = DateTime.ParseExact(expectedString, "u", null, DateTimeStyles.None); Assert.Equal(expectedString, result.ToString("u")); } [Fact] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_G() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); DateTime result = DateTime.ParseExact(expectedString, "g", null, DateTimeStyles.None); Assert.Equal(expectedString, result.ToString("g")); } [Theory] [MemberData(nameof(Format_String_TestData_O))] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O(DateTime dt, string expected) { string actual = dt.ToString("o"); Assert.Equal(expected, actual); DateTime result = DateTime.ParseExact(actual, "o", null, DateTimeStyles.None); Assert.Equal(expected, result.ToString("o")); } public static IEnumerable<object[]> Format_String_TestData_O() { yield return new object[] { DateTime.MaxValue, "9999-12-31T23:59:59.9999999" }; yield return new object[] { DateTime.MinValue, "0001-01-01T00:00:00.0000000" }; yield return new object[] { new DateTime(1906, 8, 15, 7, 24, 5, 300), "1906-08-15T07:24:05.3000000" }; } [Theory] [MemberData(nameof(Format_String_TestData_R))] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R(DateTime dt, string expected) { string actual = dt.ToString("r"); Assert.Equal(expected, actual); DateTime result = DateTime.ParseExact(actual, "r", null, DateTimeStyles.None); Assert.Equal(expected, result.ToString("r")); } public static IEnumerable<object[]> Format_String_TestData_R() { yield return new object[] { DateTime.MaxValue, "Fri, 31 Dec 9999 23:59:59 GMT" }; yield return new object[] { DateTime.MinValue, "Mon, 01 Jan 0001 00:00:00 GMT" }; yield return new object[] { new DateTime(1906, 8, 15, 7, 24, 5, 300), "Wed, 15 Aug 1906 07:24:05 GMT" }; } [Fact] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("r"); DateTime result = DateTime.ParseExact(expectedString, "r", null, DateTimeStyles.None); Assert.Equal(expectedString, result.ToString("r")); } [Fact] public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider() { var formatter = new MyFormatter(); string dateBefore = DateTime.Now.ToString(); DateTime dateAfter = DateTime.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AdjustToUniversal); Assert.Equal(dateBefore, dateAfter.ToString()); } [Fact] public static void ParseExact_String_StringArray_FormatProvider_DateTimeStyles() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); var formats = new string[] { "g" }; DateTime result = DateTime.ParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal); Assert.Equal(expectedString, result.ToString("g")); } [Fact] public static void TryParseExact_String_String_FormatProvider_DateTimeStyles_NullFormatProvider() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); DateTime resulted; Assert.True(DateTime.TryParseExact(expectedString, "g", null, DateTimeStyles.AdjustToUniversal, out resulted)); Assert.Equal(expectedString, resulted.ToString("g")); } [Fact] public static void TryParseExact_String_StringArray_FormatProvider_DateTimeStyles() { DateTime expected = DateTime.MaxValue; string expectedString = expected.ToString("g"); var formats = new string[] { "g" }; DateTime result; Assert.True(DateTime.TryParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal, out result)); Assert.Equal(expectedString, result.ToString("g")); } public static void ParseExact_EscapedSingleQuotes() { var formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("mt-MT")); const string format = @"dddd, d' ta\' 'MMMM yyyy"; DateTime expected = new DateTime(1999, 2, 28, 17, 00, 01); string formatted = expected.ToString(format, formatInfo); DateTime actual = DateTime.ParseExact(formatted, format, formatInfo); Assert.Equal(expected.Date, actual.Date); } [Theory] [InlineData("fi-FI")] [InlineData("nb-NO")] [InlineData("nb-SJ")] [InlineData("sr-Cyrl-XK")] [InlineData("sr-Latn-ME")] [InlineData("sr-Latn-RS")] [InlineData("sr-Latn-XK")] public static void Parse_SpecialCultures(string cultureName) { // Test DateTime parsing with cultures which has the date separator and time separator are same CultureInfo cultureInfo; try { cultureInfo = new CultureInfo(cultureName); } catch (CultureNotFoundException) { // Ignore un-supported culture in current platform return; } var dateTime = new DateTime(2015, 11, 20, 11, 49, 50); string dateString = dateTime.ToString(cultureInfo.DateTimeFormat.ShortDatePattern, cultureInfo); DateTime parsedDate; Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate)); if (cultureInfo.DateTimeFormat.ShortDatePattern.Contains("yyyy") || HasDifferentDateTimeSeparators(cultureInfo.DateTimeFormat)) { Assert.Equal(dateTime.Date, parsedDate); } else { // When the date separator and time separator are the same, DateTime.TryParse cannot // tell the difference between a short date like dd.MM.yy and a short time // like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time // and uses the current date to construct the date time. DateTime now = DateTime.Now; Assert.Equal(new DateTime(now.Year, now.Month, now.Day, dateTime.Day, dateTime.Month, dateTime.Year % 100), parsedDate); } dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongDatePattern, cultureInfo); Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate)); Assert.Equal(dateTime.Date, parsedDate); dateString = dateTime.ToString(cultureInfo.DateTimeFormat.FullDateTimePattern, cultureInfo); Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate)); Assert.Equal(dateTime, parsedDate); dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongTimePattern, cultureInfo); Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate)); Assert.Equal(dateTime.TimeOfDay, parsedDate.TimeOfDay); } private static bool HasDifferentDateTimeSeparators(DateTimeFormatInfo dateTimeFormat) { // Since .NET Core doesn't expose DateTimeFormatInfo DateSeparator and TimeSeparator properties, // this method gets the separators using DateTime.ToString by passing in the invariant separators. // The invariant separators will then get turned into the culture's separators by ToString, // which are then compared. var dateTime = new DateTime(2015, 11, 24, 17, 57, 29); string separators = dateTime.ToString("/@:", dateTimeFormat); int delimiterIndex = separators.IndexOf('@'); string dateSeparator = separators.Substring(0, delimiterIndex); string timeSeparator = separators.Substring(delimiterIndex + 1); return dateSeparator != timeSeparator; } [Fact] public static void GetDateTimeFormats() { var allStandardFormats = new char[] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; var dateTime = new DateTime(2009, 7, 28, 5, 23, 15); var formats = new List<string>(); foreach (char format in allStandardFormats) { string[] dates = dateTime.GetDateTimeFormats(format); Assert.True(dates.Length > 0); DateTime parsedDate; Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate)); formats.AddRange(dates); } List<string> actualFormats = dateTime.GetDateTimeFormats().ToList(); Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t)); actualFormats = dateTime.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList(); Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t)); } [Fact] public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat() { var dateTime = new DateTime(2009, 7, 28, 5, 23, 15); Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format } private static void VerifyDateTime(DateTime dateTime, int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) { Assert.Equal(year, dateTime.Year); Assert.Equal(month, dateTime.Month); Assert.Equal(day, dateTime.Day); Assert.Equal(hour, dateTime.Hour); Assert.Equal(minute, dateTime.Minute); Assert.Equal(second, dateTime.Second); Assert.Equal(millisecond, dateTime.Millisecond); Assert.Equal(kind, dateTime.Kind); } private class MyFormatter : IFormatProvider { public object GetFormat(Type formatType) { return typeof(IFormatProvider) == formatType ? this : null; } } [Fact] public static void InvalidDateTimeStyles() { string strDateTime = "Thursday, August 31, 2006 1:14"; string[] formats = new string[] { "f" }; IFormatProvider provider = new CultureInfo("en-US"); DateTimeStyles style = DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal; Assert.Throws<ArgumentException>(() => DateTime.ParseExact(strDateTime, formats, provider, style)); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookRangeFormatRequest. /// </summary> public partial class WorkbookRangeFormatRequest : BaseRequest, IWorkbookRangeFormatRequest { /// <summary> /// Constructs a new WorkbookRangeFormatRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookRangeFormatRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookRangeFormat using POST. /// </summary> /// <param name="workbookRangeFormatToCreate">The WorkbookRangeFormat to create.</param> /// <returns>The created WorkbookRangeFormat.</returns> public System.Threading.Tasks.Task<WorkbookRangeFormat> CreateAsync(WorkbookRangeFormat workbookRangeFormatToCreate) { return this.CreateAsync(workbookRangeFormatToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookRangeFormat using POST. /// </summary> /// <param name="workbookRangeFormatToCreate">The WorkbookRangeFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookRangeFormat.</returns> public async System.Threading.Tasks.Task<WorkbookRangeFormat> CreateAsync(WorkbookRangeFormat workbookRangeFormatToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookRangeFormat>(workbookRangeFormatToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookRangeFormat. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookRangeFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookRangeFormat>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookRangeFormat. /// </summary> /// <returns>The WorkbookRangeFormat.</returns> public System.Threading.Tasks.Task<WorkbookRangeFormat> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookRangeFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookRangeFormat.</returns> public async System.Threading.Tasks.Task<WorkbookRangeFormat> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookRangeFormat>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookRangeFormat using PATCH. /// </summary> /// <param name="workbookRangeFormatToUpdate">The WorkbookRangeFormat to update.</param> /// <returns>The updated WorkbookRangeFormat.</returns> public System.Threading.Tasks.Task<WorkbookRangeFormat> UpdateAsync(WorkbookRangeFormat workbookRangeFormatToUpdate) { return this.UpdateAsync(workbookRangeFormatToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookRangeFormat using PATCH. /// </summary> /// <param name="workbookRangeFormatToUpdate">The WorkbookRangeFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookRangeFormat.</returns> public async System.Threading.Tasks.Task<WorkbookRangeFormat> UpdateAsync(WorkbookRangeFormat workbookRangeFormatToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookRangeFormat>(workbookRangeFormatToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeFormatRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeFormatRequest Expand(Expression<Func<WorkbookRangeFormat, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeFormatRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookRangeFormatRequest Select(Expression<Func<WorkbookRangeFormat, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookRangeFormatToInitialize">The <see cref="WorkbookRangeFormat"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookRangeFormat workbookRangeFormatToInitialize) { if (workbookRangeFormatToInitialize != null && workbookRangeFormatToInitialize.AdditionalData != null) { if (workbookRangeFormatToInitialize.Borders != null && workbookRangeFormatToInitialize.Borders.CurrentPage != null) { workbookRangeFormatToInitialize.Borders.AdditionalData = workbookRangeFormatToInitialize.AdditionalData; object nextPageLink; workbookRangeFormatToInitialize.AdditionalData.TryGetValue("borders@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookRangeFormatToInitialize.Borders.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
#region About and License //======================================================================= // Copyright Andrew Szot 2015. // Distributed under the MIT License. // (See accompanying file LICENSE.txt) //======================================================================= #endregion using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Xml; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Henge3D; using Henge3D.Physics; namespace Game_Physics_Editor { /// <summary> /// The main game responsible for rendering everything to the screen, /// managing user interaction through the camera, user input, and the /// bounding box data. /// </summary> public class MainGame : Microsoft.Xna.Framework.Game { private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; private LineRenderer _lineRenderer; private Camera _cam; private Input _input; /// <summary> /// The model filename of the model the user has opened. /// </summary> private string s_modelFilename; /// <summary> /// The save folder for the physics data. /// </summary> private string s_saveLocation; private Model _model; private bool b_renderWireframe = false; private RasterizerState _wireframe; private List<BoundingBox> _gameBBs = new List<BoundingBox>(); public List<BoundingBox> GameBBs { get { return _gameBBs; } set { _gameBBs = value; } } public bool RenderWireFrame { get { return b_renderWireframe; } set { b_renderWireframe = value; } } public MainGame(string modelFilename, string saveLocation) { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.SynchronizeWithVerticalRetrace = true; s_modelFilename = modelFilename; s_saveLocation = saveLocation; } protected override void Initialize() { base.Initialize(); _cam = new Camera(); _cam.SetDefault(GraphicsDevice.Viewport); _cam.Pitch = MathHelper.PiOver4; _cam.Yaw = 0f; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); _model = Content.Load<Model>(s_modelFilename); _input = new Input(this); _lineRenderer = new LineRenderer(); _wireframe = new RasterizerState(); _wireframe.FillMode = FillMode.WireFrame; } protected override void UnloadContent() { } /// <summary> /// Save all of the physics bounding box data to the save location specified earlier by the user. /// </summary> /// <returns>Whether the save was successful.</returns> public bool SaveData() { string filename = Path.Combine(s_saveLocation, s_modelFilename + "_Physics.xml"); try { // This writes out the data the same way the Wumpus Game Engine Reads in the data. using (FileStream fs = File.Create(filename)) { using (XmlWriter writer = XmlWriter.Create(fs)) { writer.WriteStartDocument(); writer.WriteStartElement("BoundingBoxes"); foreach (BoundingBox bb in _gameBBs) { writer.WriteStartElement("BoundingBox"); writer.WriteStartElement("Min"); writer.WriteElementString("X", bb.Min.X.ToString()); writer.WriteElementString("Y", bb.Min.Y.ToString()); writer.WriteElementString("Z", bb.Min.Z.ToString()); writer.WriteEndElement(); writer.WriteStartElement("Max"); writer.WriteElementString("X", bb.Max.X.ToString()); writer.WriteElementString("Y", bb.Max.Y.ToString()); writer.WriteElementString("Z", bb.Max.Z.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); } } } catch (Exception e) { return false; } return true; } /// <summary> /// Update the camera movement and whether the user wants to create the physics editor form. /// </summary> /// <param name="gameTime"></param> protected override void Update(GameTime gameTime) { base.Update(gameTime); Vector3 moveVec = Vector3.Zero; // Camera movement. if (_input.KeyboardState.IsKeyDown(Keys.W)) moveVec += Vector3.UnitZ; if (_input.KeyboardState.IsKeyDown(Keys.A)) moveVec += Vector3.UnitX; if (_input.KeyboardState.IsKeyDown(Keys.D)) moveVec += -Vector3.UnitX; if (_input.KeyboardState.IsKeyDown(Keys.S)) moveVec += -Vector3.UnitZ; if (_input.KeyboardState.IsKeyDown(Keys.Escape)) this.Exit(); // Form creation input. foreach (var key in _input.KeysPressed) { switch (key) { case Keys.B: PhysicsEditorForm pef = new PhysicsEditorForm(this); pef.Show(); break; } } // Camera update. float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; _cam.Move(moveVec, 10f, dt); _cam.Update(gameTime); Vector2 yawPitch = new Vector2(_input.MouseDelta.X, -_input.MouseDelta.Y); yawPitch *= _input.MouseSensitivity; if (yawPitch != Vector2.Zero) { _cam.Yaw -= yawPitch.X; _cam.Pitch += yawPitch.Y; } if (_input.MouseState.RightButton == ButtonState.Pressed) _input.CaptureMouse = true; else _input.CaptureMouse = false; } /// <summary> /// Draw the model and the bounding boxes to the screen. /// </summary> /// <param name="gameTime"></param> protected override void Draw(GameTime gameTime) { // Changing this value will change the background color in the scene. GraphicsDevice.Clear(Color.CornflowerBlue); // The light direction can also be changed for more pleasant viewing. Vector3 lightDir = new Vector3(-1f, -1f, -1f); lightDir.Normalize(); base.Draw(gameTime); if (b_renderWireframe) GraphicsDevice.RasterizerState = _wireframe; else GraphicsDevice.RasterizerState = RasterizerState.CullClockwise; // Render the mesh. foreach (var mesh in _model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = Matrix.Identity; effect.View = _cam.View; effect.Projection = _cam.Proj; effect.DiffuseColor = new Vector3(0.6f); effect.EnableDefaultLighting(); } mesh.Draw(); } // Draw the bounding boxes. Vector3 color = Color.Red.ToVector3(); foreach (BoundingBox bb in _gameBBs) { Vector3 mx = bb.Max; Vector3 mn = bb.Min; Vector3 p0 = mn; Vector3 p1 = new Vector3(mn.X, mn.Y, mx.Z); Vector3 p2 = new Vector3(mn.X, mx.Y, mn.Z); Vector3 p3 = new Vector3(mx.X, mn.Y, mn.Z); Vector3 p4 = mx; Vector3 p5 = new Vector3(mx.X, mx.Y, mn.Z); Vector3 p6 = new Vector3(mx.X, mn.Y, mx.Z); Vector3 p7 = new Vector3(mn.X, mx.Y, mx.Z); _lineRenderer.Draw(GraphicsDevice, p0, p1, _cam, color); _lineRenderer.Draw(GraphicsDevice, p0, p2, _cam, color); _lineRenderer.Draw(GraphicsDevice, p0, p3, _cam, color); _lineRenderer.Draw(GraphicsDevice, p1, p6, _cam, color); _lineRenderer.Draw(GraphicsDevice, p1, p7, _cam, color); _lineRenderer.Draw(GraphicsDevice, p2, p7, _cam, color); _lineRenderer.Draw(GraphicsDevice, p2, p5, _cam, color); _lineRenderer.Draw(GraphicsDevice, p3, p5, _cam, color); _lineRenderer.Draw(GraphicsDevice, p3, p6, _cam, color); _lineRenderer.Draw(GraphicsDevice, p4, p6, _cam, color); _lineRenderer.Draw(GraphicsDevice, p4, p7, _cam, color); _lineRenderer.Draw(GraphicsDevice, p4, p5, _cam, color); _lineRenderer.Draw(GraphicsDevice, p3, p5, _cam, color); _lineRenderer.Draw(GraphicsDevice, p0, p1, _cam, color); } } } }
/* * GridLayout.cs - Implementation of the * "System.Windows.Forms.GridLayout" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System.Drawing; // This is a special-purpose control that lays out its children in a grid. // It is intended for use inside dialog box controls like "FileDialog". internal class GridLayout : Control, IRecommendedSize { // Internal state. private int columns; private int rows; private int stretchColumn; private int stretchRow; private int margin; private int colSpacing; private int rowSpacing; private Control[] children; // Constructor. public GridLayout(int columns, int rows) { this.columns = columns; this.rows = rows; this.stretchColumn = columns - 1; this.stretchRow = rows - 1; this.margin = 4; this.colSpacing = 4; this.rowSpacing = 4; this.children = new Control [columns * rows]; this.TabStop = false; } // Get or set the column to be stretched. public int StretchColumn { get { return stretchColumn; } set { stretchColumn = value; } } // Get or set the row to be stretched. public int StretchRow { get { return stretchRow; } set { stretchRow = value; } } // Get or set the margin. public int Margin { get { return margin; } set { margin = value; } } // Get or set the spacing between columns. public int ColumnSpacing { get { return colSpacing; } set { colSpacing = value; } } // Get or set the spacing between rows. public int RowSpacing { get { return rowSpacing; } set { rowSpacing = value; } } // Get the child control at a particular location. public Control GetControl(int column, int row) { return children[column * rows + row]; } // Set the child control at a particular location. Locations can be blank. public void SetControl(int column, int row, Control child) { if(child.Parent != this) { Controls.Add(child); } children[column * rows + row] = child; } // Get the recommended client size for this control. public Size RecommendedSize { get { int width = 0; int height = 0; int maxWidth; int maxHeight; int xextra, yextra; Size childSize; int x, y; Control child; // Scan the columns, looking for maximums. for(x = 0; x < columns; ++x) { maxWidth = 0; for(y = 0; y < rows; ++y) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Width > maxWidth) { maxWidth = childSize.Width; } } } width += maxWidth; } // Scan the rows, looking for maximums. for(y = 0; y < rows; ++y) { maxHeight = 0; for(x = 0; x < columns; ++x) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Height > maxHeight) { maxHeight = childSize.Height; } } } height += maxHeight; } // Add the margins and return the final size. xextra = margin * 2; if(columns >= 2) { xextra += (columns - 1) * colSpacing; } yextra = margin * 2; if(rows >= 2) { yextra += (rows - 1) * rowSpacing; } return new Size(width + xextra, height + yextra); } } // Lay out the children in this control. protected override void OnLayout(LayoutEventArgs e) { int[] columnOffsets = new int [columns]; int[] columnWidths = new int [columns]; int[] rowOffsets = new int [rows]; int[] rowHeights = new int [rows]; int x, y; Control child; int posnLower, posnUpper; Size childSize; // Compute the offset and width of all columns. posnLower = margin; posnUpper = ClientSize.Width - margin; for(x = 0; x < stretchColumn; ++x) { columnOffsets[x] = posnLower; columnWidths[x] = 0; for(y = 0; y < rows; ++y) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Width > columnWidths[x]) { columnWidths[x] = childSize.Width; } } } posnLower += columnWidths[x] + colSpacing; } for(x = columns - 1; x > stretchColumn; --x) { columnWidths[x] = 0; for(y = 0; y < rows; ++y) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Width > columnWidths[x]) { columnWidths[x] = childSize.Width; } } } posnUpper -= columnWidths[x]; columnOffsets[x] = posnUpper; posnUpper -= colSpacing; } columnOffsets[stretchColumn] = posnLower; columnWidths[stretchColumn] = posnUpper - posnLower; // Compute the offset and height of all rows. posnLower = margin; posnUpper = ClientSize.Height - margin; for(y = 0; y < stretchRow; ++y) { rowOffsets[y] = posnLower; rowHeights[y] = 0; for(x = 0; x < columns; ++x) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Height > rowHeights[y]) { rowHeights[y] = childSize.Height; } } } posnLower += rowHeights[y] + rowSpacing; } for(y = rows - 1; y > stretchRow; --y) { rowHeights[y] = 0; for(x = 0; x < columns; ++x) { child = GetControl(x, y); if(child != null && child.visible) { childSize = HBoxLayout.GetRecommendedSize(child); if(childSize.Height > rowHeights[y]) { rowHeights[y] = childSize.Height; } } } posnUpper -= rowHeights[y]; rowOffsets[y] = posnUpper; posnUpper -= rowSpacing; } rowOffsets[stretchRow] = posnLower; rowHeights[stretchRow] = posnUpper - posnLower; // Place the controls in their final locations. for(y = 0; y < rows; ++y) { for(x = 0; x < columns; ++x) { child = GetControl(x, y); if(child != null && child.visible) { child.SetBounds (columnOffsets[x], rowOffsets[y], columnWidths[x], rowHeights[y]); } } } } }; // class GridLayout }; // namespace System.Windows.Forms
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported(bool useSafeHandle) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { if (useSafeHandle) { _ = s.SafeHandle; } else { _ = s.Handle; } Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_StringHost_ExposedHandle_NotSupported(bool useSafeHandle) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { if (useSafeHandle) { _ = s.SafeHandle; } else { _ = s.Handle; } Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported(bool useSafeHandle) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { if (useSafeHandle) { _ = s.SafeHandle; } else { _ = s.Handle; } Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported(bool useSafeHandle) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { if (useSafeHandle) { _ = s.SafeHandle; } else { _ = s.Handle; } Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Theory] [InlineData(true)] [InlineData(false)] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported(bool useSafeHandle) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { if (useSafeHandle) { _ = s.SafeHandle; } else { _ = s.Handle; } Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void Connect_ConnectTwice_NotSupported(int invalidatingAction) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction) { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); }); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); }); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); }); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); }); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { // Unlike other tests that reuse a static Socket instance, this test avoids doing so // to work around a behavior of .NET 4.7.2. See https://github.com/dotnet/corefx/issues/29481 // for more details. using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<NotSupportedException>(() => s.BeginConnect( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); } using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<NotSupportedException>(() => { s.ConnectAsync( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); }); } } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); }); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); }); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); }); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); }); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); }); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("addresses", () => { GetSocket().ConnectAsync(new IPAddress[0], 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); }); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); }); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void EndConnect_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndConnect(Task.CompletedTask)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void EndSend_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSend(Task.CompletedTask)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); }); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); }); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void EndSendto_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSendTo(Task.CompletedTask)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("endPoint", () => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using UnityEngine; using Kinect; public class KinectSensor : MonoBehaviour, KinectInterface { //make KinectSensor a singleton (sort of) private static KinectInterface instance=null; public static KinectInterface Instance { get { if (instance == null) throw new Exception("There needs to be an active instance of the KinectSensor component."); return instance; } private set { instance = value; } } /// <summary> /// how high (in meters) off the ground is the sensor /// </summary> public float sensorHeight; /// <summary> /// where (relative to the ground directly under the sensor) should the kinect register as 0,0,0 /// </summary> public Vector3 kinectCenter; /// <summary> /// what point (relative to kinectCenter) should the sensor look at /// </summary> public Vector4 lookAt; /// <summary> /// Variables used to pass to smoothing function. Values are set to default based on Action in Motion's Research /// </summary> public float smoothing =0.5f; public float correction=0.5f; public float prediction=0.5f; public float jitterRadius=0.05f; public float maxDeviationRadius=0.04f; //public bool enableNearMode = false; /// <summary> ///variables used for updating and accessing depth data /// </summary> private bool updatedSkeleton = false; private bool newSkeleton = false; [HideInInspector] private NuiSkeletonFrame skeletonFrame = new NuiSkeletonFrame() { SkeletonData = new NuiSkeletonData[6] }; private Vector4[] m_skeletonPosition = null; private float[] m_skldata = null; private byte[] handEvent = null; private bool m_isLeftHandGrip = false; private bool m_isRightHandGrip = false; /// <summary> ///variables used for updating and accessing video data /// </summary> private bool updatedBackgroundRemoval = false; private bool newBackgroundRemoval = false; [HideInInspector] private Color32[] BackgroundRemovalImage; private Color32[] BackgroundRemovalImageTexture; byte[] m_BackgroundRemoval_data = null; /// <summary> ///variables used for updating and accessing video data /// </summary> private bool updatedColor = false; private bool newColor = false; [HideInInspector] private Color32[] colorImage; private Color32[] colorImageTexture; private byte[] m_color_data = null; /// <summary> ///variables used for updating and accessing depth data /// </summary> private bool updatedDepth = false; private bool newDepth = false; [HideInInspector] private short[] depthPlayerData; //private Color32[] depthImage; private Color32[] depthImageTexture; private byte[] m_depth_data = null; //image stream handles for the kinect private IntPtr colorStreamHandle; private IntPtr depthStreamHandle; private int depth_width = 640; private int depth_height = 480; private int video_width = 640; private int video_height = 480; float KinectInterface.getSensorHeight() { return sensorHeight; } Vector3 KinectInterface.getKinectCenter() { return kinectCenter; } Vector4 KinectInterface.getLookAt() { return lookAt; } void Awake() { KinectSensor.instance = null; if (KinectSensor.instance != null) { Debug.Log("There should be only one active instance of the KinectSensor component at at time."); throw new Exception("There should be only one active instance of the KinectSensor component at a time."); } try { // The MSR Kinect DLL (native code) is going to load into the Unity process and stay resident even between debug runs of the game. // So our component must be resilient to starting up on a second run when the Kinect DLL is already loaded and // perhaps even left in a running state. Kinect does not appear to like having NuiInitialize called when it is already initialized as // it messes up the internal state and stops functioning. It is resilient to having Shutdown called right before initializing even if it // hasn't been initialized yet. So calling this first puts us in a good state on a first or second run. // However, calling NuiShutdown before starting prevents the image streams from being read, so if you want to use image data // (either depth or RGB), comment this line out. //NuiShutdown(); int hr = NativeMethods.qfKinectInit(); if (hr != 0) { throw new Exception("NuiInitialize Failed."); } //////////////////////////////////////////////////////// depth_width = NativeMethods.qfKinectGetDepthWidth(); depth_height = NativeMethods.qfKinectGetDepthHeight(); video_width = NativeMethods.qfKinectGetVideoWidth(); video_height = NativeMethods.qfKinectGetVideoHeight(); //////////////////////////////////////////////////////// //init BackgroundRemovalImage = new Color32[video_width * video_height]; BackgroundRemovalImageTexture = new Color32[video_width * video_height]; m_BackgroundRemoval_data = new byte[video_width * video_height * 4]; colorImage = new Color32[video_width * video_height]; colorImageTexture = new Color32[video_width * video_height]; m_color_data = new byte[video_width * video_height * 4]; //depthImage = new Color32[depth_width * depth_height]; m_depth_data = new byte[depth_width * depth_height * 4]; depthPlayerData = new short[depth_width * depth_height]; m_skldata = new float[20*4]; handEvent = new byte[2]; for (int i=0; i<skeletonFrame.SkeletonData.Length; ++i) { skeletonFrame.SkeletonData[i].eTrackingState = Kinect.NuiSkeletonTrackingState.NotTracked; skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState = new NuiSkeletonPositionTrackingState[20]; skeletonFrame.SkeletonData[i].SkeletonPositions = new Vector4[20]; for (int i_skl=0; i_skl<skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState.Length; ++i_skl) { skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState[i_skl] = Kinect.NuiSkeletonPositionTrackingState.NotTracked; } } //////////////////////////////////////////////////////// DontDestroyOnLoad(gameObject); KinectSensor.Instance = this; } catch (Exception e) { Debug.Log(e.Message); } } void LateUpdate() { updatedSkeleton = false; newSkeleton = false; updatedBackgroundRemoval = false; newBackgroundRemoval = false; updatedColor = false; newColor = false; updatedDepth = false; newDepth = false; m_isLeftHandGrip = false; m_isRightHandGrip = false; m_skeletonPosition = null; } /// <summary> ///The first time in each frame that it is called, poll the kinect for updated skeleton data and return ///true if there is new data. Subsequent calls do nothing and return the same value. /// </summary> /// <returns> /// A <see cref="System.Boolean"/> : is there new data this frame /// </returns> bool KinectInterface.pollSkeleton() { if (!updatedSkeleton) { updatedSkeleton = true; float[] skldata = m_skldata; if (null != skldata) { int hr = NativeMethods.qfKinectCopySkeletonData(skldata); if(hr == 0) { newSkeleton = true; } int i_skldata = 0; for (int i=0; i<1; ++i) { skeletonFrame.liTimeStamp = (long)(Time.time * 1000); skeletonFrame.SkeletonData[i].eTrackingState = newSkeleton ? Kinect.NuiSkeletonTrackingState.SkeletonTracked : Kinect.NuiSkeletonTrackingState.NotTracked; for (int i_skl=0 ; i_skl<skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState.Length ; ++i_skl, i_skldata+=4) { skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState[i_skl] = newSkeleton ? Kinect.NuiSkeletonPositionTrackingState.Tracked : Kinect.NuiSkeletonPositionTrackingState.NotTracked; skeletonFrame.SkeletonData[i].SkeletonPositions[i_skl] = new Vector4(skldata[i_skldata+0], skldata[i_skldata+1], skldata[i_skldata+2], skldata[i_skldata+3]); } } //default user m_skeletonPosition = skeletonFrame.SkeletonData[0].SkeletonPositions; } if (null != handEvent) { //handEvent for (int i=0; i<handEvent.Length; ++i) { handEvent[i] = 0; } try { NativeMethods.qfKinectCopyHandEventReslut(handEvent); } catch (Exception ex) { Debug.Log(ex); } m_isLeftHandGrip = handEvent[0] == 1; m_isRightHandGrip = handEvent[1] == 1; } } return newSkeleton; } NuiSkeletonFrame KinectInterface.getSkeleton(){ return skeletonFrame; } Vector4[] KinectInterface.getSkeleton_defaultUser() { return m_skeletonPosition; } bool KinectInterface.getIsLeftHandGrip_defaultUser() { return m_isLeftHandGrip; } bool KinectInterface.getIsRightHandGrip_defaultUser() { return m_isRightHandGrip; } /// <summary> ///The first time in each frame that it is called, poll the kinect for updated color data and return ///true if there is new data. Subsequent calls do nothing and return the same value. /// </summary> /// <returns> /// A <see cref="System.Boolean"/> : is there new data this frame /// </returns> bool KinectInterface.pollColor() { if (!updatedColor) { updatedColor = true; byte[] data = m_color_data; if (null != data) { int hr = NativeMethods.qfKinectCopyVideoData(data); if (hr == 0) { byte tmp = 0; for (int i=0; i<data.Length; i+=4) { //swap red and blue tmp = data[i+0]; data[i+0] = data[i+2]; data[i+2] = tmp; //alpha data[i+3] = 255; } qfOpenCV.rgbaToColor32(m_color_data, video_width, video_height, 4, colorImageTexture); newColor = true; } } } return newColor; } Color32[] KinectInterface.getColor(){ return colorImage; } Color32[] KinectInterface.getColorTexture() { return colorImageTexture; } /// <summary> ///The first time in each frame that it is called, poll the kinect for updated depth (and player) data and return ///true if there is new data. Subsequent calls do nothing and return the same value. /// </summary> /// <returns> /// A <see cref="System.Boolean"/> : is there new data this frame /// </returns> bool KinectInterface.pollDepth() { if (!updatedDepth) { updatedDepth = true; byte[] depth_data = m_depth_data; if (null != depth_data) { int hr = NativeMethods.qfKinectCopyDepthData(depth_data); if (hr == 0) { depthPlayerData = extractDepthImage(depth_data); newDepth = true; } } } return newDepth; } short[] KinectInterface.getDepth(){ return depthPlayerData; } private Color32[] extractColorImage(byte[] buf) { int totalPixels = video_width * video_height; int i_byte = 0; Color32[] colorBuf = colorImage; for (int pix = 0; pix < totalPixels; ++pix, i_byte+=4) { colorBuf[pix].r = buf[i_byte+0]; colorBuf[pix].g = buf[i_byte+1]; colorBuf[pix].b = buf[i_byte+2]; colorBuf[pix].a = buf[i_byte+3]; } return colorBuf; } private short[] extractDepthImage(byte[] buf) { short[] newbuf = depthPlayerData; for (int i=0, i_byte=0; i<newbuf.Length; ++i, i_byte+=4) { newbuf[i] = (short)((buf[i_byte+1] << 8) | buf[i_byte+0]); } return newbuf; } bool KinectInterface.pollBackgroundRemoval() { if (!updatedBackgroundRemoval) { updatedBackgroundRemoval = true; byte[] data = m_BackgroundRemoval_data; if (null != data) { int hr = NativeMethods.qfKinectCopyBackgroundRemovalData(data); if (hr == 0) { byte tmp = 0; for (int i=0; i<data.Length; i+=4) { //swap red and blue tmp = data[i+0]; data[i+0] = data[i+2]; data[i+2] = tmp; } qfOpenCV.rgbaToColor32(data, video_width, video_height, 4, BackgroundRemovalImageTexture); newBackgroundRemoval = true; } } } return newBackgroundRemoval; } Color32[] KinectInterface.getBackgroundRemoval(){ return BackgroundRemovalImage; } Color32[] KinectInterface.getBackgroundRemovalTexture() { return BackgroundRemovalImageTexture; } void OnApplicationQuit() { NativeMethods.qfKinectUnInit(); } }
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 Exam.RESTApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Linq; using ContentPatcher.Framework.Tokens.ValueProviders; using Pathoschild.Stardew.Common.Utilities; namespace ContentPatcher.Framework.Tokens { /// <summary>High-level logic for a Content Patcher token wrapped around an underlying value provider.</summary> internal class Token : IToken { /********* ** Fields *********/ /// <summary>The underlying value provider.</summary> protected IValueProvider Values { get; } /********* ** Accessors *********/ /// <inheritdoc /> public string Scope { get; } /// <inheritdoc /> public virtual string Name { get; } /// <inheritdoc /> public bool IsMutable => this.Values.IsMutable; /// <inheritdoc /> public bool IsReady => this.Values.IsReady; /// <inheritdoc /> public bool RequiresInput => this.Values.RequiresPositionalInput; /// <inheritdoc /> public bool BypassesContextValidation => this.Values.BypassesContextValidation; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="provider">The underlying value provider.</param> /// <param name="scope">The mod namespace in which the token is accessible, or <c>null</c> for any namespace.</param> public Token(IValueProvider provider, string scope = null) { this.Values = provider; this.Scope = scope; this.Name = provider.Name; } /// <inheritdoc /> public virtual bool UpdateContext(IContext context) { return this.Values.UpdateContext(context); } /// <inheritdoc /> public virtual IEnumerable<string> GetTokensUsed() { return this.Values.GetTokensUsed(); } /// <inheritdoc /> public virtual IContextualState GetDiagnosticState() { return this.Values.GetDiagnosticState(); } /// <inheritdoc /> public virtual bool CanHaveMultipleValues(IInputArguments input) { // 'contains' and 'valueAt' filter to a single value if (input.ReservedArgs.ContainsKey(InputArguments.ContainsKey) || input.ReservedArgs.ContainsKey(InputArguments.ValueAtKey)) return false; // default logic return this.Values.CanHaveMultipleValues(input); } /// <inheritdoc /> public virtual bool TryValidateInput(IInputArguments input, out string error) { // validate 'valueAt' foreach (var arg in input.ReservedArgsList) { if (InputArguments.ValueAtKey.EqualsIgnoreCase(arg.Key) && !int.TryParse(arg.Value.Raw, out _)) { error = $"invalid '{InputArguments.ValueAtKey}' index '{arg.Value.Raw}', must be a numeric value."; return false; } } // default logic return this.Values.TryValidateInput(input, out error); } /// <inheritdoc /> public virtual bool TryValidateValues(IInputArguments input, InvariantHashSet values, IContext context, out string error) { // 'contains' limited to true/false if (input.ReservedArgs.ContainsKey(InputArguments.ContainsKey)) { string[] invalidValues = values .Where(p => !bool.TryParse(p, out bool _)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); if (invalidValues.Any()) { error = $"invalid values ({string.Join(", ", invalidValues)}); expected 'true' or 'false' when used with 'contains'."; return false; } error = null; return true; } // default logic if (!this.TryValidateInput(input, out error) || !this.Values.TryValidateValues(input, values, out error)) return false; error = null; return true; } /// <inheritdoc /> public virtual InvariantHashSet GetAllowedInputArguments() { return this.Values.GetValidPositionalArgs(); } /// <inheritdoc /> public virtual bool HasBoundedValues(IInputArguments input, out InvariantHashSet allowedValues) { // 'contains' limited to true/false if (input.ReservedArgs.ContainsKey(InputArguments.ContainsKey)) { allowedValues = InvariantHashSet.Boolean(); return true; } // default logic return this.Values.HasBoundedValues(input, out allowedValues); } /// <inheritdoc /> public virtual bool HasBoundedRangeValues(IInputArguments input, out int min, out int max) { // 'contains' limited to true/false if (input.ReservedArgs.ContainsKey(InputArguments.ContainsKey)) { min = -1; max = -1; return false; } // default logic return this.Values.HasBoundedRangeValues(input, out min, out max); } /// <inheritdoc /> public virtual string NormalizeValue(string value) { return this.Values.NormalizeValue(value); } /// <inheritdoc /> public virtual IEnumerable<string> GetValues(IInputArguments input) { // default logic IEnumerable<string> rawValues = this.Values.GetValues(input); // apply global input arguments if (input.ReservedArgs.Any()) { string[] values = rawValues.ToArray(); foreach (KeyValuePair<string, IInputArgumentValue> arg in input.ReservedArgsList) { if (InputArguments.ContainsKey.EqualsIgnoreCase(arg.Key)) values = this.ApplyContains(values, arg.Value); else if (InputArguments.ValueAtKey.EqualsIgnoreCase(arg.Key)) values = this.ApplyValueAt(values, arg.Value); } rawValues = values; } return rawValues; } /********* ** Protected methods *********/ /// <summary>Construct an instance.</summary> /// <param name="name">The token name.</param> /// <param name="provider">The underlying value provider.</param> /// <param name="scope">The mod namespace in which the token is accessible, or <c>null</c> for any namespace.</param> protected Token(string name, IValueProvider provider, string scope = null) : this(provider, scope) { this.Name = name; } /// <summary>Apply the <see cref="InputArguments.ContainsKey"/> argument.</summary> /// <param name="values">The underlying values to modify.</param> /// <param name="argValue">The argument value.</param> private string[] ApplyContains(string[] values, IInputArgumentValue argValue) { InvariantHashSet search = new(argValue.Parsed.Select(this.NormalizeValue)); bool match = search.Any() && values.Any(value => search.Contains(value)); return new[] { match.ToString() }; } /// <summary>Apply the <see cref="InputArguments.ValueAtKey"/> argument.</summary> /// <param name="values">The underlying values to modify.</param> /// <param name="argValue">The argument value.</param> private string[] ApplyValueAt(string[] values, IInputArgumentValue argValue) { // parse index if (!int.TryParse(argValue.Raw, out int index)) throw new FormatException($"Invalid '{InputArguments.ValueAtKey}' index '{argValue.Raw}', must be a numeric index."); // should never happen since it's validated before this point if (Math.Abs(index) >= values.Length) return Array.Empty<string>(); // get value at index (negative index = from end) return index >= 0 ? new[] { values[index] } : new[] { values[values.Length + index] }; } } }
// // ReportViewer.cs // // Author: // Krzysztof Marecki // // Copyright (c) 2010 Krzysztof Marecki // Copyright (c) 2012 Peter Gill // // This file is part of the NReports project // This file is part of the My-FyiReporting project // // 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; using System.Collections.Specialized; using System.Text; using fyiReporting.RDL; using Gtk; namespace fyiReporting.RdlGtkViewer { [System.ComponentModel.ToolboxItem(true)] public partial class ReportViewer : Gtk.Bin { private Report report; private Pages pages; private PrintOperation printing; public NeedPassword DataSourceReferencePassword = null; private string connectionString; private bool overwriteSubreportConnection; public event EventHandler ReportPrinted; public ListDictionary Parameters { get; private set; } bool show_errors; public bool ShowErrors { get { return show_errors; } set { show_errors = value; CheckVisibility(); } } public string DefaultExportFileName { get; set;} bool show_params; public bool ShowParameters { get { return show_params; } set { show_params = value; CheckVisibility(); } } public string WorkingDirectory { get; set; } Uri sourceFile; public Uri SourceFile { get { return sourceFile; } private set { sourceFile = value; WorkingDirectory = System.IO.Path.GetDirectoryName (sourceFile.LocalPath); } } public ReportViewer() { this.Build(); Parameters = new ListDictionary(); this.errorsAction.Toggled += OnErrorsActionToggled; DisableActions(); ShowErrors = false; } /// <summary> /// Loads the report. /// </summary> /// <param name="filename">Filename.</param> /// <param name="parameters">Example: parameter1=someValue&parameter2=anotherValue</param> /// <param name="connectionString">Relace all Connection string in report.</param> /// <param name="overwriteSubreportConnection">If true connection string in subreport also will be overwrite</param> public void LoadReport (Uri filename, string parameters, string connectionString, bool overwriteSubreportConnection = false) { SourceFile = filename; this.connectionString = connectionString; this.overwriteSubreportConnection = overwriteSubreportConnection; LoadReport (filename, parameters); } /// <summary> /// Loads the report. /// </summary> /// <param name="source">Xml source of report</param> /// <param name="parameters">Example: parameter1=someValue&parameter2=anotherValue</param> /// <param name="connectionString">Relace all Connection string in report.</param> /// <param name="overwriteSubreportConnection">If true connection string in subreport also will be overwrite</param> public void LoadReport(string source, string parameters, string connectionString, bool overwriteSubreportConnection = false) { this.connectionString = connectionString; this.overwriteSubreportConnection = overwriteSubreportConnection; LoadReport(source, parameters); } /// <summary> /// Loads the report. /// </summary> /// <param name='filename'> /// Filename. /// </param> public void LoadReport(Uri filename) { LoadReport(filename, ""); } /// <summary> /// Loads the report. /// </summary> /// <param name='sourcefile'> /// Filename. /// </param> /// <param name='parameters'> /// Example: parameter1=someValue&parameter2=anotherValue /// </param> public void LoadReport(Uri sourcefile, string parameters) { SourceFile = sourcefile; string source = System.IO.File.ReadAllText(sourcefile.LocalPath); LoadReport(source, parameters); } /// <summary> /// Loads the report. /// </summary> /// <param name="source">Xml source of report</param> /// <param name="parameters">Example: parameter1=someValue&parameter2=anotherValue</param> public void LoadReport(string source, string parameters) { // Any parameters? e.g. file1.rdl?orderid=5 if (parameters.Trim() != "") { this.Parameters = this.GetParmeters(parameters); } else { this.Parameters = null; } // Compile the report report = this.GetReport(source); if (report == null) return; AddParameterControls(); RefreshReport(); } void RefreshReport() { SetParametersFromControls(); report.RunGetData(Parameters); pages = report.BuildPages(); foreach (Gtk.Widget w in vboxPages.AllChildren) { vboxPages.Remove(w); } for (int pageCount = 0; pageCount < pages.Count; pageCount++) { ReportArea area = new ReportArea(); area.SetReport(report, pages[pageCount]); //area.Scale vboxPages.Add(area); } this.ShowAll(); SetErrorMessages (report.ErrorItems); if (report.ErrorMaxSeverity == 0) show_errors = false; errorsAction.VisibleHorizontal = report.ErrorMaxSeverity > 0; // Title = string.Format ("RDL report viewer - {0}", report.Name); EnableActions(); CheckVisibility(); } protected void OnZoomOutActionActivated(object sender, System.EventArgs e) { foreach (Gtk.Widget w in vboxPages.AllChildren) { if (w is ReportArea) { ((ReportArea)w).Scale -= 0.1f; } } //reportarea.Scale -= 0.1f; } protected void OnZoomInActionActivated(object sender, System.EventArgs e) { foreach (Gtk.Widget w in vboxPages.AllChildren) { if (w is ReportArea) { ((ReportArea)w).Scale += 0.1f; } } //reportarea.Scale += 0.1f; } // GetParameters creates a list dictionary // consisting of a report parameter name and a value. private System.Collections.Specialized.ListDictionary GetParmeters(string parms) { System.Collections.Specialized.ListDictionary ld = new System.Collections.Specialized.ListDictionary(); if (parms == null) { return ld; // dictionary will be empty in this case } // parms are separated by & char[] breakChars = new char[] { '&' }; string[] ps = parms.Split(breakChars); foreach (string p in ps) { int iEq = p.IndexOf("="); if (iEq > 0) { string name = p.Substring(0, iEq); string val = p.Substring(iEq + 1); ld.Add(name, val); } } return ld; } private Report GetReport(string reportSource) { // Now parse the file RDLParser rdlp; Report r; rdlp = new RDLParser(reportSource); rdlp.Folder = WorkingDirectory; rdlp.OverwriteConnectionString = connectionString; rdlp.OverwriteInSubreport = overwriteSubreportConnection; // RDLParser takes RDL XML and Parse compiles the report r = rdlp.Parse(); if (r.ErrorMaxSeverity > 0) { foreach (string emsg in r.ErrorItems) { Console.WriteLine(emsg); } SetErrorMessages (r.ErrorItems); int severity = r.ErrorMaxSeverity; r.ErrorReset(); if (severity > 4) { errorsAction.Active = true; return null; // don't return when severe errors } } return r; } void OnErrorsActionToggled(object sender, EventArgs e) { ShowErrors = errorsAction.Active; } void CheckVisibility() { if (ShowErrors) { scrolledwindowErrors.ShowAll(); } else { scrolledwindowErrors.HideAll(); } if (ShowParameters) { vboxParameters.ShowAll(); } else { vboxParameters.HideAll(); } } protected override void OnShown() { base.OnShown(); CheckVisibility(); } void DisableActions() { saveAsAction.Sensitive = false; refreshAction.Sensitive = false; printAction.Sensitive = false; ZoomInAction.Sensitive = false; ZoomOutAction.Sensitive = false; } void EnableActions() { saveAsAction.Sensitive = true; refreshAction.Sensitive = true; printAction.Sensitive = true; ZoomInAction.Sensitive = true; ZoomOutAction.Sensitive = true; } void AddParameterControls() { foreach (Widget child in vboxParameters.Children) { vboxParameters.Remove(child); } foreach (UserReportParameter rp in report.UserReportParameters) { HBox hbox = new HBox(); Label labelPrompt = new Label(); labelPrompt.SetAlignment(0, 0.5f); labelPrompt.Text = string.Format("{0} :", rp.Prompt); hbox.PackStart(labelPrompt, true, true, 0); Entry entryValue = new Entry(); if (Parameters.Contains(rp.Name)) { if (Parameters[rp.Name] != null) { entryValue.Text = Parameters[rp.Name].ToString(); } } else { if (rp.DefaultValue != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < rp.DefaultValue.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(rp.DefaultValue[i].ToString()); } entryValue.Text = sb.ToString(); } } hbox.PackStart(entryValue, false, false, 0); vboxParameters.PackStart(hbox, false, false, 0); } } void SetParametersFromControls() { int i = 0; foreach (UserReportParameter rp in report.UserReportParameters) { HBox hbox = (HBox)vboxParameters.Children[i]; Entry entry = (Entry)hbox.Children[1]; //parameters.Add (rp.Name, entry.Text); Parameters[rp.Name] = entry.Text; i++; } } void SetErrorMessages(IList errors) { textviewErrors.Buffer.Clear(); if (errors == null || errors.Count == 0) return; StringBuilder msgs = new StringBuilder(); msgs.AppendLine("Report rendering errors:"); msgs.AppendLine (); foreach (var error in errors) msgs.AppendLine(error.ToString()); textviewErrors.Buffer.Text = msgs.ToString(); } protected void OnPdfActionActivated(object sender, System.EventArgs e) { // ********************************* object[] param = new object[4]; param[0] = "Cancel"; param[1] = Gtk.ResponseType.Cancel; param[2] = "Save"; param[3] = Gtk.ResponseType.Accept; Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog("Save File As", null, Gtk.FileChooserAction.Save, param); fc.CurrentName = DefaultExportFileName??report.Name; Gtk.FileFilter pdfFilter = new Gtk.FileFilter(); pdfFilter.Name = "PDF"; Gtk.FileFilter csvFilter = new Gtk.FileFilter(); csvFilter.Name = "CSV"; Gtk.FileFilter asphtmlFilter = new Gtk.FileFilter(); asphtmlFilter.Name = "ASP HTML"; Gtk.FileFilter excel2007Data = new Gtk.FileFilter(); excel2007Data.Name = "Excel 2007 Data"; Gtk.FileFilter excel2007 = new Gtk.FileFilter(); excel2007.Name = "Excel 2007"; Gtk.FileFilter htmlFilter = new Gtk.FileFilter(); htmlFilter.Name = "HTML"; Gtk.FileFilter mhtmlFilter = new Gtk.FileFilter(); mhtmlFilter.Name = "MHTML"; Gtk.FileFilter rtfFilter = new Gtk.FileFilter(); rtfFilter.Name = "RTF"; Gtk.FileFilter xmlFilter = new Gtk.FileFilter(); xmlFilter.Name = "XML"; fc.AddFilter(pdfFilter); fc.AddFilter(csvFilter); fc.AddFilter(asphtmlFilter); fc.AddFilter(excel2007Data); fc.AddFilter(excel2007); fc.AddFilter(htmlFilter); fc.AddFilter(mhtmlFilter); fc.AddFilter(xmlFilter); if (fc.Run() == (int)Gtk.ResponseType.Accept) { try { // Must use the RunGetData before each export or there is no data. report.RunGetData(this.Parameters); string filename = fc.Filename; OutputPresentationType exportType = OutputPresentationType.PDF; if (fc.Filter.Name == "CSV") { exportType = OutputPresentationType.CSV; if (filename.ToLower().Trim().EndsWith(".csv") == false) { filename = filename + ".csv"; } } else if (fc.Filter.Name == "PDF") { exportType = OutputPresentationType.PDF; if (filename.ToLower().Trim().EndsWith(".pdf") == false) { filename = filename + ".pdf"; } } else if (fc.Filter.Name == "ASP HTML") { exportType = OutputPresentationType.ASPHTML; if (filename.ToLower().Trim().EndsWith(".asphtml") == false) { filename = filename + ".asphtml"; } } else if (fc.Filter.Name == "Excel 2007 Data") { exportType = OutputPresentationType.ExcelTableOnly; if (filename.ToLower().Trim().EndsWith(".xlsx") == false) { filename = filename + ".xlsx"; } } else if(fc.Filter.Name == "Excel 2007") { exportType = OutputPresentationType.Excel2007; if(filename.ToLower().Trim().EndsWith(".xlsx") == false) { filename = filename + ".xlsx"; } } else if (fc.Filter.Name == "HTML") { exportType = OutputPresentationType.HTML; if (filename.ToLower().Trim().EndsWith(".html") == false) { filename = filename + ".html"; } } else if (fc.Filter.Name == "MHTML") { exportType = OutputPresentationType.MHTML; if (filename.ToLower().Trim().EndsWith(".mhtml") == false) { filename = filename + ".mhtml"; } } else if (fc.Filter.Name == "XML") { exportType = OutputPresentationType.XML; if (filename.ToLower().Trim().EndsWith(".xml") == false) { filename = filename + ".xml"; } } ExportReport(report, filename, exportType); } catch (Exception ex) { Gtk.MessageDialog m = new Gtk.MessageDialog(null, Gtk.DialogFlags.Modal, Gtk.MessageType.Info, Gtk.ButtonsType.Ok, false, "Error Saving Copy of PDF." + System.Environment.NewLine + ex.Message); m.Run(); m.Destroy(); } } //Don't forget to call Destroy() or the FileChooserDialog window won't get closed. fc.Destroy(); } /// <summary> /// Save the report to the output selected. /// </summary> /// <param name='report'> /// Report. /// </param> /// <param name='FileName'> /// File name. /// </param> private void ExportReport(Report report, string FileName, OutputPresentationType exportType) { OneFileStreamGen sg = null; try { sg = new OneFileStreamGen(FileName, true); report.RunRender(sg, exportType); } catch (Exception ex) { Gtk.MessageDialog m = new Gtk.MessageDialog(null, Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, false, ex.Message); m.Run(); m.Destroy(); } finally { if (sg != null) { sg.CloseMainStream(); } } return; } protected void OnPrintActionActivated(object sender, System.EventArgs e) { using (PrintContext context = new PrintContext(GdkWindow.Handle)) { printing = new PrintOperation(); printing.Unit = Unit.Points; printing.UseFullPage = true; printing.DefaultPageSetup = new PageSetup(); printing.DefaultPageSetup.Orientation = report.PageHeightPoints > report.PageWidthPoints ? PageOrientation.Portrait : PageOrientation.Landscape; printing.BeginPrint += HandlePrintBeginPrint; printing.DrawPage += HandlePrintDrawPage; printing.EndPrint += HandlePrintEndPrint; printing.Run(PrintOperationAction.PrintDialog, null); } } void HandlePrintBeginPrint (object o, BeginPrintArgs args) { printing.NPages = pages.Count; } void HandlePrintDrawPage (object o, DrawPageArgs args) { Cairo.Context g = args.Context.CairoContext; RenderCairo render = new RenderCairo (g); render.RunPage(pages[args.PageNr]); } void HandlePrintEndPrint (object o, EndPrintArgs args) { ReportPrinted?.Invoke(this, EventArgs.Empty); } protected void OnRefreshActionActivated(object sender, System.EventArgs e) { RefreshReport(); } int hpanedWidth = 0; void SetHPanedPosition() { int textviewWidth = scrolledwindowErrors.Allocation.Width + 10; hpanedReport.Position = hpanedWidth - textviewWidth; } protected void OnHpanedReportSizeAllocated(object o, Gtk.SizeAllocatedArgs args) { if (args.Allocation.Width != hpanedWidth) { hpanedWidth = args.Allocation.Width; SetHPanedPosition(); } } } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Configuration; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ZLogger.Providers; namespace ZLogger { public static class UnityLoggerFactory { public static ILoggerFactory Create(Action<ILoggingBuilder> configure) { var services = new ServiceCollection(); services.AddLogging(x => { AddBeforeConfiguration(x); // register singleton configure(x); AddAfterConfiguration(x); // remove and register enumerable }); // use this for check IL2CPP type information. //var provider = new DiagnosticServiceProvider(services); var provider = services.BuildServiceProvider(); var loggerFactory = provider.GetService<ILoggerFactory>(); return new DisposingLoggerFactory(loggerFactory, provider); } static void AddBeforeConfiguration(ILoggingBuilder builder) { builder.Services.TryAddSingleton<ILoggerProviderConfigurationFactory, LoggerProviderConfigurationFactory>(); builder.Services.TryAddSingleton(typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>)); } static void AddAfterConfiguration(ILoggingBuilder builder) { var removeTargets = builder.Services.Where(item => ( item.ServiceType == typeof(IConfigureOptions<ZLoggerOptions>) && (item?.ImplementationType?.FullName?.StartsWith("Microsoft.Extensions.Logging.Configuration.LoggerProviderConfigureOptions") ?? false))) .ToArray(); foreach (var item in removeTargets) { builder.Services.Remove(item); } builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerUnityLoggerProvider>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerConsoleLoggerProvider>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerFileLoggerProvider>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerRollingFileLoggerProvider>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerStreamLoggerProvider>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<ZLoggerOptions>, LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerLogProcessorLoggerProvider>>()); } // for IL2CPP. static void TypeHint() { _ = new LoggerFactory(default(IEnumerable<ILoggerProvider>), default(LoggerFilterOptions)); { var setups = new IConfigureOptions<ZLoggerOptions>[] { new ConfigureOptions<ZLoggerOptions>(default) }.AsEnumerable(); var postConfigure = new IPostConfigureOptions<ZLoggerOptions>[] { new PostConfigureOptions<ZLoggerOptions>(default, default) }.AsEnumerable(); var optionFactory = new OptionsFactory<ZLoggerOptions>(setups, postConfigure); _ = new OptionsManager<ZLoggerOptions>(optionFactory); var sources = new[] { new ConfigurationChangeTokenSource<ZLoggerOptions>(default) }.AsEnumerable(); var cache = new OptionsCache<ZLoggerOptions>(); _ = new OptionsMonitor<ZLoggerOptions>(optionFactory, sources, cache); } { var setups = new IConfigureOptions<LoggerFilterOptions>[] { new ConfigureOptions<LoggerFilterOptions>(default) }.AsEnumerable(); var postConfigure = new IPostConfigureOptions<LoggerFilterOptions>[] { new PostConfigureOptions<LoggerFilterOptions>(default, default) }.AsEnumerable(); var optionFactory = new OptionsFactory<LoggerFilterOptions>(setups, postConfigure); _ = new OptionsManager<LoggerFilterOptions>(optionFactory); var sources = new[] { new ConfigurationChangeTokenSource<LoggerFilterOptions>(default) }.AsEnumerable(); var cache = new OptionsCache<LoggerFilterOptions>(); _ = new OptionsMonitor<LoggerFilterOptions>(optionFactory, sources, cache); } { _ = Options.Create<LoggerFilterOptions>(new LoggerFilterOptions()); _ = Options.Create<ZLoggerOptions>(new ZLoggerOptions()); _ = new ConfigureNamedOptions<LoggerFilterOptions>(default, default); _ = new ConfigureNamedOptions<ZLoggerOptions>(default, default); } var loggingConfigurations = new[] { new LoggingConfiguration(default) }.AsEnumerable(); var loggingProviderConfigurationFactory = new LoggerProviderConfigurationFactory(loggingConfigurations); { { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerUnityLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerUnityLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerUnityLoggerProvider>(providerConfiguration); } { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerConsoleLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerConsoleLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerConsoleLoggerProvider>(providerConfiguration); } { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerFileLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerFileLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerFileLoggerProvider>(providerConfiguration); } { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerRollingFileLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerRollingFileLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerRollingFileLoggerProvider>(providerConfiguration); } { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerStreamLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerStreamLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerStreamLoggerProvider>(providerConfiguration); } { var providerConfiguration = new LoggerProviderConfiguration<ZLoggerLogProcessorLoggerProvider>(loggingProviderConfigurationFactory); _ = new LoggerProviderConfigureOptions<ZLoggerOptions, ZLoggerLogProcessorLoggerProvider>(providerConfiguration); _ = new LoggerProviderOptionsChangeTokenSource<ZLoggerOptions, ZLoggerLogProcessorLoggerProvider>(providerConfiguration); } } } class LoggingConfiguration { public IConfiguration Configuration { get; } public LoggingConfiguration(IConfiguration configuration) { Configuration = configuration; } } class LoggerProviderConfiguration<T> : ILoggerProviderConfiguration<T> { public LoggerProviderConfiguration(ILoggerProviderConfigurationFactory providerConfigurationFactory) { Configuration = providerConfigurationFactory.GetConfiguration(typeof(T)); } public IConfiguration Configuration { get; } } class LoggerProviderConfigurationFactory : ILoggerProviderConfigurationFactory { private readonly IEnumerable<LoggingConfiguration> _configurations; public LoggerProviderConfigurationFactory(IEnumerable<LoggingConfiguration> configurations) { _configurations = configurations; } public IConfiguration GetConfiguration(Type providerType) { if (providerType == null) { throw new ArgumentNullException(nameof(providerType)); } var fullName = providerType.FullName; var alias = ProviderAliasUtilities.GetAlias(providerType); var configurationBuilder = new ConfigurationBuilder(); foreach (var configuration in _configurations) { var sectionFromFullName = configuration.Configuration.GetSection(fullName); configurationBuilder.AddConfiguration(sectionFromFullName); if (!string.IsNullOrWhiteSpace(alias)) { var sectionFromAlias = configuration.Configuration.GetSection(alias); configurationBuilder.AddConfiguration(sectionFromAlias); } } return configurationBuilder.Build(); } } class LoggerProviderConfigureOptions<TOptions, TProvider> : ConfigureFromConfigurationOptions<TOptions> where TOptions : class { public LoggerProviderConfigureOptions(ILoggerProviderConfiguration<TProvider> providerConfiguration) : base(providerConfiguration.Configuration) { } } static class ProviderAliasUtilities { private const string AliasAttibuteTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; private const string AliasAttibuteAliasProperty = "Alias"; internal static string GetAlias(Type providerType) { foreach (var attribute in providerType.GetTypeInfo().GetCustomAttributes(inherit: false)) { if (attribute.GetType().FullName == AliasAttibuteTypeFullName) { var valueProperty = attribute .GetType() .GetProperty(AliasAttibuteAliasProperty, BindingFlags.Public | BindingFlags.Instance); if (valueProperty != null) { return valueProperty.GetValue(attribute) as string; } } } return null; } } class DisposingLoggerFactory : ILoggerFactory, IDisposable { readonly ILoggerFactory loggerFactory; readonly IServiceProvider serviceProvider; public DisposingLoggerFactory(ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory)); if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider)); this.loggerFactory = loggerFactory; this.serviceProvider = serviceProvider; } public void Dispose() { (serviceProvider as IDisposable)?.Dispose(); } public ILogger CreateLogger(string categoryName) { return loggerFactory.CreateLogger(categoryName); } public void AddProvider(ILoggerProvider provider) { loggerFactory.AddProvider(provider); } } } }
using System; using UnityEngine; namespace Codes.Linus.IntVectors { [Serializable] public struct Vector3i { // Fields public int x; public int y; public int z; // Indexer public int this [int index] { get { switch (index) { case X_INDEX: return this.x; case Y_INDEX: return this.y; case Z_INDEX: return this.z; default: throw new IndexOutOfRangeException ("Invalid Vector3i index!"); } } set { switch (index) { case X_INDEX: this.x = value; break; case Y_INDEX: this.y = value; break; case Z_INDEX: this.z = value; break; default: throw new IndexOutOfRangeException ("Invalid Vector3i index!"); } } } // Constructors public Vector3i (int x, int y) { this.x = x; this.y = y; this.z = 0; } public Vector3i (int x, int y, int z) { this.x = x; this.y = y; this.z = z; } // Properties public float sqrMagnitude { get { return x * x + y * y + z * z; } } public float magnitude { get { return Mathf.Sqrt (sqrMagnitude); } } public bool IsWithinBounds (Vector3i from, Vector3i to) { return this.x >= from.x && this.x < to.x && this.y >= from.y && this.y < to.y && this.z >= from.z && this.z < to.z; } // Set public void Set (int new_x, int new_y, int new_z) { this.x = new_x; this.y = new_y; this.z = new_z; } // Scaling public void Scale (Vector3i scale) { x *= scale.x; y *= scale.y; z *= scale.z; } public static Vector3i Scale (Vector3i a, Vector3i b) { return new Vector3i ( a.x * b.x, a.y * b.y, a.z * b.z ); } // Rotations public void RotateCW(int axis) { int temp; switch(axis) { case 0: temp = y; y = -z; z = temp; break; case 1: temp = x; x = z; z = -temp; break; case 2: temp = x; x = -y; y = temp; break; } } public void RotateCCW(int axis) { int temp; switch (axis) { case 0: temp = y; y = z; z = -temp; break; case 1: temp = x; x = -z; z = temp; break; case 2: temp = x; x = y; y = -temp; break; } } // Loops public enum LoopOrder: int { ZYX, ZXY, XZY, YZX, YXZ, XYZ } private static int[,] loopCoords = new int[,]{ {2,1,0}, {2,0,1}, {0,2,1}, {1,2,0}, {1,0,2}, {0,1,2} }; private static int GetCoord(LoopOrder loopOrder, int loopLevel) { return loopCoords [(int)loopOrder, loopLevel]; } public static void CubeLoop (Vector3i from, Vector3i to, Action<Vector3i> body) { if (body == null) { throw new ArgumentNullException("body"); } Vector3i iterator = Vector3i.zero; for (iterator.x = from.x; iterator.x < to.x; iterator.x++) { for (iterator.y = from.y; iterator.y < to.y; iterator.y++) { for (iterator.z = from.z; iterator.z < to.z; iterator.z++) { body (iterator); } } } } // ToString public override string ToString () { return string.Format ("({0}, {1}, {2})", x, y, z); } // Operators public static Vector3i operator + (Vector3i a, Vector3i b) { return new Vector3i ( a.x + b.x, a.y + b.y, a.z + b.z ); } public static Vector3i operator - (Vector3i a) { return new Vector3i ( -a.x, -a.y, -a.z ); } public static Vector3i operator - (Vector3i a, Vector3i b) { return a + (-b); } public static Vector3i operator * (int d, Vector3i a) { return new Vector3i ( d * a.x, d * a.y, d * a.z ); } public static Vector3i operator * (Vector3i a, int d) { return d * a; } public static Vector3i operator / (Vector3i a, int d) { return new Vector3i ( a.x / d, a.y / d, a.z / d ); } // Equality public static bool operator == (Vector3i lhs, Vector3i rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } public static bool operator != (Vector3i lhs, Vector3i rhs) { return !(lhs == rhs); } public override bool Equals (object other) { if (!(other is Vector3i)) { return false; } return this == (Vector3i)other; } public bool Equals (Vector3i other) { return this == other; } public override int GetHashCode () { return this.x.GetHashCode () ^ this.y.GetHashCode () << 2 ^ this.z.GetHashCode () >> 2; } // Static Methods public static float Distance (Vector3i a, Vector3i b) { return (a - b).magnitude; } public static Vector3i Min (Vector3i lhs, Vector3i rhs) { return new Vector3i ( Mathf.Min (lhs.x, rhs.x), Mathf.Min (lhs.y, rhs.y), Mathf.Min (lhs.z, rhs.z) ); } public static Vector3i Max (Vector3i lhs, Vector3i rhs) { return new Vector3i ( Mathf.Max (lhs.x, rhs.x), Mathf.Max (lhs.y, rhs.y), Mathf.Max (lhs.z, rhs.z) ); } public static int Dot (Vector3i lhs, Vector3i rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } public static Vector3i Cross (Vector3i lhs, Vector3i rhs) { return new Vector3i ( lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x ); } public static float Magnitude (Vector3i a) { return a.magnitude; } public static float SqrMagnitude (Vector3i a) { return a.sqrMagnitude; } // Default values public static Vector3i back { get { return new Vector3i (0, 0, -1); } } public static Vector3i forward { get { return new Vector3i (0, 0, 1); } } public static Vector3i down { get { return new Vector3i (0, -1, 0); } } public static Vector3i up { get { return new Vector3i (0, +1, 0); } } public static Vector3i left { get { return new Vector3i (-1, 0, 0); } } public static Vector3i right { get { return new Vector3i (+1, 0, 0); } } public static Vector3i one { get { return new Vector3i (+1, +1, +1); } } public static Vector3i zero { get { return new Vector3i (0, 0, 0); } } // Conversions public static explicit operator Vector3i (Vector3 source) { return new Vector3i ((int)source.x, (int)source.y, (int)source.z); } public static implicit operator Vector3 (Vector3i source) { return new Vector3 (source.x, source.y, source.z); } // Constants public const int X_INDEX = 0; public const int Y_INDEX = 1; public const int Z_INDEX = 2; } }
/** * (C) Copyright IBM Corp. 2018, 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using NSubstitute; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Collections.Generic; using IBM.Cloud.SDK.Core.Http; using IBM.Cloud.SDK.Core.Http.Exceptions; using IBM.Cloud.SDK.Core.Authentication.NoAuth; using IBM.Watson.Discovery.v2.Model; using IBM.Cloud.SDK.Core.Model; namespace IBM.Watson.Discovery.v2.UnitTests { [TestClass] public class DiscoveryServiceUnitTests { #region Constructor [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void Constructor_HttpClient_Null() { DiscoveryService service = new DiscoveryService(httpClient: null); } [TestMethod] public void ConstructorHttpClient() { DiscoveryService service = new DiscoveryService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorExternalConfig() { var apikey = System.Environment.GetEnvironmentVariable("DISCOVERY_APIKEY"); System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", "apikey"); DiscoveryService service = Substitute.For<DiscoveryService>("versionDate", null); Assert.IsNotNull(service); System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", apikey); } [TestMethod] public void Constructor() { DiscoveryService service = new DiscoveryService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorAuthenticator() { DiscoveryService service = new DiscoveryService("versionDate", new NoAuthAuthenticator()); Assert.IsNotNull(service); } [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void ConstructorNoVersion() { DiscoveryService service = new DiscoveryService(null, new NoAuthAuthenticator()); } #endregion [TestMethod] public void ListCollections_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var result = service.ListCollections(projectId: projectId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/collections"); } [TestMethod] public void Query_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var collectionIds = new List<string>(); var filter = "filter"; var query = "query"; var naturalLanguageQuery = "naturalLanguageQuery"; var aggregation = "aggregation"; var count = 1; var _return = new List<string>(); var offset = 1; var sort = "sort"; var highlight = false; var spellingSuggestions = false; var tableResults = new QueryLargeTableResults(); var suggestedRefinements = new QueryLargeSuggestedRefinements(); var passages = new QueryLargePassages(); var result = service.Query(projectId: projectId, collectionIds: collectionIds, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, aggregation: aggregation, count: count, _return: _return, offset: offset, sort: sort, highlight: highlight, spellingSuggestions: spellingSuggestions, tableResults: tableResults, suggestedRefinements: suggestedRefinements, passages: passages); JObject bodyObject = new JObject(); if (collectionIds != null && collectionIds.Count > 0) { bodyObject["collection_ids"] = JToken.FromObject(collectionIds); } if (!string.IsNullOrEmpty(filter)) { bodyObject["filter"] = JToken.FromObject(filter); } if (!string.IsNullOrEmpty(query)) { bodyObject["query"] = JToken.FromObject(query); } if (!string.IsNullOrEmpty(naturalLanguageQuery)) { bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery); } if (!string.IsNullOrEmpty(aggregation)) { bodyObject["aggregation"] = JToken.FromObject(aggregation); } if (count != null) { bodyObject["count"] = JToken.FromObject(count); } if (_return != null && _return.Count > 0) { bodyObject["return"] = JToken.FromObject(_return); } if (offset != null) { bodyObject["offset"] = JToken.FromObject(offset); } if (!string.IsNullOrEmpty(sort)) { bodyObject["sort"] = JToken.FromObject(sort); } bodyObject["highlight"] = JToken.FromObject(highlight); bodyObject["spelling_suggestions"] = JToken.FromObject(spellingSuggestions); if (tableResults != null) { bodyObject["table_results"] = JToken.FromObject(tableResults); } if (suggestedRefinements != null) { bodyObject["suggested_refinements"] = JToken.FromObject(suggestedRefinements); } if (passages != null) { bodyObject["passages"] = JToken.FromObject(passages); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v2/projects/{projectId}/query"); } [TestMethod] public void GetAutocompletion_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var prefix = "prefix"; var collectionIds = new List<string>() { "collectionIds0", "collectionIds1" }; var field = "field"; long? count = 1; var result = service.GetAutocompletion(projectId: projectId, prefix: prefix, collectionIds: collectionIds, field: field, count: count); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/autocompletion"); } [TestMethod] public void QueryNotices_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var filter = "filter"; var query = "query"; var naturalLanguageQuery = "naturalLanguageQuery"; long? count = 1; long? offset = 1; var result = service.QueryNotices(projectId: projectId, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, count: count, offset: offset); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/notices"); } [TestMethod] public void ListFields_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var collectionIds = new List<string>() { "collectionIds0", "collectionIds1" }; var result = service.ListFields(projectId: projectId, collectionIds: collectionIds); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/fields"); } [TestMethod] public void GetComponentSettings_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var result = service.GetComponentSettings(projectId: projectId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/component_settings"); } [TestMethod] public void AddDocument_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var collectionId = "collectionId"; var file = new MemoryStream(); var filename = "filename"; var fileContentType = "fileContentType"; var metadata = "metadata"; var xWatsonDiscoveryForce = false; var result = service.AddDocument(projectId: projectId, collectionId: collectionId, file: file, filename: filename, fileContentType: fileContentType, metadata: metadata, xWatsonDiscoveryForce: xWatsonDiscoveryForce); request.Received().WithArgument("version", versionDate); client.Received().PostAsync($"{service.ServiceUrl}/v2/projects/{projectId}/collections/{collectionId}/documents"); } [TestMethod] public void UpdateDocument_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var collectionId = "collectionId"; var documentId = "documentId"; var file = new MemoryStream(); var filename = "filename"; var fileContentType = "fileContentType"; var metadata = "metadata"; var xWatsonDiscoveryForce = false; var result = service.UpdateDocument(projectId: projectId, collectionId: collectionId, documentId: documentId, file: file, filename: filename, fileContentType: fileContentType, metadata: metadata, xWatsonDiscoveryForce: xWatsonDiscoveryForce); request.Received().WithArgument("version", versionDate); client.Received().PostAsync($"{service.ServiceUrl}/v2/projects/{projectId}/collections/{collectionId}/documents/{documentId}"); } [TestMethod] public void DeleteDocument_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var collectionId = "collectionId"; var documentId = "documentId"; var xWatsonDiscoveryForce = false; var result = service.DeleteDocument(projectId: projectId, collectionId: collectionId, documentId: documentId, xWatsonDiscoveryForce: xWatsonDiscoveryForce); request.Received().WithArgument("version", versionDate); client.Received().DeleteAsync($"{service.ServiceUrl}/v2/projects/{projectId}/collections/{collectionId}/documents/{documentId}"); } [TestMethod] public void ListTrainingQueries_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var result = service.ListTrainingQueries(projectId: projectId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/training_data/queries"); } [TestMethod] public void DeleteTrainingQueries_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var result = service.DeleteTrainingQueries(projectId: projectId); request.Received().WithArgument("version", versionDate); client.Received().DeleteAsync($"{service.ServiceUrl}/v2/projects/{projectId}/training_data/queries"); } [TestMethod] public void CreateTrainingQuery_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var naturalLanguageQuery = "naturalLanguageQuery"; var filter = "filter"; var examples = new List<TrainingExample>(); var result = service.CreateTrainingQuery(projectId: projectId, naturalLanguageQuery: naturalLanguageQuery, filter: filter, examples: examples); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(naturalLanguageQuery)) { bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery); } if (!string.IsNullOrEmpty(filter)) { bodyObject["filter"] = JToken.FromObject(filter); } if (examples != null && examples.Count > 0) { bodyObject["examples"] = JToken.FromObject(examples); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v2/projects/{projectId}/training_data/queries"); } [TestMethod] public void GetTrainingQuery_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var queryId = "queryId"; var result = service.GetTrainingQuery(projectId: projectId, queryId: queryId); request.Received().WithArgument("version", versionDate); client.Received().GetAsync($"{service.ServiceUrl}/v2/projects/{projectId}/training_data/queries/{queryId}"); } [TestMethod] public void UpdateTrainingQuery_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); DiscoveryService service = new DiscoveryService(client); var versionDate = "versionDate"; service.Version = versionDate; var projectId = "projectId"; var queryId = "queryId"; var naturalLanguageQuery = "naturalLanguageQuery"; var filter = "filter"; var examples = new List<TrainingExample>(); var result = service.UpdateTrainingQuery(projectId: projectId, queryId: queryId, naturalLanguageQuery: naturalLanguageQuery, filter: filter, examples: examples); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(naturalLanguageQuery)) { bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery); } if (!string.IsNullOrEmpty(filter)) { bodyObject["filter"] = JToken.FromObject(filter); } if (examples != null && examples.Count > 0) { bodyObject["examples"] = JToken.FromObject(examples); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithArgument("version", versionDate); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v2/projects/{projectId}/training_data/queries/{queryId}"); } } }
<?cs include:"doctype.cs" ?> <?cs include:"macros.cs" ?> <html> <?cs if:sdk.redirect ?> <head> <title>Redirecting...</title> <meta http-equiv="refresh" content="0;url=<?cs var:toroot ?>sdk/<?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>index.html<?cs /if ?>"> <link href="<?cs var:toroot ?>assets/android-developer-docs.css" rel="stylesheet" type="text/css" /> </head> <?cs else ?> <?cs include:"head_tag.cs" ?> <?cs /if ?> <body class="gc-documentation" itemscope itemtype="http://schema.org/CreativeWork"> <a name="top"></a> <?cs call:custom_masthead() ?> <?cs call:sdk_nav() ?> <?cs if:sdk.redirect ?> <div class="g-unit"> <div id="jd-content"> <p>Redirecting to <a href="<?cs var:toroot ?>sdk/<?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>index.html<?cs /if ?>"><?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>Download the SDK<?cs /if ?> </a> ...</p> <?cs else ?> <?cs # else, if NOT redirect ... # # # The following is for SDK/NDK pages # # ?> <div class="g-unit" id="doc-content" > <div id="jd-header" class="guide-header" > <span class="crumb">&nbsp;</span> <h1 itemprop="name"><?cs if:android.whichdoc == "online" ?>Download the <?cs /if ?><?cs var:page.title ?></h1> </div> <div id="jd-content" itemprop="description"> <?cs if:sdk.not_latest_version ?> <div class="special"> <p><strong>This is NOT the current Android SDK release.</strong></p> <p><a href="/sdk/index.html">Download the current Android SDK</a></p> </div> <?cs /if ?> <?cs if:ndk ?> <?cs # # # # # # # # the following is for the NDK # # (nested in if/else redirect) # # # # ?> <p>The Android NDK is a companion tool to the Android SDK that lets you build performance-critical portions of your apps in native code. It provides headers and libraries that allow you to build activities, handle user input, use hardware sensors, access application resources, and more, when programming in C or C++. If you write native code, your applications are still packaged into an .apk file and they still run inside of a virtual machine on the device. The fundamental Android application model does not change.</p> <p>Using native code does not result in an automatic performance increase, but always increases application complexity. If you have not run into any limitations using the Android framework APIs, you probably do not need the NDK. Read <a href="<?cs var:toroot ?>sdk/ndk/overview.html">What is the NDK?</a> for more information about what the NDK offers and whether it will be useful to you. </p> <p> The NDK is designed for use <em>only</em> in conjunction with the Android SDK. If you have not already installed and setup the <a href="http://developer.android.com/sdk/index.html">Android SDK</a>, please do so before downloading the NDK. </p> <table class="download"> <tr> <th>Platform</th> <th>Package</th> <th>Size</th> <th>MD5 Checksum</th> </tr> <tr> <td>Windows</td> <td> <a href="http://dl.google.com/android/ndk/<?cs var:ndk.win_download ?>"><?cs var:ndk.win_download ?></a> </td> <td><?cs var:ndk.win_bytes ?> bytes</td> <td><?cs var:ndk.win_checksum ?></td> </tr> <tr class="alt-color"> <td>Mac OS X (intel)</td> <td> <a href="http://dl.google.com/android/ndk/<?cs var:ndk.mac_download ?>"><?cs var:ndk.mac_download ?></a> </td> <td><?cs var:ndk.mac_bytes ?> bytes</td> <td><?cs var:ndk.mac_checksum ?></td> </tr> <tr> <td>Linux 32/64-bit (x86)</td> <td> <a href="http://dl.google.com/android/ndk/<?cs var:ndk.linux_download ?>"><?cs var:ndk.linux_download ?></a> </td> <td><?cs var:ndk.linux_bytes ?> bytes</td> <td><?cs var:ndk.linux_checksum ?></td> </tr> </table> <?cs else ?> <?cs # end if NDK ... # # # # # # # the following is for the SDK # # (nested in if/else redirect and if/else NDK) # # # # ?> <?cs if:android.whichdoc == "online" ?> <p>Welcome Developers! If you are new to the Android SDK, please read the steps below, for an overview of how to set up the SDK. </p> <p>If you're already using the Android SDK, you should update to the latest tools or platform using the <em>Android SDK and AVD Manager</em>, rather than downloading a new SDK starter package. See <a href="<?cs var:toroot ?>sdk/adding-components.html">Adding SDK Components</a>.</p> <table class="download"> <tr> <th>Platform</th> <th>Package</th> <th>Size</th> <th>MD5 Checksum</th> </tr> <tr> <td rowspan="2">Windows</td> <td> <a onclick="onDownload(this)" href="http://dl.google.com/android/<?cs var:sdk.win_download ?>"><?cs var:sdk.win_download ?></a> </td> <td><?cs var:sdk.win_bytes ?> bytes</td> <td><?cs var:sdk.win_checksum ?></td> </tr> <tr> <!-- blank TD from Windows rowspan --> <td> <a onclick="onDownload(this)" href="http://dl.google.com/android/<?cs var:sdk.win_installer ?>"><?cs var:sdk.win_installer ?></a> (Recommended) </td> <td><?cs var:sdk.win_installer_bytes ?> bytes</td> <td><?cs var:sdk.win_installer_checksum ?></td> </tr> <tr class="alt-color"> <td>Mac OS X (intel)</td> <td> <a onclick="onDownload(this)" href="http://dl.google.com/android/<?cs var:sdk.mac_download ?>"><?cs var:sdk.mac_download ?></a> </td> <td><?cs var:sdk.mac_bytes ?> bytes</td> <td><?cs var:sdk.mac_checksum ?></td> </tr> <tr> <td>Linux (i386)</td> <td> <a onclick="onDownload(this)" href="http://dl.google.com/android/<?cs var:sdk.linux_download ?>"><?cs var:sdk.linux_download ?></a> </td> <td><?cs var:sdk.linux_bytes ?> bytes</td> <td><?cs var:sdk.linux_checksum ?></td> </tr> </table> <div id="next-steps" style="display:none"> <p><b><em><span id="filename"></span></em> is now downloading. Follow the steps below to get started.</b></p> </div> <script type="text/javascript"> function onDownload(link) { $("#filename").text($(link).html()); $("#next-steps").show(); } </script> <?cs else ?> <?cs # end if online ?> <?cs if:sdk.preview ?><?cs # it's preview offline docs ?> <p>Welcome developers! We are pleased to provide you with a preview SDK for the upcoming Android 3.0 release, to give you a head-start on developing applications for it. </p> <p>See the <a href="<?cs var:toroot ?>sdk/preview/start.html">Getting Started</a> document for more information about how to set up the preview SDK and get started.</p> <style type="text/css"> .non-preview { display:none; } </style> <?cs else ?><?cs # it's normal offline docs ?> <style type="text/css"> p.offline-message { display:block; } p.online-message { display:none; } </style> <?cs /if ?> <?cs /if ?> <?cs # end if/else online ?> <?cs /if ?> <?cs # end if/else NDK ?> <?cs /if ?> <?cs # end if/else redirect ?> <?cs call:tag_list(root.descr) ?> </div><!-- end jd-content --> <?cs if:!sdk.redirect ?> <?cs include:"footer.cs" ?> <?cs /if ?> </div><!-- end g-unit --> <?cs include:"trailer.cs" ?> </body> </html>
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class CountTests { public class Count007 { private static int Count001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.Count<int>(); var rst2 = q.Count<int>(); return ((rst1 == rst2) ? 0 : 1); } private static int Count002() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; var rst1 = q.Count<string>(); var rst2 = q.Count<string>(); return ((rst1 == rst2) ? 0 : 1); } public static int Main() { int ret = RunTest(Count001) + RunTest(Count002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count1a { // source implements ICollection<T> and source is empty public static int Test1a() { int[] data = { }; int expected = 0; var actual = data.Count(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count1b { // source is empty public static int Test1b() { int[] data = { }; Func<int, bool> predicate = Functions.IsEven; int expected = 0; var actual = data.Count(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count2a { // source implements ICollection<T> and source is empty public static int Test2a() { int?[] data = { -10, 4, 9, null, 11 }; int expected = 5; var actual = data.Count(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count2b { // source has one element and predicate is true public static int Test2b() { int[] data = { 4 }; Func<int, bool> predicate = Functions.IsEven; int expected = 1; var actual = data.Count(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count3a { // source does NOT implement ICollection<T> and source is empty public static int Test3a() { IEnumerable<int> data = Functions.NumRange(0, 0); int expected = 0; var actual = data.Count(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test3a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count3b { // source has one element and predicate is false public static int Test3b() { int[] data = { 5 }; Func<int, bool> predicate = Functions.IsEven; int expected = 0; var actual = data.Count(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test3b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count4a { // source does NOT implement ICollection<T> and source has one element public static int Test4a() { IEnumerable<int> data = Functions.NumRange(5, 1); int expected = 1; var actual = data.Count(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test4a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count4b { // source has limited number of elements and predicate true for 1st and last element public static int Test4b() { int[] data = { 2, 5, 7, 9, 29, 10 }; Func<int, bool> predicate = Functions.IsEven; int expected = 2; var actual = data.Count(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test4b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count5a { // source does NOT implement ICollection<T> and source has > 1 elements public static int Test5a() { IEnumerable<int> data = Functions.NumRange(5, 10); int expected = 10; var actual = data.Count(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test5a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Count5b { // source has limited number of elements and predicate true for all the elements public static int Test5b() { int[] data = { 2, 20, 22, 100, 50, 10 }; Func<int, bool> predicate = Functions.IsEven; int expected = 6; var actual = data.Count(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test5b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
/// /// MonoWSDL.cs -- a WSDL to proxy code generator. /// /// Author: Erik LeBel (eriklebel@yahoo.ca) /// Lluis Sanchez (lluis@novell.com) /// /// Copyright (C) 2003, Erik LeBel, /// using System; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; using System.Collections; using System.Collections.Specialized; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Net; using System.Web.Services.Description; using System.Web.Services.Discovery; using System.Web.Services; using Microsoft.CSharp; namespace Mono.WebServices { public class Driver { string ProductId = "Web Services Description Language Utility\nMono Framework v" + Environment.Version; const string UsageMessage = "wsdl [options] {path | URL} {path | URL} ...\n\n" + " -d, -domain:domain Domain of username for server authentication.\n" + " -l, -language:language Language of generated code. Allowed CS (default)\n" + " and VB. You can also specify the fully qualified\n" + " name of a class that implements the\n" + " System.CodeDom.Compiler.CodeDomProvider Class.\n" + " -n, -namespace:ns The namespace of the generated code, default\n" + " namespace if none.\n" + " -nologo Surpress the startup logo.\n" + " -o, -out:filename The target file for generated code.\n" + " -p, -password:pwd Password used to contact the server.\n" + " -protocol:protocol Protocol to implement. Allowed: Soap (default),\n" + " HttpGet or HttpPost.\n" + " -fields Generate fields instead of properties in data\n" + " classes.\n" + " -server Generate server instead of client proxy code.\n" + " -u, -username:username Username used to contact the server.\n" + " -proxy:url Address of the proxy.\n" + " -pu, -proxyusername:username Username used to contact the proxy.\n" + " -pp, -proxypassword:pwd Password used to contact the proxy.\n" + " -pd, -proxydomain:domain Domain of username for proxy authentication.\n" + " -urlkey, -appsettingurlkey:key Configuration key that contains the default\n" + " url for the generated WS proxy.\n" + " -baseurl, -appsettingbaseurl:url Base url to use when constructing the\n" + " service url.\n" + " -sample:[binding/]operation Display a sample SOAP request and response.\n" + " -? Display this message\n" + "\n" + "Options can be of the forms -option, --option or /option\n"; ArrayList descriptions = new ArrayList (); ArrayList schemas = new ArrayList (); bool noLogo; bool help; string sampleSoap; string proxyAddress; string proxyDomain; string proxyPassword; string proxyUsername; string username; string password; string domain; string applicationSignature; string appSettingURLKey; string appSettingBaseURL; string language = "CS"; string ns; string outFilename; string protocol = "Soap"; ServiceDescriptionImportStyle style; CodeGenerationOptions options = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; bool verbose; StringCollection urls = new StringCollection (); /// /// <summary> /// Application entry point. /// </summary> /// public static int Main(string[] args) { Driver d = new Driver(); return d.Run(args); } Driver() { applicationSignature = ProductId; } int Run (string[] args) { try { // parse command line arguments foreach (string argument in args) ImportArgument(argument); if (noLogo == false) Console.WriteLine(ProductId); if (help || urls.Count == 0) { Console.WriteLine(UsageMessage); return 0; } CodeCompileUnit codeUnit = new CodeCompileUnit(); CodeNamespace proxyCode = GetCodeNamespace(); codeUnit.Namespaces.Add (proxyCode); WebReferenceCollection references = new WebReferenceCollection (); foreach (string murl in urls) { DiscoveryClientProtocol dcc = CreateClient (); string url = murl; if (!url.StartsWith ("http://") && !url.StartsWith ("https://") && !url.StartsWith ("file://")) url = new Uri (Path.GetFullPath (url)).ToString (); dcc.DiscoverAny (url); dcc.ResolveAll (); WebReference reference = new WebReference (dcc.Documents, proxyCode, protocol, appSettingURLKey, appSettingBaseURL); references.Add (reference); if (sampleSoap != null) ConsoleSampleGenerator.Generate (descriptions, schemas, sampleSoap, protocol); } if (sampleSoap != null) return 0; // generate the code if (GenerateCode (references, codeUnit)) return 1; else return 0; } catch (Exception exception) { Console.WriteLine("Error: {0}", exception.Message); // Supress this except for when debug is enabled Console.WriteLine("Stack:\n {0}", exception.StackTrace); return 2; } } /// /// <summary> /// Generate code for the specified ServiceDescription. /// </summary> /// public bool GenerateCode (WebReferenceCollection references, CodeCompileUnit codeUnit) { bool hasWarnings = false; CodeDomProvider provider = GetProvider(); ICodeGenerator generator = provider.CreateGenerator(); StringCollection validationWarnings; validationWarnings = ServiceDescriptionImporter.GenerateWebReferences (references, options, style, generator, codeUnit, verbose); for (int n=0; n<references.Count; n++) { WebReference wr = references [n]; BasicProfileViolationCollection violations = new BasicProfileViolationCollection (); if (!WebServicesInteroperability.CheckConformance (WsiClaims.BP10, wr, violations)) { wr.Warnings |= ServiceDescriptionImportWarnings.WsiConformance; } if (wr.Warnings != 0) { if (!hasWarnings) { WriteText ("", 0, 0); WriteText ("There where some warnings while generating the code:", 0, 0); } WriteText ("", 0, 0); WriteText (urls[n], 2, 2); if ((wr.Warnings & ServiceDescriptionImportWarnings.WsiConformance) > 0) { WriteText ("- This web reference does not conform to WS-I Basic Profile v1.0", 4, 6); foreach (BasicProfileViolation vio in violations) { WriteText (vio.NormativeStatement + ": " + vio.Details, 8, 8); foreach (string ele in vio.Elements) WriteText ("* " + ele, 10, 12); } } if ((wr.Warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0) WriteText ("- WARNING: No proxy class was generated", 4, 6); if ((wr.Warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0) WriteText ("- WARNING: The proxy class generated includes no methods", 4, 6); if ((wr.Warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0) WriteText ("- WARNING: At least one optional extension has been ignored", 4, 6); if ((wr.Warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0) WriteText ("- WARNING: At least one necessary extension has been ignored", 4, 6); if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0) WriteText ("- WARNING: At least one binding is of an unsupported type and has been ignored", 4, 6); if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0) WriteText ("- WARNING: At least one operation is of an unsupported type and has been ignored", 4, 6); hasWarnings = true; } } if (hasWarnings) WriteText ("",0,0); string filename = outFilename; bool hasBindings = false; foreach (object doc in references[0].Documents.Values) { ServiceDescription desc = doc as ServiceDescription; if (desc == null) continue; if (desc.Services.Count > 0 && filename == null) filename = desc.Services[0].Name + "." + provider.FileExtension; if (desc.Bindings.Count > 0 || desc.Services.Count > 0) hasBindings = true; } if (filename == null) filename = "output." + provider.FileExtension; if (hasBindings) { WriteText ("Writing file '" + filename + "'", 0, 0); StreamWriter writer = new StreamWriter(filename); CodeGeneratorOptions compilerOptions = new CodeGeneratorOptions(); generator.GenerateCodeFromCompileUnit (codeUnit, writer, compilerOptions); writer.Close(); } return hasWarnings; } /// /// <summary> /// Create the CodeNamespace with the generator's signature commented in. /// </summary> /// CodeNamespace GetCodeNamespace() { CodeNamespace codeNamespace = new CodeNamespace(ns); if (applicationSignature != null) { codeNamespace.Comments.Add(new CodeCommentStatement("\n This source code was auto-generated by " + applicationSignature + "\n")); } return codeNamespace; } /// /// <summary/> /// void WriteCodeUnit(CodeCompileUnit codeUnit, string serviceName) { CodeDomProvider provider = GetProvider(); ICodeGenerator generator = provider.CreateGenerator(); CodeGeneratorOptions options = new CodeGeneratorOptions(); string filename; if (outFilename != null) filename = outFilename; else filename = serviceName + "." + provider.FileExtension; Console.WriteLine ("Writing file '{0}'", filename); StreamWriter writer = new StreamWriter(filename); generator.GenerateCodeFromCompileUnit(codeUnit, writer, options); writer.Close(); } /// /// <summary> /// Fetch the Code Provider for the language specified by the 'language' members. /// </summary> /// private CodeDomProvider GetProvider() { CodeDomProvider provider; switch (language.ToUpper ()) { case "CS": provider = new CSharpCodeProvider (); break; case "VB": provider = new Microsoft.VisualBasic.VBCodeProvider (); break; default: Type type = Type.GetType(language); if (type != null) { return (CodeDomProvider) Activator.CreateInstance (type); } throw new Exception ("Unknown language"); } return provider; } /// /// <summary> /// Interperet the command-line arguments and configure the relavent components. /// </summary> /// void ImportArgument(string argument) { string optionValuePair; if (argument.StartsWith("--")) { optionValuePair = argument.Substring(2); } else if (argument.StartsWith("/") || argument.StartsWith("-")) { optionValuePair = argument.Substring(1); } else { urls.Add (argument); return; } string option; string value; int indexOfEquals = optionValuePair.IndexOf(':'); if (indexOfEquals > 0) { option = optionValuePair.Substring(0, indexOfEquals); value = optionValuePair.Substring(indexOfEquals + 1); } else { option = optionValuePair; value = null; } switch (option) { case "appsettingurlkey": case "urlkey": appSettingURLKey = value; break; case "appsettingbaseurl": case "baseurl": appSettingBaseURL = value; break; case "d": case "domain": domain = value; break; case "l": case "language": language = value; break; case "n": case "namespace": ns = value; break; case "nologo": noLogo = true; break; case "o": case "out": outFilename = value; break; case "p": case "password": password = value; break; case "protocol": protocol = value; break; case "proxy": proxyAddress = value; break; case "proxydomain": case "pd": proxyDomain = value; break; case "proxypassword": case "pp": proxyPassword = value; break; case "proxyusername": case "pu": proxyUsername = value; break; case "server": style = ServiceDescriptionImportStyle.Server; break; case "u": case "username": username = value; break; case "verbose": verbose = true; break; case "fields": options &= ~CodeGenerationOptions.GenerateProperties; break; case "sample": sampleSoap = value; break; case "?": help = true; break; default: if (argument.StartsWith ("/") && argument.IndexOfAny (Path.InvalidPathChars) == -1) { urls.Add (argument); break; } else throw new Exception("Unknown option " + option); } } DiscoveryClientProtocol CreateClient () { DiscoveryClientProtocol dcc = new DiscoveryClientProtocol (); if (username != null || password != null || domain != null) { NetworkCredential credentials = new NetworkCredential(); if (username != null) credentials.UserName = username; if (password != null) credentials.Password = password; if (domain != null) credentials.Domain = domain; dcc.Credentials = credentials; } if (proxyAddress != null) { WebProxy proxy = new WebProxy (proxyAddress); if (proxyUsername != null || proxyPassword != null || proxyDomain != null) { NetworkCredential credentials = new NetworkCredential(); if (proxyUsername != null) credentials.UserName = proxyUsername; if (proxyPassword != null) credentials.Password = proxyPassword; if (proxyDomain != null) credentials.Domain = proxyDomain; proxy.Credentials = credentials; } } return dcc; } static void WriteText (string text, int initialLeftMargin, int leftMargin) { int n = 0; int margin = initialLeftMargin; int maxCols = 80; if (text == "") { Console.WriteLine (); return; } while (n < text.Length) { int col = margin; int lastWhite = -1; int sn = n; while (col < maxCols && n < text.Length) { if (char.IsWhiteSpace (text[n])) lastWhite = n; col++; n++; } if (lastWhite == -1 || col < maxCols) lastWhite = n; else if (col >= maxCols) n = lastWhite + 1; Console.WriteLine (new String (' ', margin) + text.Substring (sn, lastWhite - sn)); margin = leftMargin; } } } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.IO; using System.Security; using SearchOption = System.IO.SearchOption; namespace Alphaleonis.Win32.Filesystem { partial class Directory { #region .NET /// <summary>Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path) { return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath); } /// <summary>Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { var options = DirectoryEnumerationOptions.FilesAndFolders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0); return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, PathFormat.RelativePath); } #endregion // .NET /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { var options = DirectoryEnumerationOptions.FilesAndFolders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0); return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, path, Path.WildcardStarMatchAll, options, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(null, path, searchPattern, options, pathFormat); } #region Transactional /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption) { var options = DirectoryEnumerationOptions.FilesAndFolders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0); return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>, and optionally searches subdirectories.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/> and <paramref name="searchOption"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="searchOption"> /// One of the <see cref="SearchOption"/> enumeration values that specifies whether the <paramref name="searchOption"/> /// should include only the current directory or should include all subdirectories. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat) { var options = DirectoryEnumerationOptions.FilesAndFolders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0); return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, Path.WildcardStarMatchAll, options, pathFormat); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns an enumerable collection of file names and directory names that match a <paramref name="searchPattern"/> in a specified <paramref name="path"/>.</summary> /// <returns>An enumerable collection of file system entries in the directory specified by <paramref name="path"/> and that match the specified <paramref name="searchPattern"/>.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The directory to search.</param> /// <param name="searchPattern"> /// The search string to match against the names of directories in <paramref name="path"/>. /// This parameter can contain a combination of valid literal path and wildcard /// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions. /// </param> /// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static IEnumerable<string> EnumerateFileSystemEntriesTransacted(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosCore<string>(transaction, path, searchPattern, options, pathFormat); } #endregion // Transactional } }
using System; using System.Collections.Generic; using System.Text; using MMCar_Finder; using System.Drawing; using System.Windows.Forms; using MarkerFinderTest; using NavigationSimulator; using System.Threading; namespace OnlabNeuralis { public class CameraObjectPositionProvider : ICarPositionProvider, IObstaclePositionProvider, IFinishPositionProvider, ISampler { CameraDirectShow camera; MyMarkerFinder mf; PictureBox pb; private const int COUNT_MAX = 1; FinishState currentFinishState; CarModelState currentCarModelState; CarModelState sampledCarState; PositionAndOrientationPredictor finishPredictor; List<ObstacleModel> obstacles; List<ObstacleState> currentObstacleStates; Thread trainThread; bool running; public CameraObjectPositionProvider(PictureBox pb) { this.pb = pb; camera = new CameraDirectShow(); camera.OnNewFrame += new OnNewFrameDelegate(camera_OnNewFrame); camera.Start(); finishPredictor = new PositionAndOrientationPredictor(30, 10); obstacles = new List<ObstacleModel>(); currentCarModelState = new CarModelState(new PointD(ComMath.Normal(0.05, 0, 1, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(0.05, 0, 1, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), new PointD(0, 1)); currentFinishState = new FinishState(new PointD(ComMath.Normal(0.95, 0, 1, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(0.95, 0, 1, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), 0.5 * Math.PI); } void camera_OnNewFrame(Bitmap frame) { if (pb != null) pb.Image = frame; } public void StartMarkerFinding(Image background, Image carMarker, Image finishMarker) { List<Bitmap> markerlist = new List<Bitmap>(); markerlist.Add(new Bitmap(carMarker)); markerlist.Add(new Bitmap(finishMarker)); mf = new MyMarkerFinder(markerlist, new Bitmap(background)); } public void StartTrain() { trainThread = new Thread(new ThreadStart(run)); running = true; trainThread.IsBackground = true; trainThread.Start(); } public void run() { while (running) { finishPredictor.Train(); lock (obstacles) { foreach (ObstacleModel ops in obstacles) { lock (ops) { ops.state.pp.Train(); } } } Thread.Sleep(0); } } public void StopTrain() { running = false; } public Image GetImage() { return camera.GetBitmap(); } public void Simulate(IModelSimulator modelsim, CarModelInput input, double timestep) { CarModel model = new CarModel(GetCarState()); model.SimulateModel(input, modelsim, timestep); currentCarModelState = model.state; } public CarModelState GetCarState() { return sampledCarState; } public CarModel GetCarModel() { return new CarModel(currentCarModelState); } public List<ObstacleState> GetObstacleStates(int iteration) { if (iteration > 0) { List<ObstacleState> oss = new List<ObstacleState>(); lock (obstacles) { foreach (ObstacleModel om in obstacles) { lock (om) { List<PointD> p = om.state.pp.PredictNextPositions(iteration); if (p != null) oss.Add(new ObstacleState(p[iteration - 1], om.state.radius)); else oss.Add(new ObstacleState(om.state.pp.position, om.state.radius)); } } } return oss; } else { List<ObstacleState> ret = new List<ObstacleState>(); lock (obstacles) { foreach (ObstacleModel om in obstacles) { lock (om) { ret.Add(om.state); } } } return ret; } } public List<ObstacleModel> GetObstacleModels(int iteration) { if (iteration > 0) { List<ObstacleState> states = GetObstacleStates(iteration); List<ObstacleModel> list = new List<ObstacleModel>(); if (states != null) { foreach (ObstacleState os in states) { list.Add( new ObstacleModel(os.pp.position, os.radius)); } } return list; } else { return obstacles; } } public FinishState GetFinishState(int iteration) { if (iteration > 0) { List<PointD> p = finishPredictor.PredictNextPositions(iteration); List<PointD> o = finishPredictor.PredictNextOrientations(iteration); if ((p != null) && (o != null)) return new FinishState(p[iteration - 1], o[iteration - 1]); else return currentFinishState; } else { return currentFinishState; } } public FinishModel GetFinishModel(int iteration) { FinishModel fm = new FinishModel(GetFinishState(iteration)); fm.SetSelectedState(1, 0); return fm; } //public CarModelState GetState(int index) //{ // double[] ret = GetPosition(index); // CarModelState cs = new CarModelState(); // cs.Angle = -ret[2]; // //cs.Position = new PointD(ComMath.Normal(ret[0], 0, im.Width, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(im.Height - ret[1], 0, im.Height, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)); // return cs; //} public void TakeSample() { RunMarkerFinder(); sampledCarState = currentCarModelState; } private void RunMarkerFinder() { if (mf != null) { Bitmap frame = camera.GetBitmap(); List<Shape> shapes = null; shapes = mf.ProcessFrame(frame); bool carFound = false; bool finishFound = false; // finish currentObstacleStates = new List<ObstacleState>(); foreach (Shape s in shapes) { if ((s.index == 0) && (s.scale > 0.17) && (s.scale < 0.22)) { currentCarModelState = new CarModelState(new PointD(ComMath.Normal(s.pos.X, 0, frame.Width, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(s.pos.Y, 0, frame.Height, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), -Math.PI / 2 - s.rot); carFound = true; } else if ((s.index == 1) && (s.scale > 0.16) && (s.scale < 0.20)) { currentFinishState = new FinishState(new PointD(ComMath.Normal(s.pos.X, 0, frame.Width, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(s.pos.Y, 0, frame.Height, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), -Math.PI / 2 - s.rot); finishPredictor.AddPoint(currentFinishState.Position, currentFinishState.Orientation); finishFound = true; } else { currentObstacleStates.Add(new ObstacleState(new PointD(ComMath.Normal(s.pos.X, 0, frame.Width, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(s.pos.Y, 0, frame.Height, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), s.scale * 500)); //ide kell egy robusztus alg //ha zaj jon, akkor ne vegye be } } lock (obstacles) { List<ObstacleState> curObState = new List<ObstacleState>(currentObstacleStates); foreach (ObstacleModel ops in obstacles) { List<PointD> list = ops.state.pp.PredictNextPositions(1); ObstacleState osw =null; PointD pd; if (list != null) pd = list[0]; else pd = ops.state.pp.position; double mindist = double.MaxValue; foreach (ObstacleState os in curObState) { double dist = (os.pp.position.X - pd.X) * (os.pp.position.X - pd.X) + (os.pp.position.Y - pd.Y) * (os.pp.position.Y - pd.Y); if (dist < mindist) { mindist = dist; osw = os; } } if (osw != null) { lock (ops) { ops.state.pp.AddNewPosition(osw.pp.position); } curObState.Remove(osw); } else { //a predikcioval leptetjuk tovabb lock (ops) { ops.state.pp.AddNewPosition(pd); } } } foreach(ObstacleState os in curObState) { lock (obstacles) { ObstacleModel om = new ObstacleModel(os.pp.position, os.radius); om.SetSelectedState(1, 0); if (obstacles.Count < 1) obstacles.Add(om); } } } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using LB.Areas.HelpPage.ModelDescriptions; using LB.Areas.HelpPage.Models; namespace LB.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; namespace System.IO.Compression { //The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public class ZipArchiveEntry { #region Fields private const UInt16 DefaultVersionToExtract = 10; private ZipArchive _archive; private readonly Boolean _originallyInArchive; private readonly Int32 _diskNumberStart; private ZipVersionNeededValues _versionToExtract; //Also, always use same for version made by because MSDOS high byte is 0 private BitFlagValues _generalPurposeBitFlag; private CompressionMethodValues _storedCompressionMethod; private DateTimeOffset _lastModified; private Int64 _compressedSize; private Int64 _uncompressedSize; private Int64 _offsetOfLocalHeader; private Int64? _storedOffsetOfCompressedData; private UInt32 _crc32; private Byte[] _compressedBytes; private MemoryStream _storedUncompressedData; private Boolean _currentlyOpenForWrite; private Boolean _everOpenedForWrite; private Stream _outstandingWriteStream; private String _storedEntryName; private Byte[] _storedEntryNameBytes; //only apply to update mode private List<ZipGenericExtraField> _cdUnknownExtraFields; private List<ZipGenericExtraField> _lhUnknownExtraFields; private Byte[] _fileComment; private CompressionLevel? _compressionLevel; #endregion Fields //Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel) : this(archive, cd) { // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation // as it is a pugable component that completely encapsulates the meaning of compressionLevel. _compressionLevel = compressionLevel; } //Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd) { _archive = archive; _originallyInArchive = true; _diskNumberStart = cd.DiskNumberStart; _versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract; _generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag; CompressionMethod = (CompressionMethodValues)cd.CompressionMethod; _lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified)); _compressedSize = cd.CompressedSize; _uncompressedSize = cd.UncompressedSize; _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader; /* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength * but entryname/extra length could be different in LH */ _storedOffsetOfCompressedData = null; _crc32 = cd.Crc32; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = DecodeEntryName(cd.Filename); _lhUnknownExtraFields = null; //the cd should have these as null if we aren't in Update mode _cdUnknownExtraFields = cd.ExtraFields; _fileComment = cd.FileComment; _compressionLevel = null; } //Initializes new entry internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel) : this(archive, entryName) { // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation // as it is a pugable component that completely encapsulates the meaning of compressionLevel. _compressionLevel = compressionLevel; } //Initializes new entry internal ZipArchiveEntry(ZipArchive archive, String entryName) { _archive = archive; _originallyInArchive = false; _diskNumberStart = 0; _versionToExtract = ZipVersionNeededValues.Default; //this must happen before following two assignment _generalPurposeBitFlag = 0; CompressionMethod = CompressionMethodValues.Deflate; _lastModified = DateTimeOffset.Now; _compressedSize = 0; //we don't know these yet _uncompressedSize = 0; _offsetOfLocalHeader = 0; _storedOffsetOfCompressedData = null; _crc32 = 0; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = entryName; _cdUnknownExtraFields = null; _lhUnknownExtraFields = null; _fileComment = null; _compressionLevel = null; if (_storedEntryNameBytes.Length > UInt16.MaxValue) throw new ArgumentException(SR.EntryNamesTooLong); //grab the stream if we're in create mode if (_archive.Mode == ZipArchiveMode.Create) { _archive.AcquireArchiveStream(this); } } /// <summary> /// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null. /// </summary> public ZipArchive Archive { get { return _archive; } } /// <summary> /// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened. /// </summary> /// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception> public Int64 CompressedLength { get { Contract.Ensures(Contract.Result<Int64>() >= 0); if (_everOpenedForWrite) throw new InvalidOperationException(SR.LengthAfterWrite); return _compressedSize; } } /// <summary> /// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths. /// </summary> public String FullName { get { Contract.Ensures(Contract.Result<String>() != null); return _storedEntryName; } private set { if (value == null) throw new ArgumentNullException("FullName"); bool isUTF8; _storedEntryNameBytes = EncodeEntryName(value, out isUTF8); _storedEntryName = value; if (isUTF8) _generalPurposeBitFlag |= BitFlagValues.UnicodeFileName; else _generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName; if (ZipHelper.EndsWithDirChar(value)) VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory); } } /// <summary> /// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the /// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp, /// an indicator value of 1980 January 1 at midnight will be returned. /// </summary> /// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was /// opened in read-only mode.</exception> /// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the /// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time /// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception> public DateTimeOffset LastWriteTime { get { return _lastModified; } set { ThrowIfInvalidArchive(); if (_archive.Mode == ZipArchiveMode.Read) throw new NotSupportedException(SR.ReadOnlyArchive); if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite) throw new IOException(SR.FrozenAfterWrite); if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax) throw new ArgumentOutOfRangeException("value", SR.DateTimeOutOfRange); _lastModified = value; } } /// <summary> /// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened. /// </summary> /// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception> public Int64 Length { get { Contract.Ensures(Contract.Result<Int64>() >= 0); if (_everOpenedForWrite) throw new InvalidOperationException(SR.LengthAfterWrite); return _uncompressedSize; } } /// <summary> /// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character. /// </summary> public String Name { get { Contract.Ensures(Contract.Result<String>() != null); return Path.GetFileName(FullName); } } /// <summary> /// Deletes the entry from the archive. /// </summary> /// <exception cref="IOException">The entry is already open for reading or writing.</exception> /// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception> /// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception> public void Delete() { if (_archive == null) return; if (_currentlyOpenForWrite) throw new IOException(SR.DeleteOpenEntry); if (_archive.Mode != ZipArchiveMode.Update) throw new NotSupportedException(SR.DeleteOnlyInUpdate); _archive.ThrowIfDisposed(); _archive.RemoveEntry(this); _archive = null; UnloadStreams(); } /// <summary> /// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writeable and not seekable. If Update mode, the returned stream will be readable, writeable, seekable, and support SetLength. /// </summary> /// <returns>A Stream that represents the contents of the entry.</returns> /// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception> /// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception> public Stream Open() { Contract.Ensures(Contract.Result<Stream>() != null); ThrowIfInvalidArchive(); switch (_archive.Mode) { case ZipArchiveMode.Read: return OpenInReadMode(true); case ZipArchiveMode.Create: return OpenInWriteMode(); case ZipArchiveMode.Update: default: Debug.Assert(_archive.Mode == ZipArchiveMode.Update); return OpenInUpdateMode(); } } /// <summary> /// Returns the FullName of the entry. /// </summary> /// <returns>FullName of the entry</returns> public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FullName; } /* public void MoveTo(String destinationEntryName) { if (destinationEntryName == null) throw new ArgumentNullException("destinationEntryName"); if (String.IsNullOrEmpty(destinationEntryName)) throw new ArgumentException("destinationEntryName cannot be empty", "destinationEntryName"); if (_archive == null) throw new InvalidOperationException("Attempt to move a deleted entry"); if (_archive._isDisposed) throw new ObjectDisposedException(_archive.ToString()); if (_archive.Mode != ZipArchiveMode.Update) throw new NotSupportedException("MoveTo can only be used when the archive is in Update mode"); String oldFilename = _filename; _filename = destinationEntryName; if (_filenameLength > UInt16.MaxValue) { _filename = oldFilename; throw new ArgumentException("Archive entry names must be smaller than 2^16 bytes"); } } */ #region Privates internal Boolean EverOpenedForWrite { get { return _everOpenedForWrite; } } private Int64 OffsetOfCompressedData { get { if (_storedOffsetOfCompressedData == null) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); //by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength //to find start of data, but still using central directory size information if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader)) throw new InvalidDataException(SR.LocalFileHeaderCorrupt); _storedOffsetOfCompressedData = _archive.ArchiveStream.Position; } return _storedOffsetOfCompressedData.Value; } } private MemoryStream UncompressedData { get { if (_storedUncompressedData == null) { //this means we have never opened it before //if _uncompressedSize > Int32.MaxValue, it's still okay, because MemoryStream will just //grow as data is copied into it _storedUncompressedData = new MemoryStream((Int32)_uncompressedSize); if (_originallyInArchive) { using (Stream decompressor = OpenInReadMode(false)) { try { decompressor.CopyTo(_storedUncompressedData); } catch (InvalidDataException) { /* this is the case where the archive say the entry is deflate, but deflateStream * throws an InvalidDataException. This property should only be getting accessed in * Update mode, so we want to make sure _storedUncompressedData stays null so * that later when we dispose the archive, this entry loads the compressedBytes, and * copies them straight over */ _storedUncompressedData.Dispose(); _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; throw; } } } //if they start modifying it, we should make sure it will get deflated CompressionMethod = CompressionMethodValues.Deflate; } return _storedUncompressedData; } } private CompressionMethodValues CompressionMethod { get { return _storedCompressionMethod; } set { if (value == CompressionMethodValues.Deflate) VersionToExtractAtLeast(ZipVersionNeededValues.Deflate); _storedCompressionMethod = value; } } private Encoding DefaultSystemEncoding { // On the desktop, this was Encoding.GetEncoding(0), which gives you the encoding object // that corresponds too the default system codepage. // However, in ProjectN, not only Encoding.GetEncoding(Int32) is not exposed, but there is also // no guarantee that a notion of a default system code page exists on the OS. // In fact, we can really only rely on UTF8 and UTF16 being present on all platforms. // We fall back to UTF8 as this is what is used by ZIP when as the "unicode encoding". get { return Encoding.UTF8; // return Encoding.GetEncoding(0); } } private String DecodeEntryName(Byte[] entryNameBytes) { Debug.Assert(entryNameBytes != null); Encoding readEntryNameEncoding; if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0) { readEntryNameEncoding = (_archive == null) ? DefaultSystemEncoding : _archive.EntryNameEncoding ?? DefaultSystemEncoding; } else { readEntryNameEncoding = Encoding.UTF8; } return readEntryNameEncoding.GetString(entryNameBytes); } private Byte[] EncodeEntryName(String entryName, out bool isUTF8) { Debug.Assert(entryName != null); Encoding writeEntryNameEncoding; if (_archive != null && _archive.EntryNameEncoding != null) writeEntryNameEncoding = _archive.EntryNameEncoding; else writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName) ? Encoding.UTF8 : DefaultSystemEncoding; isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8); return writeEntryNameEncoding.GetBytes(entryName); } /* does almost everything you need to do to forget about this entry * writes the local header/data, gets rid of all the data, * closes all of the streams except for the very outermost one that * the user holds on to and is responsible for closing * * after calling this, and only after calling this can we be guaranteed * that we are reading to write the central directory * * should only throw an exception in extremely exceptional cases because it is called from dispose */ internal void WriteAndFinishLocalEntry() { CloseStreams(); WriteLocalFileHeaderAndDataIfNeeded(); UnloadStreams(); } //should only throw an exception in extremely exceptional cases because it is called from dispose internal void WriteCentralDirectoryFileHeader() { //This part is simple, because we should definitely know the sizes by this time BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); //_entryname only gets set when we read in or call moveTo. MoveTo does a check, and //reading in should not be able to produce a entryname longer than UInt16.MaxValue Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue); //decide if we need the Zip64 extra field: Zip64ExtraField zip64ExtraField = new Zip64ExtraField(); UInt32 compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated; Boolean zip64Needed = false; if (SizesTooLarge() #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ) { zip64Needed = true; compressedSizeTruncated = ZipHelper.Mask32Bit; uncompressedSizeTruncated = ZipHelper.Mask32Bit; //If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways zip64ExtraField.CompressedSize = _compressedSize; zip64ExtraField.UncompressedSize = _uncompressedSize; } else { compressedSizeTruncated = (UInt32)_compressedSize; uncompressedSizeTruncated = (UInt32)_uncompressedSize; } if (_offsetOfLocalHeader > UInt32.MaxValue #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ) { zip64Needed = true; offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit; //If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader; } else { offsetOfLocalHeaderTruncated = (UInt32)_offsetOfLocalHeader; } if (zip64Needed) VersionToExtractAtLeast(ZipVersionNeededValues.Zip64); //determine if we can fit zip64 extra field and original extra fields all in Int32 bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0) + (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0); UInt16 extraFieldLength; if (bigExtraFieldLength > UInt16.MaxValue) { extraFieldLength = (UInt16)(zip64Needed ? zip64ExtraField.TotalSize : 0); _cdUnknownExtraFields = null; } else { extraFieldLength = (UInt16)bigExtraFieldLength; } writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); writer.Write((UInt16)_versionToExtract); writer.Write((UInt16)_versionToExtract); //this is the version made by field. low byte is version needed, and high byte is 0 for MS DOS writer.Write((UInt16)_generalPurposeBitFlag); writer.Write((UInt16)CompressionMethod); writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32 writer.Write(_crc32); //UInt32 writer.Write(compressedSizeTruncated); //UInt32 writer.Write(uncompressedSizeTruncated); //UInt32 writer.Write((UInt16)_storedEntryNameBytes.Length); writer.Write(extraFieldLength); //UInt16 // This should hold because of how we read it originally in ZipCentralDirectoryFileHeader: Debug.Assert((_fileComment == null) || (_fileComment.Length <= UInt16.MaxValue)); writer.Write(_fileComment != null ? (UInt16)_fileComment.Length : (UInt16)0); //file comment length writer.Write((UInt16)0); //disk number start writer.Write((UInt16)0); //internal file attributes writer.Write((UInt32)0); //external file attributes writer.Write(offsetOfLocalHeaderTruncated); //offset of local header writer.Write(_storedEntryNameBytes); //write extra fields if (zip64Needed) zip64ExtraField.WriteBlock(_archive.ArchiveStream); if (_cdUnknownExtraFields != null) ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream); if (_fileComment != null) writer.Write(_fileComment); } //returns false if fails, will get called on every entry before closing in update mode //can throw InvalidDataException internal Boolean LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded() { String message; //we should have made this exact call in _archive.Init through ThrowIfOpenable Debug.Assert(IsOpenable(false, true, out message)); //load local header's extra fields. it will be null if we couldn't read for some reason if (_originallyInArchive) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); _lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader); } if (!_everOpenedForWrite && _originallyInArchive) { //we know that it is openable at this point _compressedBytes = new Byte[_compressedSize]; _archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin); //casting _compressedSize to Int32 here is safe because of check in IsOpenable ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes, (Int32)_compressedSize); } return true; } internal void ThrowIfNotOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory) { String message; if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out message)) throw new InvalidDataException(message); } private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, Boolean leaveBackingStreamOpen, EventHandler onClose) { //stream stack: backingStream -> DeflateStream -> CheckSumWriteStream //we should always be compressing with deflate. Stored is used for empty files, but we don't actually //call through this function for that - we just write the stored value in the header Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate); Stream compressorStream = _compressionLevel.HasValue ? new DeflateStream(backingStream, _compressionLevel.Value, leaveBackingStreamOpen) : new DeflateStream(backingStream, CompressionMode.Compress, leaveBackingStreamOpen); Boolean isIntermediateStream = true; Boolean leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream; var checkSumStream = new CheckSumAndSizeWriteStream( compressorStream, backingStream, leaveCompressorStreamOpenOnClose, this, onClose, (Int64 initialPosition, Int64 currentPosition, UInt32 checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler closeHandler) => { thisRef._crc32 = checkSum; thisRef._uncompressedSize = currentPosition; thisRef._compressedSize = backing.Position - initialPosition; if (closeHandler != null) closeHandler(thisRef, EventArgs.Empty); }); return checkSumStream; } private Stream GetDataDecompressor(Stream compressedStreamToRead) { Stream uncompressedStream = null; switch (CompressionMethod) { case CompressionMethodValues.Deflate: uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress); break; case CompressionMethodValues.Stored: default: //we can assume that only deflate/stored are allowed because we assume that //IsOpenable is checked before this function is called Debug.Assert(CompressionMethod == CompressionMethodValues.Stored); uncompressedStream = compressedStreamToRead; break; } return uncompressedStream; } private Stream OpenInReadMode(Boolean checkOpenable) { if (checkOpenable) ThrowIfNotOpenable(true, false); Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize); return GetDataDecompressor(compressedStream); } private Stream OpenInWriteMode() { if (_everOpenedForWrite) throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime); //we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed Debug.Assert(_archive.IsStillArchiveStreamOwner(this)); _everOpenedForWrite = true; CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object o, EventArgs e) => { //release the archive stream var entry = (ZipArchiveEntry)o; entry._archive.ReleaseArchiveStream(entry); entry._outstandingWriteStream = null; }); _outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this); return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true); } private Stream OpenInUpdateMode() { if (_currentlyOpenForWrite) throw new IOException(SR.UpdateModeOneStream); ThrowIfNotOpenable(true, true); _everOpenedForWrite = true; _currentlyOpenForWrite = true; //always put it at the beginning for them UncompressedData.Seek(0, SeekOrigin.Begin); return new WrappedStream(UncompressedData, this, thisRef => { //once they close, we know uncompressed length, but still not compressed length //so we don't fill in any size information //those fields get figured out when we call GetCompressor as we write it to //the actual archive thisRef._currentlyOpenForWrite = false; }); } private Boolean IsOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory, out String message) { message = null; if (_originallyInArchive) { if (needToUncompress) { if (CompressionMethod != CompressionMethodValues.Stored && CompressionMethod != CompressionMethodValues.Deflate) { message = SR.UnsupportedCompression; return false; } } if (_diskNumberStart != _archive.NumberOfThisDisk) { message = SR.SplitSpanned; return false; } if (_offsetOfLocalHeader > _archive.ArchiveStream.Length) { message = SR.LocalFileHeaderCorrupt; return false; } _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader)) { message = SR.LocalFileHeaderCorrupt; return false; } //when this property gets called, some duplicated work if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length) { message = SR.LocalFileHeaderCorrupt; return false; } //this limitation exists because a) it is unreasonable to load > 4GB into memory //but also because the stream reading functions make it hard if (needToLoadIntoMemory) { if (_compressedSize > Int32.MaxValue) { message = SR.EntryTooLarge; return false; } } } return true; } private Boolean SizesTooLarge() { return _compressedSize > UInt32.MaxValue || _uncompressedSize > UInt32.MaxValue; } //return value is true if we allocated an extra field for 64 bit headers, un/compressed size private Boolean WriteLocalFileHeader(Boolean isEmptyFile) { BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); //_entryname only gets set when we read in or call moveTo. MoveTo does a check, and //reading in should not be able to produce a entryname longer than UInt16.MaxValue Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue); //decide if we need the Zip64 extra field: Zip64ExtraField zip64ExtraField = new Zip64ExtraField(); Boolean zip64Used = false; UInt32 compressedSizeTruncated, uncompressedSizeTruncated; //if we already know that we have an empty file don't worry about anything, just do a straight shot of the header if (isEmptyFile) { CompressionMethod = CompressionMethodValues.Stored; compressedSizeTruncated = 0; uncompressedSizeTruncated = 0; Debug.Assert(_compressedSize == 0); Debug.Assert(_uncompressedSize == 0); Debug.Assert(_crc32 == 0); } else { //if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit //if we are using the data descriptor, then sizes and crc should be set to 0 in the header if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile) { _generalPurposeBitFlag |= BitFlagValues.DataDescriptor; zip64Used = false; compressedSizeTruncated = 0; uncompressedSizeTruncated = 0; //the crc should not have been set if we are in create mode, but clear it just to be sure Debug.Assert(_crc32 == 0); } else //if we are not in streaming mode, we have to decide if we want to write zip64 headers { if (SizesTooLarge() #if DEBUG_FORCE_ZIP64 || (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update) #endif ) { zip64Used = true; compressedSizeTruncated = ZipHelper.Mask32Bit; uncompressedSizeTruncated = ZipHelper.Mask32Bit; //prepare Zip64 extra field object. If we have one of the sizes, the other must go in there zip64ExtraField.CompressedSize = _compressedSize; zip64ExtraField.UncompressedSize = _uncompressedSize; VersionToExtractAtLeast(ZipVersionNeededValues.Zip64); } else { zip64Used = false; compressedSizeTruncated = (UInt32)_compressedSize; uncompressedSizeTruncated = (UInt32)_uncompressedSize; } } } //save offset _offsetOfLocalHeader = writer.BaseStream.Position; //calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important Int32 bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0) + (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0); UInt16 extraFieldLength; if (bigExtraFieldLength > UInt16.MaxValue) { extraFieldLength = (UInt16)(zip64Used ? zip64ExtraField.TotalSize : 0); _lhUnknownExtraFields = null; } else { extraFieldLength = (UInt16)bigExtraFieldLength; } //write header writer.Write(ZipLocalFileHeader.SignatureConstant); writer.Write((UInt16)_versionToExtract); writer.Write((UInt16)_generalPurposeBitFlag); writer.Write((UInt16)CompressionMethod); writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32 writer.Write(_crc32); //UInt32 writer.Write(compressedSizeTruncated); //UInt32 writer.Write(uncompressedSizeTruncated); //UInt32 writer.Write((UInt16)_storedEntryNameBytes.Length); writer.Write(extraFieldLength); //UInt16 writer.Write(_storedEntryNameBytes); if (zip64Used) zip64ExtraField.WriteBlock(_archive.ArchiveStream); if (_lhUnknownExtraFields != null) ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream); return zip64Used; } private void WriteLocalFileHeaderAndDataIfNeeded() { //_storedUncompressedData gets frozen here, and is what gets written to the file if (_storedUncompressedData != null || _compressedBytes != null) { if (_storedUncompressedData != null) { _uncompressedSize = _storedUncompressedData.Length; //The compressor fills in CRC and sizes //The DirectToArchiveWriterStream writes headers and such using (Stream entryWriter = new DirectToArchiveWriterStream( GetDataCompressor(_archive.ArchiveStream, true, null), this)) { _storedUncompressedData.Seek(0, SeekOrigin.Begin); _storedUncompressedData.CopyTo(entryWriter); _storedUncompressedData.Dispose(); _storedUncompressedData = null; } } else { // we know the sizes at this point, so just go ahead and write the headers if (_uncompressedSize == 0) CompressionMethod = CompressionMethodValues.Stored; WriteLocalFileHeader(false); // we just want to copy the compressed bytes straight over, but the stream apis // don't handle larger than 32 bit values, so we just wrap it in a stream using (MemoryStream compressedStream = new MemoryStream(_compressedBytes)) { compressedStream.CopyTo(_archive.ArchiveStream); } } } else //there is no data in the file, but if we are in update mode, we still need to write a header { if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite) { _everOpenedForWrite = true; WriteLocalFileHeader(true); } } } /* Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header, * writes them, then seeks back to where you started * Assumes that the stream is currently at the end of the data */ private void WriteCrcAndSizesInLocalHeader(Boolean zip64HeaderUsed) { Int64 finalPosition = _archive.ArchiveStream.Position; BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); Boolean zip64Needed = SizesTooLarge() #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ; Boolean pretendStreaming = zip64Needed && !zip64HeaderUsed; UInt32 compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_compressedSize; UInt32 uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_uncompressedSize; /* first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because * we can't go back and give ourselves the space that the extra field needs. * we do this by setting the correct property in the bit flag */ if (pretendStreaming) { _generalPurposeBitFlag |= BitFlagValues.DataDescriptor; _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToBitFlagFromHeaderStart, SeekOrigin.Begin); writer.Write((UInt16)_generalPurposeBitFlag); } /* next step is fill out the 32-bit size values in the normal header. we can't assume that * they are correct. we also write the CRC */ _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart, SeekOrigin.Begin); if (!pretendStreaming) { writer.Write(_crc32); writer.Write(compressedSizeTruncated); writer.Write(uncompressedSizeTruncated); } else //but if we are pretending to stream, we want to fill in with zeroes { writer.Write((UInt32)0); writer.Write((UInt32)0); writer.Write((UInt32)0); } /* next step: if we wrote the 64 bit header initially, a different implementation might * try to read it, even if the 32-bit size values aren't masked. thus, we should always put the * correct size information in there. note that order of uncomp/comp is switched, and these are * 64-bit values * also, note that in order for this to be correct, we have to insure that the zip64 extra field * is alwasy the first extra field that is written */ if (zip64HeaderUsed) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader + _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField, SeekOrigin.Begin); writer.Write(_uncompressedSize); writer.Write(_compressedSize); _archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin); } // now go to the where we were. assume that this is the end of the data _archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin); /* if we are pretending we did a stream write, we want to write the data descriptor out * the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use * 64-bit sizes */ if (pretendStreaming) { writer.Write(_crc32); writer.Write(_compressedSize); writer.Write(_uncompressedSize); } } private void WriteDataDescriptor() { // data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible // signature is optional but recommended by the spec BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); writer.Write(ZipLocalFileHeader.DataDescriptorSignature); writer.Write(_crc32); if (SizesTooLarge()) { writer.Write(_compressedSize); writer.Write(_uncompressedSize); } else { writer.Write((UInt32)_compressedSize); writer.Write((UInt32)_uncompressedSize); } } private void UnloadStreams() { if (_storedUncompressedData != null) _storedUncompressedData.Dispose(); _compressedBytes = null; _outstandingWriteStream = null; } private void CloseStreams() { //if the user left the stream open, close the underlying stream for them if (_outstandingWriteStream != null) { _outstandingWriteStream.Dispose(); } } private void VersionToExtractAtLeast(ZipVersionNeededValues value) { if (_versionToExtract < value) { _versionToExtract = value; } } private void ThrowIfInvalidArchive() { if (_archive == null) throw new InvalidOperationException(SR.DeletedEntry); _archive.ThrowIfDisposed(); } #endregion Privates #region Nested Types private class DirectToArchiveWriterStream : Stream { #region fields private Int64 _position; private CheckSumAndSizeWriteStream _crcSizeStream; private Boolean _everWritten; private Boolean _isDisposed; private ZipArchiveEntry _entry; private Boolean _usedZip64inLH; private Boolean _canWrite; #endregion #region constructors //makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive //this class calls other functions on ZipArchiveEntry that write directly to the archive public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry) { _position = 0; _crcSizeStream = crcSizeStream; _everWritten = false; _isDisposed = false; _entry = entry; _usedZip64inLH = false; _canWrite = true; } #endregion #region properties public override Int64 Length { get { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } } public override Int64 Position { get { Contract.Ensures(Contract.Result<Int64>() >= 0); ThrowIfDisposed(); return _position; } set { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } } public override Boolean CanRead { get { return false; } } public override Boolean CanSeek { get { return false; } } public override Boolean CanWrite { get { return _canWrite; } } #endregion #region methods private void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName); } public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) { ThrowIfDisposed(); throw new NotSupportedException(SR.ReadingNotSupported); } public override Int64 Seek(Int64 offset, SeekOrigin origin) { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } public override void SetLength(Int64 value) { ThrowIfDisposed(); throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting); } //careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented //they must set _everWritten, etc. public override void Write(Byte[] buffer, Int32 offset, Int32 count) { //we can't pass the argument checking down a level if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentNeedNonNegative); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentNeedNonNegative); if ((buffer.Length - offset) < count) throw new ArgumentException(SR.OffsetLengthInvalid); Contract.EndContractBlock(); ThrowIfDisposed(); Debug.Assert(CanWrite); //if we're not actually writing anything, we don't want to trigger the header if (count == 0) return; if (!_everWritten) { _everWritten = true; //write local header, we are good to go _usedZip64inLH = _entry.WriteLocalFileHeader(false); } _crcSizeStream.Write(buffer, offset, count); _position += count; } public override void Flush() { ThrowIfDisposed(); Debug.Assert(CanWrite); _crcSizeStream.Flush(); } protected override void Dispose(Boolean disposing) { if (disposing && !_isDisposed) { _crcSizeStream.Dispose(); //now we have size/crc info if (!_everWritten) { //write local header, no data, so we use stored _entry.WriteLocalFileHeader(true); } else { //go back and finish writing if (_entry._archive.ArchiveStream.CanSeek) //finish writing local header if we have seek capabilities _entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH); else //write out data descriptor if we don't have seek capabilities _entry.WriteDataDescriptor(); } _canWrite = false; _isDisposed = true; } base.Dispose(disposing); } #endregion } // DirectToArchiveWriterStream [Flags] private enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 } private enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8 } private enum OpenableValues { Openable, FileNonExistent, FileTooLarge } #endregion Nested Types } // class ZipArchiveEntry } // namespace
// // ILProcessor.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Collections.Generic; namespace Mono.Cecil.Cil { public sealed class ILProcessor { readonly MethodBody body; readonly Collection<Instruction> instructions; public MethodBody Body { get { return body; } } internal ILProcessor (MethodBody body) { this.body = body; this.instructions = body.Instructions; } public Instruction Create (OpCode opcode) { return Instruction.Create (opcode); } public Instruction Create (OpCode opcode, TypeReference type) { return Instruction.Create (opcode, type); } public Instruction Create (OpCode opcode, CallSite site) { return Instruction.Create (opcode, site); } public Instruction Create (OpCode opcode, MethodReference method) { return Instruction.Create (opcode, method); } public Instruction Create (OpCode opcode, FieldReference field) { return Instruction.Create (opcode, field); } public Instruction Create (OpCode opcode, string value) { return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, sbyte value) { return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, byte value) { if (opcode.OperandType == OperandType.ShortInlineVar) return Instruction.Create (opcode, body.Variables [value]); if (opcode.OperandType == OperandType.ShortInlineArg) return Instruction.Create (opcode, Mixin.GetParameter (body,value)); return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, int value) { if (opcode.OperandType == OperandType.InlineVar) return Instruction.Create (opcode, body.Variables [value]); if (opcode.OperandType == OperandType.InlineArg) return Instruction.Create (opcode, Mixin.GetParameter (body,value)); return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, long value) { return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, float value) { return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, double value) { return Instruction.Create (opcode, value); } public Instruction Create (OpCode opcode, Instruction target) { return Instruction.Create (opcode, target); } public Instruction Create (OpCode opcode, Instruction [] targets) { return Instruction.Create (opcode, targets); } public Instruction Create (OpCode opcode, VariableDefinition variable) { return Instruction.Create (opcode, variable); } public Instruction Create (OpCode opcode, ParameterDefinition parameter) { return Instruction.Create (opcode, parameter); } public void Emit (OpCode opcode) { Append (Create (opcode)); } public void Emit (OpCode opcode, TypeReference type) { Append (Create (opcode, type)); } public void Emit (OpCode opcode, MethodReference method) { Append (Create (opcode, method)); } public void Emit (OpCode opcode, CallSite site) { Append (Create (opcode, site)); } public void Emit (OpCode opcode, FieldReference field) { Append (Create (opcode, field)); } public void Emit (OpCode opcode, string value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, byte value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, sbyte value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, int value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, long value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, float value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, double value) { Append (Create (opcode, value)); } public void Emit (OpCode opcode, Instruction target) { Append (Create (opcode, target)); } public void Emit (OpCode opcode, Instruction [] targets) { Append (Create (opcode, targets)); } public void Emit (OpCode opcode, VariableDefinition variable) { Append (Create (opcode, variable)); } public void Emit (OpCode opcode, ParameterDefinition parameter) { Append (Create (opcode, parameter)); } public void InsertBefore (Instruction target, Instruction instruction) { if (target == null) throw new ArgumentNullException ("target"); if (instruction == null) throw new ArgumentNullException ("instruction"); var index = instructions.IndexOf (target); if (index == -1) throw new ArgumentOutOfRangeException ("target"); instructions.Insert (index, instruction); } public void InsertAfter (Instruction target, Instruction instruction) { if (target == null) throw new ArgumentNullException ("target"); if (instruction == null) throw new ArgumentNullException ("instruction"); var index = instructions.IndexOf (target); if (index == -1) throw new ArgumentOutOfRangeException ("target"); instructions.Insert (index + 1, instruction); } public void Append (Instruction instruction) { if (instruction == null) throw new ArgumentNullException ("instruction"); instructions.Add (instruction); } public void Replace (Instruction target, Instruction instruction) { if (target == null) throw new ArgumentNullException ("target"); if (instruction == null) throw new ArgumentNullException ("instruction"); InsertAfter (target, instruction); Remove (target); } public void Remove (Instruction instruction) { if (instruction == null) throw new ArgumentNullException ("instruction"); if (!instructions.Remove (instruction)) throw new ArgumentOutOfRangeException ("instruction"); } } }
using UnityEngine; using System.Collections.Generic; using XboxCtrlrInput; public class PlayerController : MonoBehaviour { public int playerID = 0; public float glideSpeed = 100; public float floatSpeed = 40; public float weight = 0.1f; private float scale; public GameObject bullet; private float neutralScale = 0.5f; // Store the neutral scale to use as a zero-point for float acceleration private float fireRate = 0.5f; private float nextFire = 0.0f; private float lastAimX; private float lastAimY; public AudioClip pigSnort1; public AudioClip pigSnort2; public AudioClip pigSnort3; public AudioClip pigSnort4; public AudioClip pigDeflate1; public AudioClip pigDeflate2; public AudioClip pigDeflate3; public AudioClip pigDeflate4; public AudioClip pigDeflate5; public AudioClip pigDeflate6; public AudioClip pigDeflate7; public AudioSource source; public Transform aimIndicator; public float BOUNCE_THRESHOLD = 0.2f; private List<Vector3> bounceList; private float lastBounceTime; private bool isDead = false; private float deadTime; private Vector3 deadMoveDir; void Awake() { source = GetComponent<AudioSource>(); scale = rigidbody2D.transform.localScale.x; //neutralScale = scale; lastAimX = 0.0f; lastAimY = 1.0f; bounceList = new List<Vector3>(); lastBounceTime = Time.time; } void kill() { GlobalController.Instance.playerStates[playerID] = PlayerState.Eliminated; GlobalController.Instance.killPlayer(playerID); switch(Random.Range(0, 7)) { case 1: source.PlayOneShot(pigDeflate1); break; case 2: source.PlayOneShot(pigDeflate2); break; case 3: source.PlayOneShot(pigDeflate3); break; case 4: source.PlayOneShot(pigDeflate4); break; case 5: source.PlayOneShot(pigDeflate5); break; case 6: source.PlayOneShot(pigDeflate6); break; case 7: source.PlayOneShot(pigDeflate7); break; default: source.PlayOneShot(pigDeflate1); break; } isDead = true; deadTime = 0.0f; deadMoveDir = new Vector3(-rigidbody2D.velocity.x, -rigidbody2D.velocity.y, 0); Destroy(gameObject.transform.GetChild(0).gameObject); //Destroy the pointer Destroy(gameObject.GetComponent<Rigidbody2D>()); Destroy(gameObject.GetComponent<CircleCollider2D>()); } void deadUpdate() { deadTime += Time.fixedDeltaTime; transform.position += 50*deadMoveDir*Time.fixedDeltaTime; deadMoveDir.x += Random.Range(-1.0f, 1.0f); deadMoveDir.y += Random.Range(-1.0f, 1.0f); deadMoveDir.Normalize(); Vector2 screenLoc = Camera.main.WorldToScreenPoint(transform.position); if (screenLoc.x < -50 || screenLoc.y < -50 || screenLoc.x > Camera.main.pixelWidth+50 || screenLoc.y > Camera.main.pixelHeight+50) { Destroy(gameObject); } } void OnCollisionEnter2D(Collision2D coll) { if (coll.gameObject.layer == 8) // hazard like spike { kill(); } if (coll.gameObject.layer == 9) // bullet { weight+=1.0f; scale += -0.05f; coll.transform.parent = transform; coll.rigidbody.isKinematic=true; coll.collider.enabled=false; rigidbody2D.rigidbody2D.mass+=1; //add weight here //kill(); } PlayerController otherPlayer = coll.gameObject.GetComponent<PlayerController>(); if(otherPlayer) // collision with player { float deltaBounce = Time.time - lastBounceTime; float otherDeltaBounce = Time.time - otherPlayer.lastBounceTime; if (deltaBounce > BOUNCE_THRESHOLD && otherDeltaBounce > BOUNCE_THRESHOLD) { switch(Random.Range(0, 4)) { case 1: source.PlayOneShot(pigSnort1); break; case 2: source.PlayOneShot(pigSnort2); break; case 3: source.PlayOneShot(pigSnort3); break; case 4: source.PlayOneShot(pigSnort4); break; default: source.PlayOneShot(pigSnort1); break; } lastBounceTime = Time.time; otherPlayer.lastBounceTime = Time.time; float mass1 = transform.localScale.x; float mass2 = coll.gameObject.transform.localScale.x; float velo1Scale = (mass1-mass2)/(mass1+mass2); float velo2Scale = (2*mass1)/(mass1+mass2); Vector2 newVelo1 = velo1Scale * coll.gameObject.rigidbody2D.velocity; Vector2 newVelo2 = velo2Scale * rigidbody2D.velocity; bounceList.Add(new Vector3(newVelo1.x, newVelo1.y, Time.time +1.0f)); otherPlayer.bounceList.Add(new Vector3(newVelo2.x, newVelo2.y, Time.time +1.0f)); } } } void FixedUpdate() { if (isDead) { deadUpdate(); return; } // 3 - Retrieve axis information float moveX = 0; float moveY = 0; float aimX = 0; float aimY = 0; bool shoot = false; switch (playerID) { case(0): if (Input.GetKey(KeyCode.A)) moveX -= 1.0f; if (Input.GetKey(KeyCode.D)) moveX += 1.0f; if (Input.GetKey(KeyCode.W)) moveY += 1.0f; if (Input.GetKey(KeyCode.S)) moveY -= 1.0f; Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 direction = mousePosition-transform.position; direction.z=0; direction.Normalize(); aimX = direction.x; aimY = direction.y; shoot = Input.GetMouseButtonDown(0); break; case(1): case(3): if (XCI.GetDPad(XboxDPad.Left, (playerID+1)/2)) moveX -= 1.0f; if (XCI.GetDPad(XboxDPad.Right, (playerID+1)/2)) moveX += 1.0f; if (XCI.GetDPad(XboxDPad.Up, (playerID+1)/2)) moveY += 1.0f; if (XCI.GetDPad(XboxDPad.Down, (playerID+1)/2)) moveY -= 1.0f; aimX = XCI.GetAxis(XboxAxis.LeftStickX, (playerID+1)/2); aimY = XCI.GetAxis(XboxAxis.LeftStickY, (playerID+1)/2); shoot = ((XCI.GetAxis(XboxAxis.LeftTrigger, (playerID+1)/2) > 0.5f) || (XCI.GetButtonDown(XboxButton.LeftBumper, (playerID+1)/2))); break; case (2): case (4): if (XCI.GetButton(XboxButton.X, playerID/2)) moveX -= 1.0f; if (XCI.GetButton(XboxButton.B, playerID/2)) moveX += 1.0f; if (XCI.GetButton(XboxButton.Y, playerID/2)) moveY += 1.0f; if (XCI.GetButton(XboxButton.A, playerID/2)) moveY -= 1.0f; aimX = XCI.GetAxis(XboxAxis.RightStickX, playerID/2); aimY = XCI.GetAxis(XboxAxis.RightStickY, playerID/2); shoot = ((XCI.GetAxis(XboxAxis.RightTrigger, playerID/2) > 0.5f) || (XCI.GetButtonDown(XboxButton.RightBumper, playerID/2))); break; } if (aimX*aimX + aimY*aimY < 0.5f) { aimX = lastAimX; aimY = lastAimY; } else { lastAimX = aimX; lastAimY = aimY; } // Rotate aiming indicator float theta = Mathf.Atan2(aimY, aimX) * Mathf.Rad2Deg; aimIndicator.rotation = Quaternion.Euler(0, 0, theta-90); // Shoot if (shoot && Time.time >= nextFire) { nextFire = Time.time + fireRate; fireProjectile(aimX, aimY); } // 5 - Move the game object // We want scale of 1 to result in 0 upwards acceleration // Clamp scale to a positive value so we don't sink directly due to scale float floatAcceleration = floatSpeed*scale; Vector2 newVelocity = rigidbody2D.velocity; newVelocity.x = glideSpeed*moveX; newVelocity.y = floatAcceleration*(scale-neutralScale) - 4f -weight; ///Adding bounce factor from list for (int i = 0; i < bounceList.Count; i++) { if (bounceList[i].z <= Time.time) { bounceList.RemoveAt(i); i+=-1; } else { newVelocity.x += bounceList[i].x; newVelocity.y += bounceList[i].y; } } rigidbody2D.velocity = newVelocity; scale += 0.5f*sign(moveY)*Time.fixedDeltaTime; scale = Mathf.Clamp(scale, 0.25f, 1.25f); rigidbody2D.transform.localScale = new Vector3(scale, scale, scale); } float sign(float f) { if (f == 0) return 0.0f; else if (f > 0) return 1.0f; else //if (f < 0) return -1.0f; } void fireProjectile(float x, float y) { Vector3 spawnLoc = transform.position; spawnLoc.x += x*scale*1.9f; spawnLoc.y += y*scale*1.9f; GameObject bulletInstance = (GameObject)Instantiate(bullet, spawnLoc, Quaternion.identity); // Should the bullet velocity be affected by the player's velocity? Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f ); bulletInstance.renderer.material.color = newColor; bulletInstance.rigidbody2D.AddForce(rigidbody2D.position+(new Vector2(x, y)*500)); } }
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 O365SharePointAppWeb { 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.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Cms { /** * General class for generating a CMS enveloped-data message stream. * <p> * A simple example of usage. * <pre> * CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); * * edGen.AddKeyTransRecipient(cert); * * MemoryStream bOut = new MemoryStream(); * * Stream out = edGen.Open( * bOut, CMSEnvelopedDataGenerator.AES128_CBC);* * out.Write(data); * * out.Close(); * </pre> * </p> */ public class CmsEnvelopedDataStreamGenerator : CmsEnvelopedGenerator { private object _originatorInfo = null; private object _unprotectedAttributes = null; private int _bufferSize; private bool _berEncodeRecipientSet; public CmsEnvelopedDataStreamGenerator() { } /// <summary>Constructor allowing specific source of randomness</summary> /// <param name="rand">Instance of <c>SecureRandom</c> to use.</param> public CmsEnvelopedDataStreamGenerator( SecureRandom rand) : base(rand) { } /// <summary>Set the underlying string size for encapsulated data.</summary> /// <param name="bufferSize">Length of octet strings to buffer the data.</param> public void SetBufferSize( int bufferSize) { _bufferSize = bufferSize; } /// <summary>Use a BER Set to store the recipient information.</summary> public void SetBerEncodeRecipients( bool berEncodeRecipientSet) { _berEncodeRecipientSet = berEncodeRecipientSet; } private DerInteger Version { get { int version = (_originatorInfo != null || _unprotectedAttributes != null) ? 2 : 0; return new DerInteger(version); } } /// <summary> /// Generate an enveloped object that contains an CMS Enveloped Data /// object using the passed in key generator. /// </summary> private Stream Open( Stream outStream, string encryptionOid, CipherKeyGenerator keyGen) { byte[] encKeyBytes = keyGen.GenerateKey(); KeyParameter encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes); ICipherParameters cipherParameters; AlgorithmIdentifier encAlgID = GetAlgorithmIdentifier( encryptionOid, encKey, asn1Params, out cipherParameters); Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } return Open(outStream, encAlgID, cipherParameters, recipientInfos); } private Stream Open( Stream outStream, AlgorithmIdentifier encAlgID, ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos) { try { // // ContentInfo // BerSequenceGenerator cGen = new BerSequenceGenerator(outStream); cGen.AddObject(CmsObjectIdentifiers.EnvelopedData); // // Encrypted Data // BerSequenceGenerator envGen = new BerSequenceGenerator( cGen.GetRawOutputStream(), 0, true); envGen.AddObject(this.Version); Stream envRaw = envGen.GetRawOutputStream(); Asn1Generator recipGen = _berEncodeRecipientSet ? (Asn1Generator) new BerSetGenerator(envRaw) : new DerSetGenerator(envRaw); foreach (Asn1Encodable ae in recipientInfos) { recipGen.AddObject(ae); } recipGen.Close(); BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw); eiGen.AddObject(CmsObjectIdentifiers.Data); eiGen.AddObject(encAlgID); Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream( eiGen.GetRawOutputStream(), 0, false, _bufferSize); IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.ObjectID); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); CipherStream cOut = new CipherStream(octetOutputStream, null, cipher); return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } } /** * generate an enveloped object that contains an CMS Enveloped Data object * @throws IOException */ public Stream Open( Stream outStream, string encryptionOid) { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); return Open(outStream, encryptionOid, keyGen); } /** * generate an enveloped object that contains an CMS Enveloped Data object * @throws IOException */ public Stream Open( Stream outStream, string encryptionOid, int keySize) { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); keyGen.Init(new KeyGenerationParameters(rand, keySize)); return Open(outStream, encryptionOid, keyGen); } private class CmsEnvelopedDataOutputStream : BaseOutputStream { private readonly CmsEnvelopedGenerator _outer; private readonly CipherStream _out; private readonly BerSequenceGenerator _cGen; private readonly BerSequenceGenerator _envGen; private readonly BerSequenceGenerator _eiGen; public CmsEnvelopedDataOutputStream( CmsEnvelopedGenerator outer, CipherStream outStream, BerSequenceGenerator cGen, BerSequenceGenerator envGen, BerSequenceGenerator eiGen) { _outer = outer; _out = outStream; _cGen = cGen; _envGen = envGen; _eiGen = eiGen; } public override void WriteByte( byte b) { _out.WriteByte(b); } public override void Write( byte[] bytes, int off, int len) { _out.Write(bytes, off, len); } public override void Close() { _out.Close(); // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); if (_outer.unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector()); _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs)); } _envGen.Close(); _cGen.Close(); base.Close(); } } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using Mono.Security.Protocol.Tls.Handshake; using Mono.Security.Interface; namespace Mono.Security.Protocol.Tls { #region Delegates public delegate bool CertificateValidationCallback( X509Certificate certificate, int[] certificateErrors); #if INSIDE_SYSTEM internal #else public #endif delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection); public delegate X509Certificate CertificateSelectionCallback( X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates); public delegate AsymmetricAlgorithm PrivateKeySelectionCallback( X509Certificate certificate, string targetHost); #endregion #if INSIDE_SYSTEM internal #else public #endif class SslClientStream : SslStreamBase { #region Internal Events internal event CertificateValidationCallback ServerCertValidation; internal event CertificateSelectionCallback ClientCertSelection; internal event PrivateKeySelectionCallback PrivateKeySelection; #endregion #region Properties // required by HttpsClientStream for proxy support internal Stream InputBuffer { get { return base.inputBuffer; } } public X509CertificateCollection ClientCertificates { get { return this.context.ClientSettings.Certificates; } } public X509Certificate SelectedClientCertificate { get { return this.context.ClientSettings.ClientCertificate; } } #endregion #region Callback Properties public CertificateValidationCallback ServerCertValidationDelegate { get { return this.ServerCertValidation; } set { this.ServerCertValidation = value; } } public CertificateSelectionCallback ClientCertSelectionDelegate { get { return this.ClientCertSelection; } set { this.ClientCertSelection = value; } } public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate { get { return this.PrivateKeySelection; } set { this.PrivateKeySelection = value; } } #endregion public event CertificateValidationCallback2 ServerCertValidation2; #region Constructors public SslClientStream( Stream stream, string targetHost, bool ownsStream) : this( stream, targetHost, ownsStream, SecurityProtocolType.Default, null) { } public SslClientStream( Stream stream, string targetHost, X509Certificate clientCertificate) : this( stream, targetHost, false, SecurityProtocolType.Default, new X509CertificateCollection(new X509Certificate[]{clientCertificate})) { } public SslClientStream( Stream stream, string targetHost, X509CertificateCollection clientCertificates) : this( stream, targetHost, false, SecurityProtocolType.Default, clientCertificates) { } public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType) : this( stream, targetHost, ownsStream, securityProtocolType, new X509CertificateCollection()) { } public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType, X509CertificateCollection clientCertificates): base(stream, ownsStream) { if (targetHost == null || targetHost.Length == 0) { throw new ArgumentNullException("targetHost is null or an empty string."); } this.context = new ClientContext( this, securityProtocolType, targetHost, clientCertificates); this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context); } #endregion #region Finalizer ~SslClientStream() { base.Dispose(false); } #endregion #region IDisposable Methods protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { this.ServerCertValidation = null; this.ClientCertSelection = null; this.PrivateKeySelection = null; this.ServerCertValidation2 = null; } } #endregion #region Handshake Methods /* Client Server ClientHello --------> ServerHello Certificate* ServerKeyExchange* CertificateRequest* <-------- ServerHelloDone Certificate* ClientKeyExchange CertificateVerify* [ChangeCipherSpec] Finished --------> [ChangeCipherSpec] <-------- Finished Application Data <-------> Application Data Fig. 1 - Message flow for a full handshake */ private void SafeEndReceiveRecord (IAsyncResult ar, bool ignoreEmpty = false) { byte[] record = this.protocol.EndReceiveRecord (ar); if (!ignoreEmpty && ((record == null) || (record.Length == 0))) { throw new TlsException ( AlertDescription.HandshakeFailiure, "The server stopped the handshake."); } } private enum NegotiateState { SentClientHello, ReceiveClientHelloResponse, SentCipherSpec, ReceiveCipherSpecResponse, SentKeyExchange, ReceiveFinishResponse, SentFinished, }; private class NegotiateAsyncResult : IAsyncResult { private object locker = new object (); private AsyncCallback _userCallback; private object _userState; private Exception _asyncException; private ManualResetEvent handle; private NegotiateState _state; private bool completed; public NegotiateAsyncResult(AsyncCallback userCallback, object userState, NegotiateState state) { _userCallback = userCallback; _userState = userState; _state = state; } public NegotiateState State { get { return _state; } set { _state = value; } } public object AsyncState { get { return _userState; } } public Exception AsyncException { get { return _asyncException; } } public bool CompletedWithError { get { if (!IsCompleted) return false; // Perhaps throw InvalidOperationExcetion? return null != _asyncException; } } public WaitHandle AsyncWaitHandle { get { lock (locker) { if (handle == null) handle = new ManualResetEvent (completed); } return handle; } } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get { lock (locker) { return completed; } } } public void SetComplete(Exception ex) { lock (locker) { if (completed) return; completed = true; if (handle != null) handle.Set (); if (_userCallback != null) _userCallback.BeginInvoke (this, null, null); _asyncException = ex; } } public void SetComplete() { SetComplete(null); } } internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state) { if (this.context.HandshakeState != HandshakeState.None) { this.context.Clear (); } // Obtain supported cipher suites this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, context.SecurityProtocol); // Set handshake state this.context.HandshakeState = HandshakeState.Started; NegotiateAsyncResult result = new NegotiateAsyncResult (callback, state, NegotiateState.SentClientHello); // Begin sending the client hello this.protocol.BeginSendRecord (HandshakeType.ClientHello, NegotiateAsyncWorker, result); return result; } internal override void EndNegotiateHandshake (IAsyncResult result) { NegotiateAsyncResult negotiate = result as NegotiateAsyncResult; if (negotiate == null) throw new ArgumentNullException (); if (!negotiate.IsCompleted) negotiate.AsyncWaitHandle.WaitOne(); if (negotiate.CompletedWithError) throw negotiate.AsyncException; } private void NegotiateAsyncWorker (IAsyncResult result) { NegotiateAsyncResult negotiate = result.AsyncState as NegotiateAsyncResult; try { switch (negotiate.State) { case NegotiateState.SentClientHello: this.protocol.EndSendRecord (result); // we are now ready to ready the receive the hello response. negotiate.State = NegotiateState.ReceiveClientHelloResponse; // Start reading the client hello response this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); break; case NegotiateState.ReceiveClientHelloResponse: this.SafeEndReceiveRecord (result, true); if (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone && (!this.context.AbbreviatedHandshake || this.context.LastHandshakeMsg != HandshakeType.ServerHello)) { // Read next record (skip empty, e.g. warnings alerts) this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); break; } // special case for abbreviated handshake where no ServerHelloDone is sent from the server if (this.context.AbbreviatedHandshake) { ClientSessionCache.SetContextFromCache (this.context); this.context.Negotiating.Cipher.ComputeKeys (); this.context.Negotiating.Cipher.InitializeCipher (); negotiate.State = NegotiateState.SentCipherSpec; // Send Change Cipher Spec message with the current cipher // or as plain text if this is the initial negotiation this.protocol.BeginSendChangeCipherSpec(NegotiateAsyncWorker, negotiate); } else { // Send client certificate if requested // even if the server ask for it it _may_ still be optional bool clientCertificate = this.context.ServerSettings.CertificateRequest; using (var memstream = new MemoryStream()) { // NOTE: sadly SSL3 and TLS1 differs in how they handle this and // the current design doesn't allow a very cute way to handle // SSL3 alert warning for NoCertificate (41). if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3) { clientCertificate = ((this.context.ClientSettings.Certificates != null) && (this.context.ClientSettings.Certificates.Count > 0)); // this works well with OpenSSL (but only for SSL3) } byte[] record = null; if (clientCertificate) { record = this.protocol.EncodeHandshakeRecord(HandshakeType.Certificate); memstream.Write(record, 0, record.Length); } // Send Client Key Exchange record = this.protocol.EncodeHandshakeRecord(HandshakeType.ClientKeyExchange); memstream.Write(record, 0, record.Length); // Now initialize session cipher with the generated keys this.context.Negotiating.Cipher.InitializeCipher(); // Send certificate verify if requested (optional) if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null)) { record = this.protocol.EncodeHandshakeRecord(HandshakeType.CertificateVerify); memstream.Write(record, 0, record.Length); } // send the chnage cipher spec. this.protocol.SendChangeCipherSpec(memstream); // Send Finished message record = this.protocol.EncodeHandshakeRecord(HandshakeType.Finished); memstream.Write(record, 0, record.Length); negotiate.State = NegotiateState.SentKeyExchange; // send all the records. this.innerStream.BeginWrite (memstream.GetBuffer (), 0, (int)memstream.Length, NegotiateAsyncWorker, negotiate); } } break; case NegotiateState.SentKeyExchange: this.innerStream.EndWrite (result); negotiate.State = NegotiateState.ReceiveFinishResponse; this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); break; case NegotiateState.ReceiveFinishResponse: this.SafeEndReceiveRecord (result); // Read record until server finished is received if (this.context.HandshakeState != HandshakeState.Finished) { // If all goes well this will process messages: // Change Cipher Spec // Server finished this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); } else { // Reset Handshake messages information this.context.HandshakeMessages.Reset (); // Clear Key Info this.context.ClearKeyInfo(); negotiate.SetComplete (); } break; case NegotiateState.SentCipherSpec: this.protocol.EndSendChangeCipherSpec (result); negotiate.State = NegotiateState.ReceiveCipherSpecResponse; // Start reading the cipher spec response this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); break; case NegotiateState.ReceiveCipherSpecResponse: this.SafeEndReceiveRecord (result, true); if (this.context.HandshakeState != HandshakeState.Finished) { this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate); } else { negotiate.State = NegotiateState.SentFinished; this.protocol.BeginSendRecord(HandshakeType.Finished, NegotiateAsyncWorker, negotiate); } break; case NegotiateState.SentFinished: this.protocol.EndSendRecord (result); // Reset Handshake messages information this.context.HandshakeMessages.Reset (); // Clear Key Info this.context.ClearKeyInfo(); negotiate.SetComplete (); break; } } catch (TlsException ex) { try { Exception e = ex; this.protocol.SendAlert(ref e); } catch { } negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex)); } catch (Exception ex) { try { this.protocol.SendAlert(AlertDescription.InternalError); } catch { } negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex)); } } #endregion #region Event Methods internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates) { if (this.ClientCertSelection != null) { return this.ClientCertSelection( clientCertificates, serverCertificate, targetHost, serverRequestedCertificates); } return null; } internal override bool HaveRemoteValidation2Callback { get { return ServerCertValidation2 != null; } } internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection) { CertificateValidationCallback2 cb = ServerCertValidation2; if (cb != null) return cb (collection); return null; } internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors) { if (this.ServerCertValidation != null) { return this.ServerCertValidation(certificate, errors); } return (errors != null && errors.Length == 0); } internal virtual bool RaiseServerCertificateValidation( X509Certificate certificate, int[] certificateErrors) { return base.RaiseRemoteCertificateValidation(certificate, certificateErrors); } internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection) { return base.RaiseRemoteCertificateValidation2 (collection); } internal X509Certificate RaiseClientCertificateSelection( X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates) { return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates); } internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost) { if (this.PrivateKeySelection != null) { return this.PrivateKeySelection(certificate, targetHost); } return null; } internal AsymmetricAlgorithm RaisePrivateKeySelection( X509Certificate certificate, string targetHost) { return base.RaiseLocalPrivateKeySelection(certificate, targetHost); } #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A03Level11ReChild (editable child object).<br/> /// This is a generated base class of <see cref="A03Level11ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A02Level1"/> collection. /// </remarks> [Serializable] public partial class A03Level11ReChild : BusinessBase<A03Level11ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Child_Name, "Level_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1 Child Name. /// </summary> /// <value>The Level_1_1 Child Name.</value> public string Level_1_1_Child_Name { get { return GetProperty(Level_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A03Level11ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="A03Level11ReChild"/> object.</returns> internal static A03Level11ReChild NewA03Level11ReChild() { return DataPortal.CreateChild<A03Level11ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="A03Level11ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A03Level11ReChild"/> object.</returns> internal static A03Level11ReChild GetA03Level11ReChild(SafeDataReader dr) { A03Level11ReChild obj = new A03Level11ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A03Level11ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private A03Level11ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A03Level11ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A03Level11ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_Child_NameProperty, dr.GetString("Level_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A03Level11ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="A03Level11ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_Child_Name", ReadProperty(Level_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="A03Level11ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A02Level1 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteA03Level11ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Dashboard Feed ///<para>SObject Name: DashboardFeed</para> ///<para>Custom Object: False</para> ///</summary> public class SfDashboardFeed : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "DashboardFeed"; } } ///<summary> /// Feed Item ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(false)] public string ParentId { get; set; } ///<summary> /// ReferenceTo: Dashboard /// <para>RelationshipName: Parent</para> ///</summary> [JsonProperty(PropertyName = "parent")] [Updateable(false), Createable(false)] public SfDashboard Parent { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] [Updateable(false), Createable(false)] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] [Updateable(false), Createable(false)] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(false)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] [Updateable(false), Createable(false)] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(false)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Its.Log.Instrumentation.Extensions; namespace Its.Log.Instrumentation { /// <summary> /// Provides methods for formatting objects into log strings. /// </summary> public static class Formatter { private static Func<Type, bool> autoGenerateForType = t => false; private static int defaultListExpansionLimit; private static int recursionLimit; internal static readonly RecursionCounter RecursionCounter = new RecursionCounter(); private static readonly ConcurrentDictionary<Type, Action<object, TextWriter>> genericFormatters = new ConcurrentDictionary<Type, Action<object, TextWriter>>(); /// <summary> /// Initializes the <see cref="Formatter"/> class. /// </summary> static Formatter() { ResetToDefault(); } /// <summary> /// A factory function called to get a TextWriter for writing out log-formatted objects. /// </summary> public static Func<TextWriter> CreateWriter = () => new StringWriter(CultureInfo.InvariantCulture); internal static ILogTextFormatter TextFormatter = new SingleLineTextFormatter(); internal static Action<object, TextWriter> Default { get; set; } /// <summary> /// Gets or sets the limit to the number of items that will be written out in detail from an IEnumerable sequence. /// </summary> /// <value> /// The list expansion limit. /// </value> public static int ListExpansionLimit { get { return defaultListExpansionLimit; } set { if (value < 0) { throw new ArgumentException("ListExpansionLimit must be at least 0."); } defaultListExpansionLimit = value; } } /// <summary> /// Gets or sets the string that will be written out for null items. /// </summary> /// <value> /// The null string. /// </value> public static string NullString; /// <summary> /// Gets or sets the limit to how many levels the formatter will recurse into an object graph. /// </summary> /// <value> /// The recursion limit. /// </value> public static int RecursionLimit { get { return recursionLimit; } set { if (value < 0) { throw new ArgumentException("RecursionLimit must be at least 0."); } recursionLimit = value; } } internal static event EventHandler Clearing; /// <summary> /// Resets all formatters and formatter settings to their default values. /// </summary> public static void ResetToDefault() { EventHandler handler = Clearing; if (handler != null) { handler(null, EventArgs.Empty); } AutoGenerateForType = t => false; ListExpansionLimit = 10; RecursionLimit = 6; NullString = "[null]"; RegisterDefaults(); Default = null; } /// <summary> /// Gets or sets a delegate that is checked when a type is being formatted that not previously been formatted and has no custom formatting rules set. If this delegate returns true, then <see cref="Formatter{T}.RegisterForAllMembers" /> is called for that type. /// </summary> /// <value> /// The type being formatted. /// </value> /// <exception cref="System.ArgumentNullException">value</exception> public static Func<Type, bool> AutoGenerateForType { get { return autoGenerateForType; } set { if (value == null) { throw new ArgumentNullException("value"); } autoGenerateForType = value; } } /// <summary> /// Formats the specified object using a registered formatter function if available. /// </summary> /// <param name = "obj">The object to be formatted.</param> /// <returns>A string representation of the object.</returns> public static string Format(object obj) { var writer = CreateWriter(); FormatTo(obj, writer); return writer.ToString(); } /// <summary> /// Writes a formatted representation of the object to the specified writer. /// </summary> /// <typeparam name="T">The type of the object being written.</typeparam> /// <param name="obj">The object to write.</param> /// <param name="writer">The writer.</param> public static void FormatTo<T>(this T obj, TextWriter writer) { var custom = Default; if (custom != null) { custom(obj, writer); return; } if (obj != null) { var actualType = obj.GetType(); if (typeof (T) != actualType) { // in some cases the generic parameter is Object but the object is of a more specific type, in which case get or add a cached accessor to the more specific Formatter<T>.Format method Action<object, TextWriter> genericFormatter = genericFormatters.GetOrAdd(actualType, GetGenericFormatterMethod); genericFormatter(obj, writer); return; } } Formatter<T>.Format(obj, writer); } internal static Action<object, TextWriter> GetGenericFormatterMethod(this Type type) { var methodInfo = typeof (Formatter<>) .MakeGenericType(type) .GetMethod("Format", new[] { type, typeof (TextWriter) }); var targetParam = Expression.Parameter(typeof (object), "target"); var writerParam = Expression.Parameter(typeof (TextWriter), "target"); var methodCallExpr = Expression.Call(null, methodInfo, Expression.Convert(targetParam, type), writerParam); return Expression.Lambda<Action<object, TextWriter>>(methodCallExpr, targetParam, writerParam).Compile(); } // TODO: (Formatter) make Join methods public and expose an override for iteration limit internal static void Join(IEnumerable list, TextWriter writer, int? listExpansionLimit = null) { Join(list.Cast<object>(), writer, listExpansionLimit); } internal static void Join<T>(IEnumerable<T> list, TextWriter writer, int? listExpansionLimit = null) { if (list == null) { writer.Write(NullString); return; } var i = 0; TextFormatter.WriteStartSequence(writer); listExpansionLimit = listExpansionLimit ?? Formatter<T>.ListExpansionLimit; using (var enumerator = list.GetEnumerator()) { while (enumerator.MoveNext()) { if (i < listExpansionLimit) { // write out another item in the list if (i > 0) { TextFormatter.WriteSequenceDelimiter(writer); } i++; TextFormatter.WriteStartSequenceItem(writer); enumerator.Current.FormatTo(writer); } else { // write out just a count of the remaining items in the list var difference = list.Count() - i; if (difference > 0) { writer.Write(" ... ("); writer.Write(difference); writer.Write(" more)"); } break; } } } TextFormatter.WriteEndSequence(writer); } /// <summary> /// Registers a formatter to be used when formatting instances of a specified type. /// </summary> public static void Register(Type type, Action<object, TextWriter> formatter) { MethodInfo genericRegisterMethod = typeof (Formatter<>) .MakeGenericType(type) .GetMethod("Register", new[] { typeof (Action<,>).MakeGenericType(type, typeof (TextWriter)) }); genericRegisterMethod.Invoke(null, new object[] { formatter }); } /// <summary> /// Registers a formatter to be used when formatting instances of a specified type. /// </summary> public static void RegisterForAllMembers(Type type, bool includeInternals = false) { MethodInfo genericRegisterMethod = typeof (Formatter<>) .MakeGenericType(type) .GetMethod("RegisterForAllMembers"); genericRegisterMethod.Invoke(null, new object[] { includeInternals }); } private static void RegisterDefaults() { RegisterDefaultLogEntryFormatters(); // common primitive types Formatter<bool>.Default = (value, writer) => writer.Write(value); Formatter<byte>.Default = (value, writer) => writer.Write(value); Formatter<Int16>.Default = (value, writer) => writer.Write(value); Formatter<Int32>.Default = (value, writer) => writer.Write(value); Formatter<Int64>.Default = (value, writer) => writer.Write(value); Formatter<Guid>.Default = (value, writer) => writer.Write(value); Formatter<Decimal>.Default = (value, writer) => writer.Write(value); Formatter<Single>.Default = (value, writer) => writer.Write(value); Formatter<Double>.Default = (value, writer) => writer.Write(value); Formatter<DateTime>.Default = (value, writer) => writer.Write(value.ToString("u")); Formatter<DateTimeOffset>.Default = (value, writer) => writer.Write(value.ToString("u")); // common complex types Formatter<KeyValuePair<string, object>>.Default = (pair, writer) => { writer.Write(pair.Key); TextFormatter.WriteNameValueDelimiter(writer); pair.Value.FormatTo(writer); }; Formatter<DictionaryEntry>.Default = (pair, writer) => { writer.Write(pair.Key); TextFormatter.WriteNameValueDelimiter(writer); pair.Value.FormatTo(writer); }; Formatter<ExpandoObject>.Default = (expando, writer) => { TextFormatter.WriteStartObject(writer); KeyValuePair<string, object>[] pairs = expando.ToArray(); int length = pairs.Length; for (int i = 0; i < length; i++) { KeyValuePair<string, object> pair = pairs[i]; writer.Write(pair.Key); TextFormatter.WriteNameValueDelimiter(writer); pair.Value.FormatTo(writer); if (i < length - 1) { TextFormatter.WritePropertyDelimiter(writer); } } TextFormatter.WriteEndObject(writer); }; Formatter<Type>.Default = (type, writer) => { var typeName = type.Name; if (type.IsGenericType && !type.IsAnonymous()) { writer.Write(typeName.Remove(typeName.IndexOf('`'))); writer.Write("<"); var genericArguments = type.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { Formatter<Type>.Default(genericArguments[i], writer); if (i < genericArguments.Length - 1) { writer.Write(","); } } writer.Write(">"); } else { writer.Write(typeName); } }; // an additional formatter is needed since typeof(Type) == System.RuntimeType, which is not public Register(typeof (Type).GetType(), (obj, writer) => Formatter<Type>.Default((Type) obj, writer)); // supply a formatter for String so that it will not be iterated Formatter<string>.Default = (s, writer) => writer.Write(s); // extensions Formatter<Counter>.Default = Formatter<Counter>.GenerateForAllMembers(); Formatter<Tracing>.Default = Formatter<Tracing>.GenerateForAllMembers(); // Newtonsoft.Json types -- these implement IEnumerable and their default output is not useful, so use their default ToString TryRegisterDefault("Newtonsoft.Json.Linq.JArray, Newtonsoft.Json", (obj, writer) => writer.Write(obj)); TryRegisterDefault("Newtonsoft.Json.Linq.JObject, Newtonsoft.Json", (obj, writer) => writer.Write(obj)); } private static void TryRegisterDefault(string typeName, Action<object, TextWriter> write) { try { var type = Type.GetType(typeName); if (type != null) { Register(type, write); } } catch (Exception exception) { if (exception.ShouldThrow()) { throw; } Log.Write(() => exception, string.Format("An exception occurred while trying to register a formatter for type '{0}'.", typeName)); } } internal static void RegisterDefaultLogEntryFormatters() { Formatter<LogEntry>.RegisterForMembers( e => e.CallingType, e => e.CallingMethod, e => e.ElapsedMilliseconds, e => e.Category, e => e.ExceptionId, e => e.Message, e => e.Subject, e => e.TimeStamp, e => e.Params ); } } }
using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; namespace Destructible2D { [CanEditMultipleObjects] [CustomEditor(typeof(D2dPolygonCollider))] public class D2dPolygonCollider_Editor : D2dCollider_Editor<D2dPolygonCollider> { protected override void OnInspector() { var destroyChild = false; DrawDefault("CellSize", ref destroyChild); DrawDefault("Detail", ref destroyChild); if (destroyChild == true) DirtyEach(t => t.DestroyChild()); base.OnInspector(); } } } #endif namespace Destructible2D { [AddComponentMenu(D2dHelper.ComponentMenuPrefix + "Polygon Collider")] public class D2dPolygonCollider : D2dCollider { [Tooltip("The size of each collider cell")] [D2dPopup(8, 16, 32, 64, 128, 256)] public int CellSize = 64; [Tooltip("How many vertices should remain in the collider shapes")] [Range(0.5f, 1.0f)] public float Detail = 0.9f; [SerializeField] private int width; [SerializeField] private int height; [SerializeField] private List<D2dPolygonColliderCell> cells = new List<D2dPolygonColliderCell>(); [System.NonSerialized] private List<PolygonCollider2D> unusedColliders = new List<PolygonCollider2D>(); public override void UpdateColliderSettings() { for (var i = cells.Count - 1; i >= 0; i--) { cells[i].UpdateColliderSettings(IsTrigger, Material); } } protected override void OnAlphaDataReplaced() { base.OnAlphaDataReplaced(); Rebuild(); } protected override void OnAlphaDataModified(D2dRect rect) { base.OnAlphaDataModified(rect); if (CellSize > 0) { var cellXMin = rect.MinX / CellSize; var cellYMin = rect.MinY / CellSize; var cellXMax = (rect.MaxX + 1) / CellSize; var cellYMax = (rect.MaxY + 1) / CellSize; // Mark for (var cellY = cellYMin; cellY <= cellYMax; cellY++) { var offset = cellY * width; for (var cellX = cellXMin; cellX <= cellXMax; cellX++) { var index = cellX + offset; if (index >= 0 && index < cells.Count) { Mark(cells[index]); } else { Regenerate(); } } } // Generate for (var cellY = cellYMin; cellY <= cellYMax; cellY++) { var offset = cellY * width; for (var cellX = cellXMin; cellX <= cellXMax; cellX++) { var index = cellX + offset; if (index >= 0 && index < cells.Count) { RebuildCell(cells[index], cellX, cellY); } } } Sweep(); } else { Rebuild(); } } protected override void OnAlphaDataSubset(D2dRect rect) { base.OnAlphaDataSubset(rect); Rebuild(); } protected override void OnStartSplit() { base.OnStartSplit(); Mark(); Sweep(); } private void Mark() { for (var i = cells.Count - 1; i >= 0; i--) { D2dPool<D2dPolygonColliderCell>.Despawn(cells[i], c => c.Clear(unusedColliders)); } cells.Clear(); } private void Mark(D2dPolygonColliderCell cell) { cell.Clear(unusedColliders); } private void Sweep() { for (var i = unusedColliders.Count - 1; i >= 0; i--) { D2dHelper.Destroy(unusedColliders[i]); } unusedColliders.Clear(); } private void Rebuild() { Mark(); { if (CellSize > 0) { width = (destructible.AlphaWidth + CellSize - 1) / CellSize; height = (destructible.AlphaHeight + CellSize - 1) / CellSize; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var cell = D2dPool<D2dPolygonColliderCell>.Spawn() ?? new D2dPolygonColliderCell(); RebuildCell(cell, x, y); cells.Add(cell); } } UpdateColliderSettings(); } } Sweep(); } private void RebuildCell(D2dPolygonColliderCell cell, int x, int y) { var xMin = CellSize * x; var yMin = CellSize * y; var xMax = Mathf.Min(CellSize + xMin, destructible.AlphaWidth ); var yMax = Mathf.Min(CellSize + yMin, destructible.AlphaHeight); D2dColliderBuilder.CalculatePoly(destructible.AlphaData, destructible.AlphaWidth, xMin, xMax, yMin, yMax); D2dColliderBuilder.BuildPoly(cell, unusedColliders, child, Detail); cell.UpdateColliderSettings(IsTrigger, Material); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace dex.net { public class PlainDexWriter : IDexWriter { private Dex _dex; public Dex dex { get { return _dex; } set { _dex = value; _helper._dex = _dex; } } private TypeHelper _helper; public PlainDexWriter() { _helper = new TypeHelper((index, currentClass, isClass) => {return "v" + index;} , WriteOutAnnotation); } #region DexWriter public string GetName() { return "Plain Dex"; } public string GetExtension () { return ".pdex"; } public void WriteOutMethod (Class dexClass, Method method, TextWriter output, Indentation indent, bool renderOpcodes=false) { var stringIndent = indent.ToString (); var proto = _dex.GetPrototype (method.PrototypeIndex); output.WriteLine (string.Format("{0}.METHOD {1} : {2}", stringIndent, method.Name, _dex.GetTypeName(proto.ReturnTypeIndex))); indent++; var paramCount = 0; foreach (var param in proto.Parameters) { output.WriteLine(string.Format("{0}.PARAM {1}", indent.ToString(), _dex.GetTypeName(param))); if (method.ParameterAnnotations.Count > paramCount) { indent++; WriteOutAnnotation (output, method.ParameterAnnotations[paramCount].Values, dexClass, indent); indent--; } paramCount++; } indent--; output.WriteLine (string.Format("{0}.MODIFIERS {1}", stringIndent, _helper.AccessFlagsToString(((AccessFlag)method.AccessFlags)))); output.WriteLine (string.Format("{0}.REGISTERS {1}", stringIndent, method.GetRegisterCount())); foreach (var annotation in method.Annotations) { WriteOutAnnotation(output, annotation.Values, dexClass, indent); } if (renderOpcodes) { output.WriteLine (string.Format ("{0}.CODE", stringIndent)); indent++; stringIndent = indent.ToString (); long offset = 0; var lastTryBlockId = 0; var activeTryBlocks = new List<TryCatchBlock> (); TryCatchBlock currentTryBlock = null; foreach (var opcode in method.GetInstructions()) { offset = opcode.OpCodeOffset; // Test for the end of the current try block if (currentTryBlock != null && !currentTryBlock.IsInBlock(offset)) { WriteOutCatchStatements (output, indent, currentTryBlock); activeTryBlocks.Remove (currentTryBlock); if (activeTryBlocks.Count > 0) { currentTryBlock = activeTryBlocks [activeTryBlocks.Count - 1]; } else { currentTryBlock = null; } } // Should open a new try block? if (method.TryCatchBlocks != null && method.TryCatchBlocks.Length > lastTryBlockId) { var tryBlock = method.TryCatchBlocks [lastTryBlockId]; if (tryBlock.IsInBlock (offset)) { output.WriteLine (string.Format ("{0}{1} {2} #{3}", stringIndent, "".PadLeft (12, ' '), ".TRY", lastTryBlockId)); activeTryBlocks.Add (tryBlock); currentTryBlock = tryBlock; lastTryBlockId++; } } if (opcode.Instruction != Instructions.Nop) { output.WriteLine (string.Format("{0}{1} {2}", stringIndent,offset.ToString().PadLeft(12, ' '), opcode.ToString())); } } if (currentTryBlock != null) { WriteOutCatchStatements (output, indent, currentTryBlock); } indent--; } } private void WriteOutCatchStatements(TextWriter output, Indentation indent, TryCatchBlock currentTryBlock) { output.WriteLine (string.Format ("{0}{1} {2}", indent.ToString (), "".PadLeft (12, ' '), ".CATCH")); indent++; foreach (var catchBlock in currentTryBlock.Handlers) { output.WriteLine (string.Format ("{0}{1} {2} address:{3}", indent.ToString(), "".PadLeft (12, ' '), catchBlock.TypeIndex == 0 ? "ALL" : _dex.GetTypeName(catchBlock.TypeIndex), catchBlock.HandlerOffset)); } indent--; } public void WriteOutClass (Class dexClass, ClassDisplayOptions options, TextWriter output) { WriteOutClassDefinition(output, dexClass, options); // Display fields var indent = new Indentation (1); if ((options & ClassDisplayOptions.Fields) != 0) { WriteOutFields(output, dexClass, options, indent); } if ((options & ClassDisplayOptions.Methods) != 0 && dexClass.HasMethods()) { foreach (var method in dexClass.GetMethods()) { WriteOutMethod (dexClass, method, output, indent, (options & ClassDisplayOptions.OpCodes) != 0); output.WriteLine (); } } } public List<HightlightInfo> GetCodeHightlight () { var highlight = new List<HightlightInfo> (); // Directive highlight.Add (new HightlightInfo("^\\s*(\\..*?)\\s", 0x81, 0x5B, 0xA4)); // Keywords highlight.Add (new HightlightInfo("^\\s+\\d+\\s+(.*?)\\s", 158, 28, 78)); // Integers highlight.Add (new HightlightInfo("\\s(#?-?\\d+)", 252, 120, 8)); // Offset highlight.Add (new HightlightInfo("^\\s+(\\d+)", 135, 135, 129)); // Strings highlight.Add (new HightlightInfo("(\".*?\")", 58, 92, 120)); // Labels highlight.Add (new HightlightInfo("\\s(:.+)\\b", 55, 193, 58)); return highlight; } #endregion void WriteOutAnnotation(TextWriter output, EncodedAnnotation annotation, Class currentClass, Indentation indent) { output.WriteLine(string.Format ("{0}.ANNOTATION {1}", indent.ToString(), _dex.GetTypeName(annotation.AnnotationType))); indent++; var stringIndent = indent.ToString (); foreach (var pair in annotation.GetAnnotations()) { output.WriteLine (string.Format("{0}{1}={2}", stringIndent, pair.GetName(_dex), _helper.EncodedValueToString(pair.Value, currentClass))); } indent--; } void WriteOutClassDefinition(TextWriter output, Class dexClass, ClassDisplayOptions options) { output.WriteLine (string.Format(".TYPE {0}", _dex.GetTypeName(dexClass.ClassIndex))); if ((options & ClassDisplayOptions.ClassDetails) != 0) { output.WriteLine (string.Format(".MODIFIERS {0}", _helper.AccessAndType (dexClass))); } if ((options & ClassDisplayOptions.ClassDetails) != 0) { if (dexClass.SuperClassIndex != Class.NO_INDEX) { output.WriteLine (string.Format(".SUPER {0}", _dex.GetTypeName (dexClass.SuperClassIndex))); } if (dexClass.ImplementsInterfaces()) { output.Write (".INTERFACES"); foreach (var iface in dexClass.ImplementedInterfaces()) { output.Write (" "); output.Write (_dex.GetTypeName(iface)); } output.WriteLine (); } } if ((options & ClassDisplayOptions.ClassAnnotations) != 0) { foreach (var annotation in dexClass.Annotations) { WriteOutAnnotation(output, annotation.Values, dexClass, new Indentation()); } } } void WriteOutFields(TextWriter output, Class dexClass, ClassDisplayOptions options, Indentation indent, bool renderAnnotations=true) { if ((options & ClassDisplayOptions.Fields) != 0 && dexClass.HasFields()) { output.WriteLine (); int i=0; foreach (var field in dexClass.GetFields()) { // Field modifiers, type and name if (i < dexClass.StaticFieldsValues.Length) { output.WriteLine (string.Format (".FIELD {0} {1} {2} = {3}", _helper.AccessFlagsToString (field.AccessFlags), _dex.GetTypeName (field.TypeIndex), field.Name, _helper.EncodedValueToString(dexClass.StaticFieldsValues[i], dexClass))); } else { output.WriteLine (string.Format (".FIELD {0} {1} {2}", _helper.AccessFlagsToString (field.AccessFlags), _dex.GetTypeName (field.TypeIndex), field.Name)); } // Field Annotations if (renderAnnotations) { indent++; foreach (var annotation in field.Annotations) { WriteOutAnnotation (output, annotation.Values, dexClass, indent); } indent--; } i++; } } } // private string PrototypeToString (Prototype proto) // { // var shorty = dex.GetString(proto.ShortyIndex); // var returnType = dex.GetTypeName (proto.ReturnTypeIndex); // // var builder = new StringBuilder (); // foreach (var param in proto.Parameters) { // builder.Append(string.Format("\t{0}\n", dex.GetTypeName(param))); // } // // return string.Format ("Short Form:\n\t{0}\nReturn Type:\n\t{1}\nParameters\n{2}", // shorty, returnType, builder.ToString()); // } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Managed locations operations for admin. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class ManagedLocationOperations : IServiceOperations<AzureStackClient>, IManagedLocationOperations { /// <summary> /// Initializes a new instance of the ManagedLocationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ManagedLocationOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Create / Update the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The location update result. /// </returns> public async Task<ManagedLocationCreateOrUpdateResult> CreateOrUpdateAsync(ManagedLocationCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions.Admin/locations/"; if (parameters.Location.Name != null) { url = url + Uri.EscapeDataString(parameters.Location.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject managedLocationCreateOrUpdateParametersValue = new JObject(); requestDoc = managedLocationCreateOrUpdateParametersValue; if (parameters.Location.Id != null) { managedLocationCreateOrUpdateParametersValue["id"] = parameters.Location.Id; } if (parameters.Location.Name != null) { managedLocationCreateOrUpdateParametersValue["name"] = parameters.Location.Name; } if (parameters.Location.DisplayName != null) { managedLocationCreateOrUpdateParametersValue["displayName"] = parameters.Location.DisplayName; } if (parameters.Location.Latitude != null) { managedLocationCreateOrUpdateParametersValue["latitude"] = parameters.Location.Latitude; } if (parameters.Location.Longitude != null) { managedLocationCreateOrUpdateParametersValue["longitude"] = parameters.Location.Longitude; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedLocationCreateOrUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedLocationCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Location locationInstance = new Location(); result.Location = locationInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); locationInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); locationInstance.Name = nameInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); locationInstance.DisplayName = displayNameInstance; } JToken latitudeValue = responseDoc["latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { string latitudeInstance = ((string)latitudeValue); locationInstance.Latitude = latitudeInstance; } JToken longitudeValue = responseDoc["longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { string longitudeInstance = ((string)longitudeValue); locationInstance.Longitude = longitudeInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete a location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='locationName'> /// Required. Name of location to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string locationName, CancellationToken cancellationToken) { // Validate if (locationName == null) { throw new ArgumentNullException("locationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("locationName", locationName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions.Admin/locations/"; url = url + Uri.EscapeDataString(locationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the location. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='locationName'> /// Required. The location name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Location get result. /// </returns> public async Task<ManagedLocationGetResult> GetAsync(string locationName, CancellationToken cancellationToken) { // Validate if (locationName == null) { throw new ArgumentNullException("locationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("locationName", locationName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions.Admin/locations/"; url = url + Uri.EscapeDataString(locationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedLocationGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedLocationGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Location locationInstance = new Location(); result.Location = locationInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); locationInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); locationInstance.Name = nameInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); locationInstance.DisplayName = displayNameInstance; } JToken latitudeValue = responseDoc["latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { string latitudeInstance = ((string)latitudeValue); locationInstance.Latitude = latitudeInstance; } JToken longitudeValue = responseDoc["longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { string longitudeInstance = ((string)longitudeValue); locationInstance.Longitude = longitudeInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get locations under subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The location list result. /// </returns> public async Task<ManagedLocationListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions.Admin/locations"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedLocationListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedLocationListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Location locationInstance = new Location(); result.Locations.Add(locationInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); locationInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); locationInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); locationInstance.DisplayName = displayNameInstance; } JToken latitudeValue = valueValue["latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { string latitudeInstance = ((string)latitudeValue); locationInstance.Latitude = latitudeInstance; } JToken longitudeValue = valueValue["longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { string longitudeInstance = ((string)longitudeValue); locationInstance.Longitude = longitudeInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get locations with the next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The location list result. /// </returns> public async Task<ManagedLocationListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedLocationListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedLocationListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Location locationInstance = new Location(); result.Locations.Add(locationInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); locationInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); locationInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); locationInstance.DisplayName = displayNameInstance; } JToken latitudeValue = valueValue["latitude"]; if (latitudeValue != null && latitudeValue.Type != JTokenType.Null) { string latitudeInstance = ((string)latitudeValue); locationInstance.Latitude = latitudeInstance; } JToken longitudeValue = valueValue["longitude"]; if (longitudeValue != null && longitudeValue.Type != JTokenType.Null) { string longitudeInstance = ((string)longitudeValue); locationInstance.Longitude = longitudeInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; using Avalonia.Layout; using Avalonia.Media; namespace Avalonia.Controls { /// <summary> /// A control used to indicate the progress of an operation. /// </summary> [PseudoClasses(":vertical", ":horizontal", ":indeterminate")] public class ProgressBar : RangeBase { public class ProgressBarTemplateProperties : AvaloniaObject { private double _container2Width; private double _containerWidth; private double _containerAnimationStartPosition; private double _containerAnimationEndPosition; private double _container2AnimationStartPosition; private double _container2AnimationEndPosition; public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationStartPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerAnimationStartPosition), p => p.ContainerAnimationStartPosition, (p, o) => p.ContainerAnimationStartPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationEndPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerAnimationEndPosition), p => p.ContainerAnimationEndPosition, (p, o) => p.ContainerAnimationEndPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationStartPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2AnimationStartPosition), p => p.Container2AnimationStartPosition, (p, o) => p.Container2AnimationStartPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationEndPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2AnimationEndPosition), p => p.Container2AnimationEndPosition, (p, o) => p.Container2AnimationEndPosition = o); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2WidthProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2Width), p => p.Container2Width, (p, o) => p.Container2Width = o); public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerWidthProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerWidth), p => p.ContainerWidth, (p, o) => p.ContainerWidth = o); public double ContainerAnimationStartPosition { get => _containerAnimationStartPosition; set => SetAndRaise(ContainerAnimationStartPositionProperty, ref _containerAnimationStartPosition, value); } public double ContainerAnimationEndPosition { get => _containerAnimationEndPosition; set => SetAndRaise(ContainerAnimationEndPositionProperty, ref _containerAnimationEndPosition, value); } public double Container2AnimationStartPosition { get => _container2AnimationStartPosition; set => SetAndRaise(Container2AnimationStartPositionProperty, ref _container2AnimationStartPosition, value); } public double Container2Width { get => _container2Width; set => SetAndRaise(Container2WidthProperty, ref _container2Width, value); } public double ContainerWidth { get => _containerWidth; set => SetAndRaise(ContainerWidthProperty, ref _containerWidth, value); } public double Container2AnimationEndPosition { get => _container2AnimationEndPosition; set => SetAndRaise(Container2AnimationEndPositionProperty, ref _container2AnimationEndPosition, value); } } private double _indeterminateStartingOffset; private double _indeterminateEndingOffset; private Border? _indicator; public static readonly StyledProperty<bool> IsIndeterminateProperty = AvaloniaProperty.Register<ProgressBar, bool>(nameof(IsIndeterminate)); public static readonly StyledProperty<bool> ShowProgressTextProperty = AvaloniaProperty.Register<ProgressBar, bool>(nameof(ShowProgressText)); public static readonly StyledProperty<Orientation> OrientationProperty = AvaloniaProperty.Register<ProgressBar, Orientation>(nameof(Orientation), Orientation.Horizontal); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public static readonly DirectProperty<ProgressBar, double> IndeterminateStartingOffsetProperty = AvaloniaProperty.RegisterDirect<ProgressBar, double>( nameof(IndeterminateStartingOffset), p => p.IndeterminateStartingOffset, (p, o) => p.IndeterminateStartingOffset = o); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public static readonly DirectProperty<ProgressBar, double> IndeterminateEndingOffsetProperty = AvaloniaProperty.RegisterDirect<ProgressBar, double>( nameof(IndeterminateEndingOffset), p => p.IndeterminateEndingOffset, (p, o) => p.IndeterminateEndingOffset = o); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public double IndeterminateStartingOffset { get => _indeterminateStartingOffset; set => SetAndRaise(IndeterminateStartingOffsetProperty, ref _indeterminateStartingOffset, value); } [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public double IndeterminateEndingOffset { get => _indeterminateEndingOffset; set => SetAndRaise(IndeterminateEndingOffsetProperty, ref _indeterminateEndingOffset, value); } static ProgressBar() { ValueProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); MinimumProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); MaximumProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); IsIndeterminateProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); } public ProgressBar() { UpdatePseudoClasses(IsIndeterminate, Orientation); } public ProgressBarTemplateProperties TemplateProperties { get; } = new ProgressBarTemplateProperties(); public bool IsIndeterminate { get => GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); } public bool ShowProgressText { get => GetValue(ShowProgressTextProperty); set => SetValue(ShowProgressTextProperty, value); } public Orientation Orientation { get => GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { UpdateIndicator(finalSize); return base.ArrangeOverride(finalSize); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == IsIndeterminateProperty) { UpdatePseudoClasses(change.NewValue.GetValueOrDefault<bool>(), null); } else if (change.Property == OrientationProperty) { UpdatePseudoClasses(null, change.NewValue.GetValueOrDefault<Orientation>()); } } /// <inheritdoc/> protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { _indicator = e.NameScope.Get<Border>("PART_Indicator"); UpdateIndicator(Bounds.Size); } private void UpdateIndicator(Size bounds) { if (_indicator != null) { if (IsIndeterminate) { // Pulled from ModernWPF. var dim = Orientation == Orientation.Horizontal ? bounds.Width : bounds.Height; var barIndicatorWidth = dim * 0.4; // Indicator width at 40% of ProgressBar var barIndicatorWidth2 = dim * 0.6; // Indicator width at 60% of ProgressBar TemplateProperties.ContainerWidth = barIndicatorWidth; TemplateProperties.Container2Width = barIndicatorWidth2; TemplateProperties.ContainerAnimationStartPosition = barIndicatorWidth * -1.8; // Position at -180% TemplateProperties.ContainerAnimationEndPosition = barIndicatorWidth * 3.0; // Position at 300% TemplateProperties.Container2AnimationStartPosition = barIndicatorWidth2 * -1.5; // Position at -150% TemplateProperties.Container2AnimationEndPosition = barIndicatorWidth2 * 1.66; // Position at 166% #pragma warning disable CS0618 // Type or member is obsolete // Remove these properties when we switch to fluent as default and removed the old one. IndeterminateStartingOffset = -dim; IndeterminateEndingOffset = dim; #pragma warning restore CS0618 // Type or member is obsolete var padding = Padding; var rectangle = new RectangleGeometry( new Rect( padding.Left, padding.Top, bounds.Width - (padding.Right + padding.Left), bounds.Height - (padding.Bottom + padding.Top) )); } else { double percent = Maximum == Minimum ? 1.0 : (Value - Minimum) / (Maximum - Minimum); if (Orientation == Orientation.Horizontal) _indicator.Width = bounds.Width * percent; else _indicator.Height = bounds.Height * percent; } } } private void UpdateIndicatorWhenPropChanged(AvaloniaPropertyChangedEventArgs e) { UpdateIndicator(Bounds.Size); } private void UpdatePseudoClasses( bool? isIndeterminate, Orientation? o) { if (isIndeterminate.HasValue) { PseudoClasses.Set(":indeterminate", isIndeterminate.Value); } if (o.HasValue) { PseudoClasses.Set(":vertical", o == Orientation.Vertical); PseudoClasses.Set(":horizontal", o == Orientation.Horizontal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using Microsoft.Xml; using System.ComponentModel; namespace System.ServiceModel.Channels { public sealed class TextMessageEncodingBindingElement : MessageEncodingBindingElement { private int _maxReadPoolSize; private int _maxWritePoolSize; private XmlDictionaryReaderQuotas _readerQuotas; private MessageVersion _messageVersion; private Encoding _writeEncoding; public TextMessageEncodingBindingElement() : this(MessageVersion.Default, TextEncoderDefaults.Encoding) { } public TextMessageEncodingBindingElement(MessageVersion messageVersion, Encoding writeEncoding) { if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (writeEncoding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding"); TextEncoderDefaults.ValidateEncoding(writeEncoding); _maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; _maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(_readerQuotas); _messageVersion = messageVersion; _writeEncoding = writeEncoding; } private TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { _maxReadPoolSize = elementToBeCloned._maxReadPoolSize; _maxWritePoolSize = elementToBeCloned._maxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned._readerQuotas.CopyTo(_readerQuotas); _writeEncoding = elementToBeCloned._writeEncoding; _messageVersion = elementToBeCloned._messageVersion; } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return _maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.ValueMustBePositive)); } _maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return _maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SRServiceModel.ValueMustBePositive)); } _maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_readerQuotas); } } public override MessageVersion MessageVersion { get { return _messageVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _messageVersion = value; } } public Encoding WriteEncoding { get { return _writeEncoding; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } TextEncoderDefaults.ValidateEncoding(value); _writeEncoding = value; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { return InternalBuildChannelFactory<TChannel>(context); } public override BindingElement Clone() { return new TextMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new TextMessageEncoderFactory(MessageVersion, WriteEncoding, this.MaxReadPoolSize, this.MaxWritePoolSize, this.ReaderQuotas); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)_readerQuotas; } else { return base.GetProperty<T>(context); } } internal override bool CheckEncodingVersion(EnvelopeVersion version) { return _messageVersion.Envelope == version; } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) return false; TextMessageEncodingBindingElement text = b as TextMessageEncodingBindingElement; if (text == null) return false; if (_maxReadPoolSize != text.MaxReadPoolSize) return false; if (_maxWritePoolSize != text.MaxWritePoolSize) return false; // compare XmlDictionaryReaderQuotas if (_readerQuotas.MaxStringContentLength != text.ReaderQuotas.MaxStringContentLength) return false; if (_readerQuotas.MaxArrayLength != text.ReaderQuotas.MaxArrayLength) return false; if (_readerQuotas.MaxBytesPerRead != text.ReaderQuotas.MaxBytesPerRead) return false; if (_readerQuotas.MaxDepth != text.ReaderQuotas.MaxDepth) return false; if (_readerQuotas.MaxNameTableCharCount != text.ReaderQuotas.MaxNameTableCharCount) return false; if (this.WriteEncoding.WebName != text.WriteEncoding.WebName) return false; if (!this.MessageVersion.IsMatch(text.MessageVersion)) return false; return true; } } }
namespace Obscur.Core.Cryptography.Ciphers.Block.Primitives { #if INCLUDE_RIJNDAEL /** * an implementation of Rijndael, based on the documentation and reference implementation * by Paulo Barreto, Vincent Rijmen, for v2.0 August '99. * <p> * Note: this implementation is based on information prior to readonly NIST publication. * </p> */ public class RijndaelEngine : IBlockCipher { private static readonly int MAXROUNDS = 14; private static readonly int MAXKC = (256/4); private static readonly byte[] Logtable = { 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 }; private static readonly byte[] Alogtable = { 0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, }; private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; static readonly byte[][] shifts0 = new byte [][] { new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 32 }, new byte[]{ 0, 8, 24, 32 } }; static readonly byte[][] shifts1 = { new byte[]{ 0, 24, 16, 8 }, new byte[]{ 0, 32, 24, 16 }, new byte[]{ 0, 40, 32, 24 }, new byte[]{ 0, 48, 40, 24 }, new byte[]{ 0, 56, 40, 32 } }; /** * multiply two elements of GF(2^m) * needed for MixColumn and InvMixColumn */ private byte Mul0x2( int b) { if (b != 0) { return Alogtable[25 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x3( int b) { if (b != 0) { return Alogtable[1 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x9( int b) { if (b >= 0) { return Alogtable[199 + b]; } else { return 0; } } private byte Mul0xb( int b) { if (b >= 0) { return Alogtable[104 + b]; } else { return 0; } } private byte Mul0xd( int b) { if (b >= 0) { return Alogtable[238 + b]; } else { return 0; } } private byte Mul0xe( int b) { if (b >= 0) { return Alogtable[223 + b]; } else { return 0; } } /** * xor corresponding text input and round key input bytes */ private void KeyAddition( long[] rk) { A0 ^= rk[0]; A1 ^= rk[1]; A2 ^= rk[2]; A3 ^= rk[3]; } private long Shift( long r, int shift) { //return (((long)((ulong) r >> shift) | (r << (BC - shift)))) & BC_MASK; ulong temp = (ulong) r >> shift; // NB: This corrects for Mono Bug #79087 (fixed in 1.1.17) if (shift > 31) { temp &= 0xFFFFFFFFUL; } return ((long) temp | (r << (BC - shift))) & BC_MASK; } /** * Row 0 remains unchanged * The other three rows are shifted a variable amount */ private void ShiftRow( byte[] shiftsSC) { A1 = Shift(A1, shiftsSC[1]); A2 = Shift(A2, shiftsSC[2]); A3 = Shift(A3, shiftsSC[3]); } private long ApplyS( long r, byte[] box) { long res = 0; for (int j = 0; j < BC; j += 8) { res |= (long)(box[(int)((r >> j) & 0xff)] & 0xff) << j; } return res; } /** * Replace every byte of the input by the byte at that place * in the nonlinear S-box */ private void Substitution( byte[] box) { A0 = ApplyS(A0, box); A1 = ApplyS(A1, box); A2 = ApplyS(A2, box); A3 = ApplyS(A3, box); } /** * Mix the bytes of every column in a linear way */ private void MixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (int j = 0; j < BC; j += 8) { int a0 = (int)((A0 >> j) & 0xff); int a1 = (int)((A1 >> j) & 0xff); int a2 = (int)((A2 >> j) & 0xff); int a3 = (int)((A3 >> j) & 0xff); r0 |= (long)((Mul0x2(a0) ^ Mul0x3(a1) ^ a2 ^ a3) & 0xff) << j; r1 |= (long)((Mul0x2(a1) ^ Mul0x3(a2) ^ a3 ^ a0) & 0xff) << j; r2 |= (long)((Mul0x2(a2) ^ Mul0x3(a3) ^ a0 ^ a1) & 0xff) << j; r3 |= (long)((Mul0x2(a3) ^ Mul0x3(a0) ^ a1 ^ a2) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Mix the bytes of every column in a linear way * This is the opposite operation of Mixcolumn */ private void InvMixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (int j = 0; j < BC; j += 8) { int a0 = (int)((A0 >> j) & 0xff); int a1 = (int)((A1 >> j) & 0xff); int a2 = (int)((A2 >> j) & 0xff); int a3 = (int)((A3 >> j) & 0xff); // // pre-lookup the log table // a0 = (a0 != 0) ? (Logtable[a0 & 0xff] & 0xff) : -1; a1 = (a1 != 0) ? (Logtable[a1 & 0xff] & 0xff) : -1; a2 = (a2 != 0) ? (Logtable[a2 & 0xff] & 0xff) : -1; a3 = (a3 != 0) ? (Logtable[a3 & 0xff] & 0xff) : -1; r0 |= (long)((Mul0xe(a0) ^ Mul0xb(a1) ^ Mul0xd(a2) ^ Mul0x9(a3)) & 0xff) << j; r1 |= (long)((Mul0xe(a1) ^ Mul0xb(a2) ^ Mul0xd(a3) ^ Mul0x9(a0)) & 0xff) << j; r2 |= (long)((Mul0xe(a2) ^ Mul0xb(a3) ^ Mul0xd(a0) ^ Mul0x9(a1)) & 0xff) << j; r3 |= (long)((Mul0xe(a3) ^ Mul0xb(a0) ^ Mul0xd(a1) ^ Mul0x9(a2)) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Calculate the necessary round keys * The number of calculations depends on keyBits and blockBits */ private long[][] GenerateWorkingKey( byte[] key) { int KC; int t, rconpointer = 0; int keyBits = key.Length * 8; byte[,] tk = new byte[4,MAXKC]; //long[,] W = new long[MAXROUNDS+1,4]; long[][] W = new long[MAXROUNDS+1][]; for (int i = 0; i < MAXROUNDS+1; i++) W[i] = new long[4]; switch (keyBits) { case 128: KC = 4; break; case 160: KC = 5; break; case 192: KC = 6; break; case 224: KC = 7; break; case 256: KC = 8; break; default : throw new ArgumentException("Key length not 128/160/192/224/256 bits."); } if (keyBits >= blockBits) { ROUNDS = KC + 6; } else { ROUNDS = (BC / 8) + 6; } // // copy the key into the processing area // int index = 0; for (int i = 0; i < key.Length; i++) { tk[i % 4,i / 4] = key[index++]; } t = 0; // // copy values into round key array // for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC / 8)); j++, t++) { for (int i = 0; i < 4; i++) { W[t / (BC / 8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % BC); } } // // while not enough round key material calculated // calculate new values // while (t < (ROUNDS+1)*(BC/8)) { for (int i = 0; i < 4; i++) { tk[i,0] ^= S[tk[(i+1)%4,KC-1] & 0xff]; } tk[0,0] ^= (byte) rcon[rconpointer++]; if (KC <= 6) { for (int j = 1; j < KC; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } else { for (int j = 1; j < 4; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } for (int i = 0; i < 4; i++) { tk[i,4] ^= S[tk[i,3] & 0xff]; } for (int j = 5; j < KC; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } // // copy values into round key array // for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC/8)); j++, t++) { for (int i = 0; i < 4; i++) { W[t / (BC/8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % (BC)); } } } return W; } private int BC; private long BC_MASK; private int ROUNDS; private int blockBits; private long[][] workingKey; private long A0, A1, A2, A3; private bool forEncryption; private byte[] shifts0SC; private byte[] shifts1SC; /** * default constructor - 128 bit block size. */ public RijndaelEngine() : this(128) {} /** * basic constructor - set the cipher up for a given blocksize * * @param blocksize the blocksize in bits, must be 128, 192, or 256. */ public RijndaelEngine( int blockBits) { switch (blockBits) { case 128: BC = 32; BC_MASK = 0xffffffffL; shifts0SC = shifts0[0]; shifts1SC = shifts1[0]; break; case 160: BC = 40; BC_MASK = 0xffffffffffL; shifts0SC = shifts0[1]; shifts1SC = shifts1[1]; break; case 192: BC = 48; BC_MASK = 0xffffffffffffL; shifts0SC = shifts0[2]; shifts1SC = shifts1[2]; break; case 224: BC = 56; BC_MASK = 0xffffffffffffffL; shifts0SC = shifts0[3]; shifts1SC = shifts1[3]; break; case 256: BC = 64; BC_MASK = unchecked( (long)0xffffffffffffffffL); shifts0SC = shifts0[4]; shifts1SC = shifts1[4]; break; default: throw new ArgumentException("unknown blocksize to Rijndael"); } this.blockBits = blockBits; } /** * initialise a Rijndael cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (typeof(KeyParameter).IsInstanceOfType(parameters)) { workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey()); this.forEncryption = forEncryption; return; } throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString()); } public string AlgorithmName { get { return "Rijndael"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BC / 2; } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) { throw new InvalidOperationException("Rijndael engine not initialised"); } if ((inOff + (BC / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (BC / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(workingKey); } else { DecryptBlock(workingKey); } PackBlock(output, outOff); return BC / 2; } public void Reset() { } private void UnPackBlock( byte[] bytes, int off) { int index = off; A0 = (long)(bytes[index++] & 0xff); A1 = (long)(bytes[index++] & 0xff); A2 = (long)(bytes[index++] & 0xff); A3 = (long)(bytes[index++] & 0xff); for (int j = 8; j != BC; j += 8) { A0 |= (long)(bytes[index++] & 0xff) << j; A1 |= (long)(bytes[index++] & 0xff) << j; A2 |= (long)(bytes[index++] & 0xff) << j; A3 |= (long)(bytes[index++] & 0xff) << j; } } private void PackBlock( byte[] bytes, int off) { int index = off; for (int j = 0; j != BC; j += 8) { bytes[index++] = (byte)(A0 >> j); bytes[index++] = (byte)(A1 >> j); bytes[index++] = (byte)(A2 >> j); bytes[index++] = (byte)(A3 >> j); } } private void EncryptBlock( long[][] rk) { int r; // // begin with a key addition // KeyAddition(rk[0]); // // ROUNDS-1 ordinary rounds // for (r = 1; r < ROUNDS; r++) { Substitution(S); ShiftRow(shifts0SC); MixColumn(); KeyAddition(rk[r]); } // // Last round is special: there is no MixColumn // Substitution(S); ShiftRow(shifts0SC); KeyAddition(rk[ROUNDS]); } private void DecryptBlock( long[][] rk) { int r; // To decrypt: apply the inverse operations of the encrypt routine, // in opposite order // // (KeyAddition is an involution: it 's equal to its inverse) // (the inverse of Substitution with table S is Substitution with the inverse table of S) // (the inverse of Shiftrow is Shiftrow over a suitable distance) // // First the special round: // without InvMixColumn // with extra KeyAddition // KeyAddition(rk[ROUNDS]); Substitution(Si); ShiftRow(shifts1SC); // // ROUNDS-1 ordinary rounds // for (r = ROUNDS-1; r > 0; r--) { KeyAddition(rk[r]); InvMixColumn(); Substitution(Si); ShiftRow(shifts1SC); } // // End with the extra key addition // KeyAddition(rk[0]); } } #endif }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ZipQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// A Zip operator combines two input data sources into a single output stream, /// using a pairwise element matching algorithm. For example, the result of zipping /// two vectors a = {0, 1, 2, 3} and b = {9, 8, 7, 6} is the vector of pairs, /// c = {(0,9), (1,8), (2,7), (3,6)}. Because the expectation is that each element /// is matched with the element in the other data source at the same ordinal /// position, the zip operator requires order preservation. /// </summary> /// <typeparam name="TLeftInput"></typeparam> /// <typeparam name="TRightInput"></typeparam> /// <typeparam name="TOutput"></typeparam> internal sealed class ZipQueryOperator<TLeftInput, TRightInput, TOutput> : QueryOperator<TOutput> { private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // To select result elements. private readonly QueryOperator<TLeftInput> _leftChild; private readonly QueryOperator<TRightInput> _rightChild; private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source private readonly bool _limitsParallelism = false; // Whether this operator limits parallelism //--------------------------------------------------------------------------------------- // Initializes a new zip operator. // // Arguments: // leftChild - the left data source from which to pull data. // rightChild - the right data source from which to pull data. // internal ZipQueryOperator( ParallelQuery<TLeftInput> leftChildSource, ParallelQuery<TRightInput> rightChildSource, Func<TLeftInput, TRightInput, TOutput> resultSelector) : this( QueryOperator<TLeftInput>.AsQueryOperator(leftChildSource), QueryOperator<TRightInput>.AsQueryOperator(rightChildSource), resultSelector) { } private ZipQueryOperator( QueryOperator<TLeftInput> left, QueryOperator<TRightInput> right, Func<TLeftInput, TRightInput, TOutput> resultSelector) : base(left.SpecifiedQuerySettings.Merge(right.SpecifiedQuerySettings)) { Debug.Assert(resultSelector != null, "operator cannot be null"); _leftChild = left; _rightChild = right; _resultSelector = resultSelector; _outputOrdered = _leftChild.OutputOrdered || _rightChild.OutputOrdered; OrdinalIndexState leftIndexState = _leftChild.OrdinalIndexState; OrdinalIndexState rightIndexState = _rightChild.OrdinalIndexState; _prematureMergeLeft = leftIndexState != OrdinalIndexState.Indexible; _prematureMergeRight = rightIndexState != OrdinalIndexState.Indexible; _limitsParallelism = (_prematureMergeLeft && leftIndexState != OrdinalIndexState.Shuffled) || (_prematureMergeRight && rightIndexState != OrdinalIndexState.Shuffled); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the children and wrapping them with // partitions as needed. // internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping) { // We just open our child operators, left and then right. QueryResults<TLeftInput> leftChildResults = _leftChild.Open(settings, preferStriping); QueryResults<TRightInput> rightChildResults = _rightChild.Open(settings, preferStriping); int partitionCount = settings.DegreeOfParallelism.Value; if (_prematureMergeLeft) { PartitionedStreamMerger<TLeftInput> merger = new PartitionedStreamMerger<TLeftInput>( false, ParallelMergeOptions.FullyBuffered, settings.TaskScheduler, _leftChild.OutputOrdered, settings.CancellationState, settings.QueryId); leftChildResults.GivePartitionedStream(merger); leftChildResults = new ListQueryResults<TLeftInput>( merger.MergeExecutor.GetResultsAsArray(), partitionCount, preferStriping); } if (_prematureMergeRight) { PartitionedStreamMerger<TRightInput> merger = new PartitionedStreamMerger<TRightInput>( false, ParallelMergeOptions.FullyBuffered, settings.TaskScheduler, _rightChild.OutputOrdered, settings.CancellationState, settings.QueryId); rightChildResults.GivePartitionedStream(merger); rightChildResults = new ListQueryResults<TRightInput>( merger.MergeExecutor.GetResultsAsArray(), partitionCount, preferStriping); } return new ZipQueryOperatorResults(leftChildResults, rightChildResults, _resultSelector, partitionCount, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token) { using (IEnumerator<TLeftInput> leftEnumerator = _leftChild.AsSequentialQuery(token).GetEnumerator()) using (IEnumerator<TRightInput> rightEnumerator = _rightChild.AsSequentialQuery(token).GetEnumerator()) { while (leftEnumerator.MoveNext() && rightEnumerator.MoveNext()) { yield return _resultSelector(leftEnumerator.Current, rightEnumerator.Current); } } } //--------------------------------------------------------------------------------------- // The state of the order index of the results returned by this operator. // internal override OrdinalIndexState OrdinalIndexState { get { return OrdinalIndexState.Indexible; } } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // A special QueryResults class for the Zip operator. It requires that both of the child // QueryResults are indexible. // internal class ZipQueryOperatorResults : QueryResults<TOutput> { private readonly QueryResults<TLeftInput> _leftChildResults; private readonly QueryResults<TRightInput> _rightChildResults; private readonly Func<TLeftInput, TRightInput, TOutput> _resultSelector; // To select result elements. private readonly int _count; private readonly int _partitionCount; private readonly bool _preferStriping; internal ZipQueryOperatorResults( QueryResults<TLeftInput> leftChildResults, QueryResults<TRightInput> rightChildResults, Func<TLeftInput, TRightInput, TOutput> resultSelector, int partitionCount, bool preferStriping) { _leftChildResults = leftChildResults; _rightChildResults = rightChildResults; _resultSelector = resultSelector; _partitionCount = partitionCount; _preferStriping = preferStriping; Debug.Assert(_leftChildResults.IsIndexible); Debug.Assert(_rightChildResults.IsIndexible); _count = Math.Min(_leftChildResults.Count, _rightChildResults.Count); } internal override int ElementsCount { get { return _count; } } internal override bool IsIndexible { get { return true; } } internal override TOutput GetElement(int index) { return _resultSelector(_leftChildResults.GetElement(index), _rightChildResults.GetElement(index)); } internal override void GivePartitionedStream(IPartitionedStreamRecipient<TOutput> recipient) { PartitionedStream<TOutput, int> partitionedStream = ExchangeUtilities.PartitionDataSource(this, _partitionCount, _preferStriping); recipient.Receive(partitionedStream); } } } }
//#define ZEN_DO_NOT_USE_COMPILED_EXPRESSIONS using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using ModestTree; #if !NOT_UNITY3D using UnityEngine; #endif namespace Zenject.Internal { public static class ReflectionInfoTypeInfoConverter { public static InjectTypeInfo.InjectMethodInfo ConvertMethod( ReflectionTypeInfo.InjectMethodInfo injectMethod) { var methodInfo = injectMethod.MethodInfo; var action = TryCreateActionForMethod(methodInfo); if (action == null) { action = (obj, args) => methodInfo.Invoke(obj, args); } return new InjectTypeInfo.InjectMethodInfo( action, injectMethod.Parameters.Select(x => x.InjectableInfo).ToArray(), methodInfo.Name); } public static InjectTypeInfo.InjectConstructorInfo ConvertConstructor( ReflectionTypeInfo.InjectConstructorInfo injectConstructor, Type type) { return new InjectTypeInfo.InjectConstructorInfo( TryCreateFactoryMethod(type, injectConstructor), injectConstructor.Parameters.Select(x => x.InjectableInfo).ToArray()); } public static InjectTypeInfo.InjectMemberInfo ConvertField( Type parentType, ReflectionTypeInfo.InjectFieldInfo injectField) { return new InjectTypeInfo.InjectMemberInfo( GetSetter(parentType, injectField.FieldInfo), injectField.InjectableInfo); } public static InjectTypeInfo.InjectMemberInfo ConvertProperty( Type parentType, ReflectionTypeInfo.InjectPropertyInfo injectProperty) { return new InjectTypeInfo.InjectMemberInfo( GetSetter(parentType, injectProperty.PropertyInfo), injectProperty.InjectableInfo); } static ZenFactoryMethod TryCreateFactoryMethod( Type type, ReflectionTypeInfo.InjectConstructorInfo reflectionInfo) { #if !NOT_UNITY3D if (type.DerivesFromOrEqual<Component>()) { return null; } #endif if (type.IsAbstract()) { Assert.That(reflectionInfo.Parameters.IsEmpty()); return null; } var constructor = reflectionInfo.ConstructorInfo; var factoryMethod = TryCreateFactoryMethodCompiledLambdaExpression(type, constructor); if (factoryMethod == null) { if (constructor == null) { if (ReflectionTypeAnalyzer.ConstructorChoiceStrategy == ConstructorChoiceStrategy.InjectAttribute) { return null; } // No choice in this case except to use the slow Activator.CreateInstance // as far as I know // This should be rare though and only seems to occur when instantiating // structs on platforms that don't support lambda expressions // Non-structs should always have a default constructor factoryMethod = args => { Assert.That(args.Length == 0); return Activator.CreateInstance(type, new object[0]); }; } else { factoryMethod = constructor.Invoke; } } return factoryMethod; } static ZenFactoryMethod TryCreateFactoryMethodCompiledLambdaExpression( Type type, ConstructorInfo constructor) { #if (NET_4_6 || NET_STANDARD_2_0) && !ENABLE_IL2CPP && !ZEN_DO_NOT_USE_COMPILED_EXPRESSIONS if (type.ContainsGenericParameters) { return null; } ParameterExpression param = Expression.Parameter(typeof(object[])); if (constructor == null) { return Expression.Lambda<ZenFactoryMethod>( Expression.Convert( Expression.New(type), typeof(object)), param).Compile(); } ParameterInfo[] par = constructor.GetParameters(); Expression[] args = new Expression[par.Length]; for (int i = 0; i != par.Length; ++i) { args[i] = Expression.Convert( Expression.ArrayIndex( param, Expression.Constant(i)), par[i].ParameterType); } return Expression.Lambda<ZenFactoryMethod>( Expression.Convert( Expression.New(constructor, args), typeof(object)), param).Compile(); #else return null; #endif } static ZenInjectMethod TryCreateActionForMethod(MethodInfo methodInfo) { #if (NET_4_6 || NET_STANDARD_2_0) && !ENABLE_IL2CPP && !ZEN_DO_NOT_USE_COMPILED_EXPRESSIONS if (methodInfo.DeclaringType.ContainsGenericParameters) { return null; } ParameterInfo[] par = methodInfo.GetParameters(); if (par.Any(x => x.ParameterType.ContainsGenericParameters)) { return null; } Expression[] args = new Expression[par.Length]; ParameterExpression argsParam = Expression.Parameter(typeof(object[])); ParameterExpression instanceParam = Expression.Parameter(typeof(object)); for (int i = 0; i != par.Length; ++i) { args[i] = Expression.Convert( Expression.ArrayIndex( argsParam, Expression.Constant(i)), par[i].ParameterType); } return Expression.Lambda<ZenInjectMethod>( Expression.Call( Expression.Convert(instanceParam, methodInfo.DeclaringType), methodInfo, args), instanceParam, argsParam).Compile(); #else return null; #endif } #if !(UNITY_WSA && ENABLE_DOTNET) || UNITY_EDITOR static IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags flags) { if (t == null) { return Enumerable.Empty<FieldInfo>(); } return t.GetFields(flags).Concat(GetAllFields(t.BaseType, flags)).Distinct(); } static ZenMemberSetterMethod GetOnlyPropertySetter( Type parentType, string propertyName) { Assert.That(parentType != null); Assert.That(!string.IsNullOrEmpty(propertyName)); var allFields = GetAllFields( parentType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).ToList(); var writeableFields = allFields.Where(f => f.Name == string.Format("<" + propertyName + ">k__BackingField", propertyName)).ToList(); if (!writeableFields.Any()) { throw new ZenjectException(string.Format( "Can't find backing field for get only property {0} on {1}.\r\n{2}", propertyName, parentType.FullName, string.Join(";", allFields.Select(f => f.Name).ToArray()))); } return (injectable, value) => writeableFields.ForEach(f => f.SetValue(injectable, value)); } #endif static ZenMemberSetterMethod GetSetter(Type parentType, MemberInfo memInfo) { var setterMethod = TryGetSetterAsCompiledExpression(parentType, memInfo); if (setterMethod != null) { return setterMethod; } var fieldInfo = memInfo as FieldInfo; var propInfo = memInfo as PropertyInfo; if (fieldInfo != null) { return ((injectable, value) => fieldInfo.SetValue(injectable, value)); } Assert.IsNotNull(propInfo); #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return ((object injectable, object value) => propInfo.SetValue(injectable, value, null)); #else if (propInfo.CanWrite) { return ((injectable, value) => propInfo.SetValue(injectable, value, null)); } return GetOnlyPropertySetter(parentType, propInfo.Name); #endif } static ZenMemberSetterMethod TryGetSetterAsCompiledExpression(Type parentType, MemberInfo memInfo) { #if (NET_4_6 || NET_STANDARD_2_0) && !ENABLE_IL2CPP && !ZEN_DO_NOT_USE_COMPILED_EXPRESSIONS if (parentType.ContainsGenericParameters) { return null; } var fieldInfo = memInfo as FieldInfo; var propInfo = memInfo as PropertyInfo; // It seems that for readonly fields, we have to use the slower approach below // As discussed here: https://www.productiverage.com/trying-to-set-a-readonly-autoproperty-value-externally-plus-a-little-benchmarkdotnet // We have to skip value types because those can only be set by reference using an lambda expression if (!parentType.IsValueType() && (fieldInfo == null || !fieldInfo.IsInitOnly) && (propInfo == null || propInfo.CanWrite)) { Type memberType = fieldInfo != null ? fieldInfo.FieldType : propInfo.PropertyType; var typeParam = Expression.Parameter(typeof(object)); var valueParam = Expression.Parameter(typeof(object)); return Expression.Lambda<ZenMemberSetterMethod>( Expression.Assign( Expression.MakeMemberAccess(Expression.Convert(typeParam, parentType), memInfo), Expression.Convert(valueParam, memberType)), typeParam, valueParam).Compile(); } #endif return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using DotVVM.Framework.ViewModel; using DotVVM.Framework.ViewModel.Validation; using DotVVM.Framework.ViewModel.Serialization; using DotVVM.Framework.Configuration; using DotVVM.Framework.Testing; using Microsoft.Extensions.DependencyInjection; using DotVVM.Framework.Hosting; namespace DotVVM.Framework.Tests.ViewModel { [TestClass] public class ViewModelValidatorTests { private IViewModelValidator CreateValidator() => DotvvmTestHelper.CreateConfiguration().ServiceProvider.GetRequiredService<IViewModelValidator>(); private IValidationErrorPathExpander CreateErrorPathExpander() => DotvvmTestHelper.CreateConfiguration().ServiceProvider.GetRequiredService<IValidationErrorPathExpander>(); [TestMethod] public void ViewModelValidator_SimpleObject() { var testViewModel = new TestViewModel(); var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/Text", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_ObjectWithCollection() { var testViewModel = new TestViewModel() { Children = new List<TestViewModel2>() { new TestViewModel2() { Code = "012" }, new TestViewModel2() { Code = "ABC", Id = 13 }, new TestViewModel2() { Code = "345", Id = 15 } }, Child = new TestViewModel2() { Code = "123" } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(4, results.Count); Assert.AreEqual("/Child/Id", results[0].PropertyPath); Assert.AreEqual("/Children/0/Id", results[1].PropertyPath); Assert.AreEqual("/Children/1/Code", results[2].PropertyPath); Assert.AreEqual("/Text", results[3].PropertyPath); } [TestMethod] public void ViewModelValidator_ServerOnlyRules() { var testViewModel = new TestViewModel3() { Email = "aaa" }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/Email", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_WithValidationTarget_Property() { var testViewModel = new TestViewModel() { Child = new TestViewModel2() { Code = "5" } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel.Child }; var errors = validator.ValidateViewModel(testViewModel.Child).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(2, results.Count); Assert.AreEqual("/Child/Code", results[0].PropertyPath); Assert.AreEqual("/Child/Id", results[1].PropertyPath); } [TestMethod] public void ViewModelValidator_WithValidationTarget_ArrayElement() { var testViewModel = new TestViewModel() { Children = new List<TestViewModel2>() { new TestViewModel2() { Code = "5" }, new TestViewModel2() { Code = "6" }, new TestViewModel2() { Code = "7" }, } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel.Children[1] }; var errors = validator.ValidateViewModel(testViewModel.Children[1]).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(2, results.Count); Assert.AreEqual("/Children/1/Code", results[0].PropertyPath); Assert.AreEqual("/Children/1/Id", results[1].PropertyPath); } [TestMethod] public void ViewModelValidator_Child_CustomValidationAttribute() { var testViewModel = new TestViewModel4() { Child = new TestViewModel4Child() { IsChecked = true } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/Child/ConditionalRequired", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_ListChild_CustomValidationAttribute() { var testViewModel = new List<TestViewModel4>{ new TestViewModel4() { Child = new TestViewModel4Child() { IsChecked = true } } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/0/Child/ConditionalRequired", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_Child_IValidatableObject() { var testViewModel = new TestViewModel5() { Child = new TestViewModel5Child() { IsChecked = true } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/Child/ConditionalRequired", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_CollectionOfIValidatableObjects() { var testViewModel = new TestViewModel6() { Children = new List<TestViewModel5Child>() {new TestViewModel5Child() {IsChecked = true}} }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/Children/0/ConditionalRequired", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_ValidationErrorFactoryWithValidationContextSupplied() { var testViewModel = new TestViewModel7(); var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = new ModelState() { ValidationTarget = testViewModel }; var errors = validator.ValidateViewModel(testViewModel).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("/IsChecked", results[0].PropertyPath); } [TestMethod] public void ViewModelValidator_CustomModelStateErrors() { var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null), Child = new TestViewModel2() { Id = 11, Code = "Code", }, }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = testViewModel.Context.ModelState; var validationTarget = testViewModel; modelState.ValidationTarget = validationTarget; ValidationErrorFactory.AddModelError(testViewModel, vm => vm, "Custom root error."); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual("/", results[0].PropertyPath); Assert.AreEqual("/Child/Code", results[1].PropertyPath); Assert.AreEqual("/Text", results[2].PropertyPath); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ViewModelValidator_CustomModelStateErrors_OldFormatThrows() { var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null), Child = new TestViewModel2() { Id = 11, Code = "Code", }, }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = testViewModel.Context.ModelState; var validationTarget = testViewModel; modelState.ValidationTarget = validationTarget; testViewModel.Context.AddRawModelError("Child()", "Validation target path as a knockout expression"); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); } [TestMethod] public void ViewModelValidator_CustomModelStateErrors_OutsideValidationTarget() { var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null), Child = new TestViewModel2() { Id = 11, Code = "Code", }, Children = new List<TestViewModel2>() { new TestViewModel2() { Code = "5" }, new TestViewModel2() { Code = "6" }, new TestViewModel2() { Code = "7" }, } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = testViewModel.Context.ModelState; var validationTarget = testViewModel.Children[0]; modelState.ValidationTarget = validationTarget; testViewModel.AddModelError(vm => vm, "Custom root error. Outside of validation target."); testViewModel.AddModelError(vm => vm.Child, "Custom Child error. Outside of validation target."); testViewModel.AddModelError(vm => vm.Children[2], "Custom Children[2] error. Outside of validation target."); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(5, results.Count); Assert.AreEqual("/", results[0].PropertyPath); Assert.AreEqual("/Child", results[1].PropertyPath); Assert.AreEqual("/Children/0/Code", results[2].PropertyPath); Assert.AreEqual("/Children/0/Id", results[3].PropertyPath); Assert.AreEqual("/Children/2", results[4].PropertyPath); } [TestMethod] public void ViewModelValidator_CustomModelStateErrors_ArbitraryTargetObjectAndLambda() { var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null), Child = new TestViewModel2() { Id = 11, Code = "Code", }, Children = new List<TestViewModel2>() { new TestViewModel2() { Code = "5" }, new TestViewModel2() { Code = "6" }, new TestViewModel2() { Code = "7" }, } }; var context = testViewModel.Context; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = context.ModelState; var validationTarget = testViewModel.Children[1]; modelState.ValidationTarget = validationTarget; context.AddModelError(testViewModel.Children[1], o => o.Code, "Custom /Children/1/Code error."); context.AddModelError(testViewModel.Children, o => o[1].Code, "Custom /Children/1/Code error."); // Add error that is unreachable from root viewmodel context.AddModelError(new TestViewModel2(), o => o.Id, "Unreachable error - won't be resolved."); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); var results = modelState.Errors.OrderBy(n => n.PropertyPath).ToList(); Assert.AreEqual(4, results.Count); Assert.AreEqual("/Children/1/Code", results[0].PropertyPath); Assert.AreEqual("/Children/1/Code", results[1].PropertyPath); Assert.AreEqual("/Children/1/Code", results[2].PropertyPath); Assert.AreEqual("/Children/1/Id", results[3].PropertyPath); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void ViewModelValidator_ObjectWithAttachedErrorReferencedMultipleTimes() { var innerViewModel = new TestViewModel2() { Code = "123" }; var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null), Child = new TestViewModel2() { Id = 11, Code = "Code", }, Children = new List<TestViewModel2>() { innerViewModel, new TestViewModel2() { Code = "6" }, innerViewModel, } }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var modelState = testViewModel.Context.ModelState; var validationTarget = testViewModel; modelState.ValidationTarget = validationTarget; testViewModel.AddModelError(vm => vm.Children[0], "An error on object that is found multiple times in viewmodel."); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); } [TestMethod] [DataRow("Child().Code()")] [DataRow("$rawData")] [DataRow("dotvvm.viewModels['root']")] [ExpectedException(typeof(ArgumentException))] public void ViewModelValidator_AttemptToPassOldPaths(string path) { var testViewModel = new TestViewModel() { Context = new DotvvmRequestContext(null, DotvvmTestHelper.CreateConfiguration(), null) }; var validator = CreateValidator(); var expander = CreateErrorPathExpander(); var context = testViewModel.Context; var modelState = context.ModelState; var validationTarget = testViewModel; modelState.ValidationTarget = validationTarget; context.AddRawModelError(path, "Invalid error path"); var errors = validator.ValidateViewModel(validationTarget).OrderBy(n => n.PropertyPath); modelState.ErrorsInternal.AddRange(errors); expander.Expand(modelState, testViewModel); } public class TestViewModel : DotvvmViewModelBase { [Required] public string Text { get; set; } public List<TestViewModel2> Children { get; set; } public TestViewModel2 Child { get; set; } } public class TestViewModel2 { [Required] public int? Id { get; set; } [RegularExpression("^[0-9]{3}$")] public string Code { get; set; } } public class TestViewModel3 { [EmailAddress] public string Email { get; set; } } public class TestViewModel4 { public TestViewModel4Child Child { get; set; } } public class TestViewModel4Child { public bool IsChecked { get; set; } [ConditionalRequiredValue] public string ConditionalRequired { get; set; } } public class ConditionalRequiredValueAttribute : ValidationAttribute { public override bool RequiresValidationContext => true; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var entity = (TestViewModel4Child)validationContext.ObjectInstance; if (entity.IsChecked && string.IsNullOrEmpty(entity.ConditionalRequired)) { return new ValidationResult("Value is required when the field is checked!", new[] { validationContext.MemberName }); } return base.IsValid(value, validationContext); } } public class TestViewModel5 { public TestViewModel5Child Child { get; set; } } public class TestViewModel5Child : IValidatableObject { public bool IsChecked { get; set; } public string ConditionalRequired { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (IsChecked && string.IsNullOrEmpty(ConditionalRequired)) { yield return new ValidationResult("Value is required when the field is checked!", new[] { nameof(ConditionalRequired) }); } } } public class TestViewModel6 { public List<TestViewModel5Child> Children { get; set; } } public class TestViewModel7 : IValidatableObject { public bool IsChecked { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!IsChecked) { yield return ValidationErrorFactory.CreateValidationResult<TestViewModel7>(validationContext, "Value is required when the field is checked!", vm => vm.IsChecked); } } } } }
using System; using System.IO; using System.Net; using System.Web; using System.Collections.Generic; using ServiceStack.Common.Web; using ServiceStack.Logging; using ServiceStack.MiniProfiler; using ServiceStack.Service; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.ServiceModel; using ServiceStack.Text; namespace ServiceStack.WebHost.Endpoints.Extensions { public static class HttpResponseExtensions { private static readonly ILog Log = LogManager.GetLogger(typeof(HttpResponseExtensions)); public static bool WriteToOutputStream(IHttpResponse response, object result, byte[] bodyPrefix, byte[] bodySuffix) { var partialResult = result as IPartialWriter; if (EndpointHost.Config.AllowPartialResponses && partialResult != null && partialResult.IsPartialRequest) { partialResult.WritePartialTo(response); return true; } var streamWriter = result as IStreamWriter; if (streamWriter != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); streamWriter.WriteTo(response.OutputStream); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } var stream = result as Stream; if (stream != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); stream.WriteTo(response.OutputStream); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } var bytes = result as byte[]; if (bytes != null) { response.ContentType = ContentType.Binary; if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); response.OutputStream.Write(bytes, 0, bytes.Length); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } return false; } public static bool WriteToResponse(this IHttpResponse httpRes, object result, string contentType) { var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(contentType); return httpRes.WriteToResponse(result, serializer, new SerializationContext(contentType)); } public static bool WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result) { return WriteToResponse(httpRes, httpReq, result, null, null); } public static bool WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result, byte[] bodyPrefix, byte[] bodySuffix) { if (result == null) { httpRes.EndRequestWithNoContent(); return true; } var serializationContext = new HttpRequestContext(httpReq, httpRes, result); var httpResult = result as IHttpResult; if (httpResult != null) { if (httpResult.ResponseFilter == null) { httpResult.ResponseFilter = EndpointHost.AppHost.ContentTypeFilters; } httpResult.RequestContext = serializationContext; serializationContext.ResponseContentType = httpResult.ContentType ?? httpReq.ResponseContentType; var httpResSerializer = httpResult.ResponseFilter.GetResponseSerializer(serializationContext.ResponseContentType); return httpRes.WriteToResponse(httpResult, httpResSerializer, serializationContext, bodyPrefix, bodySuffix); } var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(httpReq.ResponseContentType); return httpRes.WriteToResponse(result, serializer, serializationContext, bodyPrefix, bodySuffix); } public static bool WriteToResponse(this IHttpResponse httpRes, object result, ResponseSerializerDelegate serializer, IRequestContext serializationContext) { return httpRes.WriteToResponse(result, serializer, serializationContext, null, null); } /// <summary> /// Writes to response. /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers. /// </summary> /// <param name="response">The response.</param> /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param> /// <param name="defaultAction">The default action.</param> /// <param name="serializerCtx">The serialization context.</param> /// <param name="bodyPrefix">Add prefix to response body if any</param> /// <param name="bodySuffix">Add suffix to response body if any</param> /// <returns></returns> public static bool WriteToResponse(this IHttpResponse response, object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, byte[] bodyPrefix, byte[] bodySuffix) { using (Profiler.Current.Step("Writing to Response")) { var defaultContentType = serializerCtx.ResponseContentType; try { if (result == null) { response.EndRequestWithNoContent(); return true; } ApplyGlobalResponseHeaders(response); var httpResult = result as IHttpResult; if (httpResult != null) { if (httpResult.RequestContext == null) { httpResult.RequestContext = serializerCtx; } var httpError = httpResult as IHttpError; if (httpError != null) { if (response.HandleCustomErrorHandler(serializerCtx.Get<IHttpRequest>(), defaultContentType, httpError.Status, httpError.ToErrorResponse())) { return true; } } response.StatusCode = httpResult.Status; response.StatusDescription = httpResult.StatusDescription ?? httpResult.StatusCode.ToString(); if (string.IsNullOrEmpty(httpResult.ContentType)) { httpResult.ContentType = defaultContentType; } response.ContentType = httpResult.ContentType; } /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */ var responseOptions = result as IHasOptions; if (responseOptions != null) { //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction) const string reservedOptions = "."; foreach (var responseHeaders in responseOptions.Options) { if (responseHeaders.Key.Contains(reservedOptions)) continue; Log.DebugFormat("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value); response.AddHeader(responseHeaders.Key, responseHeaders.Value); } } var disposableResult = result as IDisposable; if (WriteToOutputStream(response, result, bodyPrefix, bodySuffix)) { response.Flush(); //required for Compression if (disposableResult != null) disposableResult.Dispose(); return true; } if (httpResult != null) { result = httpResult.Response; } //ContentType='text/html' is the default for a HttpResponse //Do not override if another has been set if (response.ContentType == null || response.ContentType == ContentType.Html) { response.ContentType = defaultContentType; } if (bodyPrefix != null && response.ContentType.IndexOf(ContentType.Json, StringComparison.InvariantCultureIgnoreCase) >= 0) { response.ContentType = ContentType.JavaScript; } if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType)) { response.ContentType += ContentType.Utf8Suffix; } var responseText = result as string; if (responseText != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); WriteTextToResponse(response, responseText, defaultContentType); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } if (defaultAction == null) { throw new ArgumentNullException("defaultAction", String.Format( "As result '{0}' is not a supported responseType, a defaultAction must be supplied", (result != null ? result.GetType().Name : ""))); } if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); if (result != null) defaultAction(serializerCtx, result, response); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); if (disposableResult != null) disposableResult.Dispose(); return false; } catch (Exception originalEx) { //TM: It would be good to handle 'remote end dropped connection' problems here. Arguably they should at least be suppressible via configuration //DB: Using standard ServiceStack configuration method if (!EndpointHost.Config.WriteErrorsToResponse) throw; var errorMessage = String.Format( "Error occured while Processing Request: [{0}] {1}", originalEx.GetType().Name, originalEx.Message); Log.Error(errorMessage, originalEx); var operationName = result != null ? result.GetType().Name.Replace("Response", "") : "OperationName"; try { if (!response.IsClosed) { response.WriteErrorToResponse( serializerCtx.Get<IHttpRequest>(), defaultContentType, operationName, errorMessage, originalEx, (int)HttpStatusCode.InternalServerError); } } catch (Exception writeErrorEx) { //Exception in writing to response should not hide the original exception Log.Info("Failed to write error to response: {0}", writeErrorEx); throw originalEx; } return true; } finally { response.EndRequest(skipHeaders: true); } } } public static void WriteTextToResponse(this IHttpResponse response, string text, string defaultContentType) { try { //ContentType='text/html' is the default for a HttpResponse //Do not override if another has been set if (response.ContentType == null || response.ContentType == ContentType.Html) { response.ContentType = defaultContentType; } response.Write(text); } catch (Exception ex) { Log.Error("Could not WriteTextToResponse: " + ex.Message, ex); throw; } } public static void WriteError(this IHttpResponse httpRes, IHttpRequest httpReq, object dto, string errorMessage) { httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, dto.GetType().Name, errorMessage, null, (int)HttpStatusCode.InternalServerError); } public static void WriteErrorToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, string contentType, string operationName, string errorMessage, Exception ex, int statusCode) { var errorDto = ex.ToErrorResponse(); if (HandleCustomErrorHandler(httpRes, httpReq, contentType, statusCode, errorDto)) return; if (httpRes.ContentType == null || httpRes.ContentType == ContentType.Html) { httpRes.ContentType = contentType; } if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(contentType)) { httpRes.ContentType += ContentType.Utf8Suffix; } httpRes.StatusCode = statusCode; var serializationCtx = new SerializationContext(contentType); var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(contentType); if (serializer != null) { serializer(serializationCtx, errorDto, httpRes); } httpRes.EndHttpHandlerRequest(skipHeaders: true); } private static bool HandleCustomErrorHandler(this IHttpResponse httpRes, IHttpRequest httpReq, string contentType, int statusCode, object errorDto) { if (httpReq != null && ContentType.Html.MatchesContentType(contentType)) { var errorHandler = EndpointHost.Config.GetCustomErrorHandler(statusCode); if (errorHandler != null) { httpReq.Items["Model"] = errorDto; errorHandler.ProcessRequest(httpReq, httpRes, httpReq.OperationName); return true; } } return false; } private static ErrorResponse ToErrorResponse(this Exception ex) { List<ResponseError> errors = null; // For some exception types, we'll need to extract additional information in debug mode // (for example, so people can fix errors in their pages). if(EndpointHost.DebugMode) { var compileEx = ex as HttpCompileException; if (compileEx != null && compileEx.Results.Errors.HasErrors) { errors = new List<ResponseError>(); foreach (var err in compileEx.Results.Errors) { errors.Add(new ResponseError { Message = err.ToString() }); } } } var dto = new ErrorResponse { ResponseStatus = new ResponseStatus { ErrorCode = ex.ToErrorCode(), Message = ex.Message, StackTrace = EndpointHost.DebugMode ? ex.StackTrace : null, Errors = errors } }; return dto; } public static void ApplyGlobalResponseHeaders(this HttpListenerResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } public static void ApplyGlobalResponseHeaders(this HttpResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } public static void ApplyGlobalResponseHeaders(this IHttpResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } [Obsolete("Use EndRequest extension method")] public static void EndServiceStackRequest(this HttpResponse httpRes, bool skipHeaders = false) { httpRes.EndRequest(skipHeaders); } [Obsolete("Use EndRequest extension method")] public static void EndServiceStackRequest(this IHttpResponse httpRes, bool skipHeaders = false) { httpRes.EndRequest(skipHeaders); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace SIL.Windows.Forms.Widgets.Flying { public class CubicBezierCurve { private PointF _origin; // Polynomial Coefficients private PointF _A; private PointF _B; private PointF _C; public CubicBezierCurve(PointF origin, PointF control1, PointF control2, PointF end) { CalculatePolynomialCoefficients(origin, control1, control2, end); _origin = origin; } private void CalculatePolynomialCoefficients(PointF origin, PointF control1, PointF control2, PointF end) { _C.X = 3.0f * (control1.X - origin.X); _B.X = 3.0f * (control2.X - control1.X) - _C.X; _A.X = end.X - origin.X - _C.X - _B.X; _C.Y = 3.0f * (control1.Y - origin.Y); _B.Y = 3.0f * (control2.Y - control1.Y) - _C.Y; _A.Y = end.Y - origin.Y - _C.Y - _B.Y; } /// <summary> /// Get Point on curve at parameter t /// </summary> /// <param name="t">the interval (varies between 0 and 1)</param> /// <returns></returns> private PointF GetPointFromInterval(float t) { float t_t = t * t; // interval squarred float t_t_t = t_t * t; PointF result = new PointF(); result.X = ((_A.X * t_t_t) + (_B.X * t_t) + (_C.X * t) + _origin.X); result.Y = ((_A.Y * t_t_t) + (_B.Y * t_t) + (_C.Y * t) + _origin.Y); return result; } /// <summary> /// Given a DistanceRatio (ArcLength to CurveLength) gives us the /// X,Y coordinates of the arc with that length /// </summary> public PointF GetPointOnCurve(float distanceRatio) { if (distanceRatio < 0 || distanceRatio > 1) { throw new ArgumentOutOfRangeException("distanceRatio", distanceRatio, "distanceRatio is a ratio and so must be between 0 and 1"); } return GetPointFromInterval(distanceRatio); } } public class Animator { public class AnimatorEventArgs: EventArgs { private readonly PointF _point; public AnimatorEventArgs(PointF point) { _point = point; } public PointF Point { get { return _point; } } } /// <summary> /// Converts a ratio of time to a ratio of distance /// </summary> /// <param name="time">the ratio of time that has past /// to the total time (varies uniformly between 0 and 1)</param> /// <returns>the ratio of the distance traveled to the total /// distance (varies between 0 and 1</returns> public delegate float Speed(float time); /// <summary> /// Gets the proportion into space at which a given proportion of /// the distance has been traveled along a path from the origin /// </summary> /// <remarks>The space is defined by a start point with /// coordinates 0,0 and an end point with coordinates 1,1</remarks> /// <param name="distance">the proportion of the distance traveled /// to the total distance (varies between 0 and 1</param> /// <returns>The proportional point into space at which /// the distance has been traveled</returns> public delegate PointF PointFromDistance(float distance); public delegate void AnimateEventDelegate(object sender, AnimatorEventArgs e); public event AnimateEventDelegate Animate = delegate { }; public event EventHandler Finished = delegate { }; private int _duration; private Speed _speedFunction; private PointFromDistance _pointFromDistanceFunction; private int _elapsedTime; private DateTime _lastMeasuredTime; private readonly Timer _timer; #region YAGNI private readonly float _repeatCount; // greater than 0 or infinite #endregion public Animator() { Duration = 500; _repeatCount = 1; _speedFunction = SpeedFunctions.LinearSpeed; _pointFromDistanceFunction = PointFromDistanceFunctions.LinearPointFromDistance; _elapsedTime = 0; _timer = new Timer(); _timer.Tick += Tick; } private void Tick(object sender, EventArgs e) { DateTime now = DateTime.Now; _elapsedTime += now.Subtract(_lastMeasuredTime).Milliseconds; _lastMeasuredTime = now; if (_elapsedTime > Duration * _repeatCount) { Stop(); Finished(this, new EventArgs()); } OnAnimate(); } private void OnAnimate() { //convert time to distance int elapsedTime; Math.DivRem(_elapsedTime, Duration, out elapsedTime); PointF pointF = PointFromDistanceFunction(SpeedFunction(elapsedTime / (float) Duration)); Animate(this, new AnimatorEventArgs(pointF)); } /// <summary> /// Starts the timer from the place it last was stopped /// </summary> public void Start() { _lastMeasuredTime = DateTime.Now; _timer.Start(); } /// <summary> /// Stops the timer (effectively a pause until Reset is called) /// </summary> public void Stop() { _timer.Stop(); } /// <summary> /// Resets the timer to time 0 /// </summary> public void Reset() { _elapsedTime = 0; } /// <summary> /// Duration in Miliseconds /// </summary> /// <exception cref="ArgumentOutOfRangeException">When negative value.</exception> public int Duration { get { return _duration; } set { if (value < 0) { throw new ArgumentOutOfRangeException(); } _duration = value; } } /// <summary> /// Determines the rate at which the annimation travels along the curve. /// </summary> public Speed SpeedFunction { get { return _speedFunction; } set { _speedFunction = value; } } public PointFromDistance PointFromDistanceFunction { get { return _pointFromDistanceFunction; } set { _pointFromDistanceFunction = value; } } /// <summary> /// The number of frames per second /// </summary> public float FrameRate { get { return 1000 / _timer.Interval; } set { if (value > 1000 || value <= 0) { throw new ArgumentOutOfRangeException("value", value, "FrameRate must be between 1 and 1000, inclusive"); } _timer.Interval = (int) (1000f / value); } } /// <summary> /// The duration of a single frame in milliseconds /// </summary> /// <exception cref="ArgumentOutOfRangeException">When negative.</exception> public int FrameDuration { get { return _timer.Interval; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(); } _timer.Interval = value; } } public class SpeedFunctions { public static float LinearSpeed(float t) { return t; } /// <summary> /// if input t varies uniformly between 0 and 1, /// output t' starts at 0 slowly increasing, gaining speed until /// the middle values and then decelerating at it approaches 1. /// </summary> /// <param name="t">varies uniformly between 0 and 1</param> /// <returns>a number which varies between 0 and 1</returns> public static float SinSpeed(float t) { return (float) (Math.Sin(t * Math.PI - Math.PI / 2f) + 1f) / 2f; } } public class PointFromDistanceFunctions { public static PointF LinearPointFromDistance(float distance) { return new PointF(distance, distance); } } public static int GetValue(float proportion, int from, int to) { return (int) ((to - from) * proportion) + from; } public static T GetValue<T>(float proportion, IList<T> list) { if (list == null) { throw new ArgumentNullException("list"); } if (list.Count < 1) { throw new ArgumentOutOfRangeException("list", list, "list is empty"); } int index = (int) (list.Count * proportion); return list[index]; } } }
using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Linq; using System.Net; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using Agent.Sdk; namespace Microsoft.VisualStudio.Services.Agent { [ServiceLocator(Default = typeof(VstsAgentWebProxy))] public interface IVstsAgentWebProxy : IAgentService { string ProxyAddress { get; } string ProxyUsername { get; } string ProxyPassword { get; } List<string> ProxyBypassList { get; } IWebProxy WebProxy { get; } } public class VstsAgentWebProxy : AgentService, IVstsAgentWebProxy { private readonly List<Regex> _regExBypassList = new List<Regex>(); private readonly List<string> _bypassList = new List<string>(); private AgentWebProxy _agentWebProxy = new AgentWebProxy(); public string ProxyAddress { get; private set; } public string ProxyUsername { get; private set; } public string ProxyPassword { get; private set; } public List<string> ProxyBypassList => _bypassList; public IWebProxy WebProxy => _agentWebProxy; public override void Initialize(IHostContext context) { base.Initialize(context); LoadProxySetting(); } // This should only be called from config public void SetupProxy(string proxyAddress, string proxyUsername, string proxyPassword) { ArgUtil.NotNullOrEmpty(proxyAddress, nameof(proxyAddress)); Trace.Info($"Update proxy setting from '{ProxyAddress ?? string.Empty}' to'{proxyAddress}'"); ProxyAddress = proxyAddress; ProxyUsername = proxyUsername; ProxyPassword = proxyPassword; if (string.IsNullOrEmpty(ProxyUsername) || string.IsNullOrEmpty(ProxyPassword)) { Trace.Info($"Config proxy use DefaultNetworkCredentials."); } else { Trace.Info($"Config authentication proxy as: {ProxyUsername}."); } _agentWebProxy.Update(ProxyAddress, ProxyUsername, ProxyPassword, ProxyBypassList); } // This should only be called from config public void SaveProxySetting() { if (!string.IsNullOrEmpty(ProxyAddress)) { string proxyConfigFile = HostContext.GetConfigFile(WellKnownConfigFile.Proxy); IOUtil.DeleteFile(proxyConfigFile); Trace.Info($"Store proxy configuration to '{proxyConfigFile}' for proxy '{ProxyAddress}'"); File.WriteAllText(proxyConfigFile, ProxyAddress); File.SetAttributes(proxyConfigFile, File.GetAttributes(proxyConfigFile) | FileAttributes.Hidden); string proxyCredFile = HostContext.GetConfigFile(WellKnownConfigFile.ProxyCredentials); IOUtil.DeleteFile(proxyCredFile); if (!string.IsNullOrEmpty(ProxyUsername) && !string.IsNullOrEmpty(ProxyPassword)) { string lookupKey = Guid.NewGuid().ToString("D").ToUpperInvariant(); Trace.Info($"Store proxy credential lookup key '{lookupKey}' to '{proxyCredFile}'"); File.WriteAllText(proxyCredFile, lookupKey); File.SetAttributes(proxyCredFile, File.GetAttributes(proxyCredFile) | FileAttributes.Hidden); var credStore = HostContext.GetService<IAgentCredentialStore>(); credStore.Write($"VSTS_AGENT_PROXY_{lookupKey}", ProxyUsername, ProxyPassword); } } else { Trace.Info("No proxy configuration exist."); } } // This should only be called from unconfig public void DeleteProxySetting() { string proxyCredFile = HostContext.GetConfigFile(WellKnownConfigFile.ProxyCredentials); if (File.Exists(proxyCredFile)) { Trace.Info("Delete proxy credential from credential store."); string lookupKey = File.ReadAllLines(proxyCredFile).FirstOrDefault(); if (!string.IsNullOrEmpty(lookupKey)) { var credStore = HostContext.GetService<IAgentCredentialStore>(); credStore.Delete($"VSTS_AGENT_PROXY_{lookupKey}"); } Trace.Info($"Delete .proxycredentials file: {proxyCredFile}"); IOUtil.DeleteFile(proxyCredFile); } string proxyBypassFile = HostContext.GetConfigFile(WellKnownConfigFile.ProxyBypass); if (File.Exists(proxyBypassFile)) { Trace.Info($"Delete .proxybypass file: {proxyBypassFile}"); IOUtil.DeleteFile(proxyBypassFile); } string proxyConfigFile = HostContext.GetConfigFile(WellKnownConfigFile.Proxy); Trace.Info($"Delete .proxy file: {proxyConfigFile}"); IOUtil.DeleteFile(proxyConfigFile); } private void LoadProxySetting() { string proxyConfigFile = HostContext.GetConfigFile(WellKnownConfigFile.Proxy); if (File.Exists(proxyConfigFile)) { // we expect the first line of the file is the proxy url Trace.Verbose($"Try read proxy setting from file: {proxyConfigFile}."); ProxyAddress = File.ReadLines(proxyConfigFile).FirstOrDefault() ?? string.Empty; ProxyAddress = ProxyAddress.Trim(); Trace.Verbose($"{ProxyAddress}"); } if (string.IsNullOrEmpty(ProxyAddress)) { Trace.Verbose("Try read proxy setting from environment variable: 'VSTS_HTTP_PROXY'."); ProxyAddress = Environment.GetEnvironmentVariable("VSTS_HTTP_PROXY") ?? string.Empty; ProxyAddress = ProxyAddress.Trim(); Trace.Verbose($"{ProxyAddress}"); } if (!string.IsNullOrEmpty(ProxyAddress) && !Uri.IsWellFormedUriString(ProxyAddress, UriKind.Absolute)) { Trace.Info($"The proxy url is not a well formed absolute uri string: {ProxyAddress}."); ProxyAddress = string.Empty; } if (!string.IsNullOrEmpty(ProxyAddress)) { Trace.Info($"Config proxy at: {ProxyAddress}."); string proxyCredFile = HostContext.GetConfigFile(WellKnownConfigFile.ProxyCredentials); if (File.Exists(proxyCredFile)) { string lookupKey = File.ReadAllLines(proxyCredFile).FirstOrDefault(); if (!string.IsNullOrEmpty(lookupKey)) { var credStore = HostContext.GetService<IAgentCredentialStore>(); var proxyCred = credStore.Read($"VSTS_AGENT_PROXY_{lookupKey}"); ProxyUsername = proxyCred.UserName; ProxyPassword = proxyCred.Password; } } if (string.IsNullOrEmpty(ProxyUsername)) { ProxyUsername = Environment.GetEnvironmentVariable("VSTS_HTTP_PROXY_USERNAME"); } if (string.IsNullOrEmpty(ProxyPassword)) { ProxyPassword = Environment.GetEnvironmentVariable("VSTS_HTTP_PROXY_PASSWORD"); } if (!string.IsNullOrEmpty(ProxyPassword)) { HostContext.SecretMasker.AddValue(ProxyPassword); } if (string.IsNullOrEmpty(ProxyUsername) || string.IsNullOrEmpty(ProxyPassword)) { Trace.Info($"Config proxy use DefaultNetworkCredentials."); } else { Trace.Info($"Config authentication proxy as: {ProxyUsername}."); } string proxyBypassFile = HostContext.GetConfigFile(WellKnownConfigFile.ProxyBypass); if (File.Exists(proxyBypassFile)) { Trace.Verbose($"Try read proxy bypass list from file: {proxyBypassFile}."); foreach (string bypass in File.ReadAllLines(proxyBypassFile)) { if (string.IsNullOrWhiteSpace(bypass)) { continue; } else { Trace.Info($"Bypass proxy for: {bypass}."); ProxyBypassList.Add(bypass.Trim()); } } } _agentWebProxy.Update(ProxyAddress, ProxyUsername, ProxyPassword, ProxyBypassList); } else { Trace.Info($"No proxy setting found."); } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls; using Avalonia.Markup.Xaml.Data; using Avalonia.Markup.Xaml.PortableXaml; using Avalonia.Platform; using Portable.Xaml; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace Avalonia.Markup.Xaml { /// <summary> /// Loads XAML for a avalonia application. /// </summary> public class AvaloniaXamlLoaderPortableXaml { private readonly AvaloniaXamlSchemaContext _context = GetContext(); private static AvaloniaXamlSchemaContext GetContext() { var result = AvaloniaLocator.Current.GetService<AvaloniaXamlSchemaContext>(); if (result == null) { result = AvaloniaXamlSchemaContext.Create(); AvaloniaLocator.CurrentMutable .Bind<AvaloniaXamlSchemaContext>() .ToConstant(result); } return result; } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class. /// </summary> public AvaloniaXamlLoaderPortableXaml() { } /// <summary> /// Loads the XAML into a Avalonia component. /// </summary> /// <param name="obj">The object to load the XAML into.</param> public static void Load(object obj) { Contract.Requires<ArgumentNullException>(obj != null); var loader = new AvaloniaXamlLoader(); loader.Load(obj.GetType(), obj); } /// <summary> /// Loads the XAML for a type. /// </summary> /// <param name="type">The type.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(Type type, object rootInstance = null) { Contract.Requires<ArgumentNullException>(type != null); // HACK: Currently Visual Studio is forcing us to change the extension of xaml files // in certain situations, so we try to load .xaml and if that's not found we try .xaml. // Ideally we'd be able to use .xaml everywhere var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); if (assetLocator == null) { throw new InvalidOperationException( "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?"); } foreach (var uri in GetUrisFor(type)) { if (assetLocator.Exists(uri)) { using (var stream = assetLocator.Open(uri)) { var initialize = rootInstance as ISupportInitialize; initialize?.BeginInit(); try { return Load(stream, rootInstance, uri); } finally { initialize?.EndInit(); } } } } throw new FileNotFoundException("Unable to find view for " + type.FullName); } /// <summary> /// Loads XAML from a URI. /// </summary> /// <param name="uri">The URI of the XAML file.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(Uri uri, Uri baseUri = null, object rootInstance = null) { Contract.Requires<ArgumentNullException>(uri != null); var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); if (assetLocator == null) { throw new InvalidOperationException( "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?"); } using (var stream = assetLocator.Open(uri, baseUri)) { return Load(stream, rootInstance, uri); } } /// <summary> /// Loads XAML from a string. /// </summary> /// <param name="xaml">The string containing the XAML.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(string xaml, object rootInstance = null) { Contract.Requires<ArgumentNullException>(xaml != null); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) { return Load(stream, rootInstance); } } /// <summary> /// Loads XAML from a stream. /// </summary> /// <param name="stream">The stream containing the XAML.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <param name="uri">The URI of the XAML</param> /// <returns>The loaded object.</returns> public object Load(Stream stream, object rootInstance = null, Uri uri = null) { var readerSettings = new XamlXmlReaderSettings() { BaseUri = uri, LocalAssembly = rootInstance?.GetType().GetTypeInfo().Assembly }; var reader = new XamlXmlReader(stream, _context, readerSettings); object result = LoadFromReader( reader, AvaloniaXamlContext.For(readerSettings, rootInstance)); var topLevel = result as TopLevel; if (topLevel != null) { DelayedBinding.ApplyBindings(topLevel); } return result; } internal static object LoadFromReader(XamlReader reader, AvaloniaXamlContext context = null) { var writer = AvaloniaXamlObjectWriter.Create( reader.SchemaContext, context); XamlServices.Transform(reader, writer); writer.ApplyAllDelayedProperties(); return writer.Result; } internal static object LoadFromReader(XamlReader reader) { //return XamlServices.Load(reader); return LoadFromReader(reader, null); } /// <summary> /// Gets the URI for a type. /// </summary> /// <param name="type">The type.</param> /// <returns>The URI.</returns> private static IEnumerable<Uri> GetUrisFor(Type type) { var asm = type.GetTypeInfo().Assembly.GetName().Name; var typeName = type.FullName; yield return new Uri("resm:" + typeName + ".xaml?assembly=" + asm); yield return new Uri("resm:" + typeName + ".paml?assembly=" + asm); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.ComIntegration { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime; class ComCatalogObject { ICatalogObject catalogObject; ICatalogCollection catalogCollection; public ComCatalogObject(ICatalogObject catalogObject, ICatalogCollection catalogCollection) { this.catalogObject = catalogObject; this.catalogCollection = catalogCollection; } public object GetValue(string key) { return this.catalogObject.GetValue(key); } public string Name { get { return (string)(this.catalogObject.Name()); } } public ComCatalogCollection GetCollection(string collectionName) { ICatalogCollection collection; collection = (ICatalogCollection)this.catalogCollection.GetCollection( collectionName, this.catalogObject.Key()); collection.Populate(); return new ComCatalogCollection(collection); } } class ComCatalogCollection { ICatalogCollection catalogCollection; public ComCatalogCollection(ICatalogCollection catalogCollection) { this.catalogCollection = catalogCollection; } public int Count { get { return this.catalogCollection.Count(); } } // (Not a property because I make a new object every time.) public ComCatalogObject Item(int index) { ICatalogObject catalogObject; catalogObject = (ICatalogObject)this.catalogCollection.Item(index); return new ComCatalogObject(catalogObject, this.catalogCollection); } public Enumerator GetEnumerator() { return new Enumerator(this); } // This is kind of a half-baked IEnumerator implementation. It // lets you use foreach(), but don't expect fancy things like // InvalidOperationExceptions and such. // public struct Enumerator { ComCatalogCollection collection; ComCatalogObject current; int count; public Enumerator(ComCatalogCollection collection) { this.collection = collection; this.current = null; this.count = -1; } public ComCatalogObject Current { get { return this.current; } } public bool MoveNext() { this.count++; if (this.count >= collection.Count) return false; this.current = this.collection.Item(this.count); return true; } public void Reset() { this.count = -1; } } } internal static class CatalogUtil { internal static string[] GetRoleMembers( ComCatalogObject application, ComCatalogCollection rolesCollection) { ComCatalogCollection applicationRoles; applicationRoles = application.GetCollection("Roles"); // This is inefficient. If it turns into a // performance problem, then we'll need to put a cache in // somewhere. // List<string> roleMembers = new List<string>(); foreach (ComCatalogObject role in rolesCollection) { string roleName = (string)role.GetValue("Name"); // Find the role in the app roles list. // foreach (ComCatalogObject appRole in applicationRoles) { string appRoleName = (string)appRole.GetValue("Name"); if (roleName == appRoleName) { // Found it, put all of the user names into // the role members list. // ComCatalogCollection users; users = appRole.GetCollection("UsersInRole"); foreach (ComCatalogObject userObject in users) { string user = (string)userObject.GetValue("User"); roleMembers.Add(user); } break; } } } return roleMembers.ToArray(); } internal static ComCatalogObject FindApplication(Guid applicationId) { ICatalog2 catalog = (ICatalog2)(new xCatalog()); ICatalogObject appObject = null; ICatalogCollection partitionCollection = null; try { partitionCollection = (ICatalogCollection)catalog.GetCollection( "Partitions"); partitionCollection.Populate(); } catch (COMException comException) { if (comException.ErrorCode != HR.COMADMIN_E_PARTITIONS_DISABLED) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(comException); } if (partitionCollection != null) { for (int i = 0; i < partitionCollection.Count(); i++) { ICatalogObject partition; partition = (ICatalogObject)partitionCollection.Item(i); ICatalogCollection appCollection; appCollection = (ICatalogCollection)partitionCollection.GetCollection( "Applications", partition.Key()); appCollection.Populate(); appObject = FindApplication(appCollection, applicationId); if (appObject != null) return new ComCatalogObject(appObject, appCollection); } } else { ICatalogCollection appCollection; appCollection = (ICatalogCollection)catalog.GetCollection( "Applications"); appCollection.Populate(); appObject = FindApplication(appCollection, applicationId); if (appObject != null) return new ComCatalogObject(appObject, appCollection); } return null; } static ICatalogObject FindApplication(ICatalogCollection appCollection, Guid applicationId) { ICatalogObject appObject = null; for (int i = 0; i < appCollection.Count(); i++) { appObject = (ICatalogObject)appCollection.Item(i); Guid id = Fx.CreateGuid((string)appObject.GetValue("ID")); if (id == applicationId) return appObject; } return null; } } }
// 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; namespace System.Linq.Expressions.Tests { public class TypeEqual : TypeBinaryTests { [Fact] public void NullExpression() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.TypeEqual(null, typeof(int))); } [Fact] public void NullType() { Expression exp = Expression.Constant(0); AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.TypeEqual(exp, null)); } [Fact] public void TypeByRef() { Expression exp = Expression.Constant(0); Type byRef = typeof(int).MakeByRefType(); AssertExtensions.Throws<ArgumentException>("type", () => Expression.TypeEqual(exp, byRef)); } [Theory, ClassData(typeof(CompilationTypes))] public void TypePointer(bool useInterpreter) { Expression exp = Expression.Constant(0); Type pointer = typeof(int*); var test = Expression.TypeEqual(exp, pointer); var lambda = Expression.Lambda<Func<bool>>(test); var func = lambda.Compile(useInterpreter); Assert.False(func()); } [Fact] public void UnreadableExpression() { Expression exp = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.TypeEqual(exp, typeof(int))); } [Fact] public void CannotReduce() { Expression exp = Expression.TypeIs(Expression.Constant(0), typeof(int)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Theory] [MemberData(nameof(ExpressionAndTypeCombinations))] public void TypePropertyMatches(Expression expression, Type type) { Assert.Equal(type, Expression.TypeEqual(expression, type).TypeOperand); } [Theory] [MemberData(nameof(ExpressionAndTypeCombinations))] public void TypeIsBoolean(Expression expression, Type type) { Assert.Equal(typeof(bool), Expression.TypeEqual(expression, type).Type); } [Theory] [MemberData(nameof(ExpressionAndTypeCombinations))] public void NodeType(Expression expression, Type type) { Assert.Equal(ExpressionType.TypeEqual, Expression.TypeEqual(expression, type).NodeType); } [Theory] [MemberData(nameof(ExpressionAndTypeCombinations))] public void ExpressionIsThatPassed(Expression expression, Type type) { Assert.Same(expression, Expression.TypeEqual(expression, type).Expression); } [Theory] [PerCompilationType(nameof(ExpressionAndTypeCombinations))] public void ExpressionEvaluation(Expression expression, Type type, bool useInterpreter) { bool expected; if (type == typeof(void)) expected = expression.Type == typeof(void); else if (expression.Type == typeof(void)) expected = false; else { Type nonNullable = type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) ? type.GetGenericArguments()[0] : type; object value = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile()(); expected = value != null && value.GetType() == nonNullable; } Assert.Equal(expected, Expression.Lambda<Func<bool>>(Expression.TypeEqual(expression, type)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ExpressionAndTypeCombinations))] public void ExpressionEvaluationWithParameter(Expression expression, Type type, bool useInterpreter) { if (expression.Type == typeof(void)) return; // Can't have void parameter. bool expected; if (type == typeof(void)) expected = false; else { Type nonNullable = type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) ? type.GetGenericArguments()[0] : type; object value = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile()(); expected = value != null && value.GetType() == nonNullable; } ParameterExpression param = Expression.Parameter(expression.Type); Func<bool> func = Expression.Lambda<Func<bool>>( Expression.Block( new[] { param }, Expression.Assign(param, expression), Expression.TypeEqual(param, type) ) ).Compile(useInterpreter); Assert.Equal(expected, func()); } [Fact] public void UpdateSameReturnsSame() { Expression expression = Expression.Constant(0); TypeBinaryExpression typeExp = Expression.TypeEqual(expression, typeof(int)); Assert.Same(typeExp, typeExp.Update(expression)); Assert.Same(typeExp, NoOpVisitor.Instance.Visit(typeExp)); } [Fact] public void UpdateNotSameReturnsNotSame() { Expression expression = Expression.Constant(0); TypeBinaryExpression typeExp = Expression.TypeEqual(expression, typeof(int)); Assert.NotSame(typeExp, typeExp.Update(Expression.Constant(0))); } [Fact] public void VisitHitsVisitTypeBinary() { TypeBinaryExpression expression = Expression.TypeEqual(Expression.Constant(0), typeof(int)); TypeBinaryVisitCheckingVisitor visitor = new TypeBinaryVisitCheckingVisitor(); visitor.Visit(expression); Assert.Same(expression, visitor.LastTypeBinaryVisited); } [Theory] [ClassData(typeof(CompilationTypes))] public void VariantDelegateArgument(bool useInterpreter) { Action<object> ao = x => { }; Action<string> a = x => { }; Action<string> b = ao; ParameterExpression param = Expression.Parameter(typeof(Action<string>)); Func<Action<string>, bool> isActStr = Expression.Lambda<Func<Action<string>, bool>>( Expression.TypeEqual(param, typeof(Action<string>)), param ).Compile(useInterpreter); Assert.False(isActStr(ao)); Assert.True(isActStr(a)); Assert.False(isActStr(b)); } [Theory, PerCompilationType(nameof(TypeArguments))] public void TypeEqualConstant(Type type, bool useInterpreter) { Func<bool> isNullOfType = Expression.Lambda<Func<bool>>( Expression.TypeEqual(Expression.Constant(null), type) ).Compile(useInterpreter); Assert.False(isNullOfType()); isNullOfType = Expression.Lambda<Func<bool>>( Expression.TypeEqual(Expression.Constant(null, typeof(string)), type) ).Compile(useInterpreter); Assert.False(isNullOfType()); } [Fact] public void ToStringTest() { TypeBinaryExpression e = Expression.TypeEqual(Expression.Parameter(typeof(string), "s"), typeof(string)); Assert.Equal("(s TypeEqual String)", e.ToString()); } } }
namespace Maui.Tools.Studio.WebSpy { partial class BrowserForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if ( disposing && (components != null) ) { // TODO: does this dispose the browser? components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.myUrlTxt = new System.Windows.Forms.TextBox(); this.myBrowser = new System.Windows.Forms.WebBrowser(); this.myGo = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.myReset = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.myValue = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.mySkipColumns = new System.Windows.Forms.TextBox(); this.mySkipRows = new System.Windows.Forms.TextBox(); this.mySeriesName = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.myColumnHeader = new System.Windows.Forms.TextBox(); this.myRowHeader = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.myDimension = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.mySearchPath = new System.Windows.Forms.Button(); this.myPath = new System.Windows.Forms.TextBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.myEditCapture = new System.Windows.Forms.Button(); this.myReplay = new System.Windows.Forms.Button(); this.myNavUrls = new System.Windows.Forms.TextBox(); this.myCapture = new System.Windows.Forms.Button(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.myValidateDatumProvidersMenu = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.panel1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // myUrlTxt // this.myUrlTxt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.myUrlTxt.Location = new System.Drawing.Point(5, 27); this.myUrlTxt.Name = "myUrlTxt"; this.myUrlTxt.Size = new System.Drawing.Size(694, 20); this.myUrlTxt.TabIndex = 0; // // myBrowser // this.myBrowser.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.myBrowser.IsWebBrowserContextMenuEnabled = false; this.myBrowser.Location = new System.Drawing.Point(5, 54); this.myBrowser.MinimumSize = new System.Drawing.Size(20, 20); this.myBrowser.Name = "myBrowser"; this.myBrowser.Size = new System.Drawing.Size(775, 364); this.myBrowser.TabIndex = 2; // // myGo // this.myGo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.myGo.Location = new System.Drawing.Point(705, 25); this.myGo.Name = "myGo"; this.myGo.Size = new System.Drawing.Size(75, 23); this.myGo.TabIndex = 1; this.myGo.Text = "&Go"; this.myGo.UseVisualStyleBackColor = true; this.myGo.Click += new System.EventHandler(this.myGo_Click); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.tabControl1); this.panel1.Location = new System.Drawing.Point(5, 424); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(775, 135); this.panel1.TabIndex = 4; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(775, 135); this.tabControl1.TabIndex = 22; // // tabPage1 // this.tabPage1.Controls.Add(this.myReset); this.tabPage1.Controls.Add(this.label8); this.tabPage1.Controls.Add(this.myValue); this.tabPage1.Controls.Add(this.label7); this.tabPage1.Controls.Add(this.mySkipColumns); this.tabPage1.Controls.Add(this.mySkipRows); this.tabPage1.Controls.Add(this.mySeriesName); this.tabPage1.Controls.Add(this.label6); this.tabPage1.Controls.Add(this.label5); this.tabPage1.Controls.Add(this.label4); this.tabPage1.Controls.Add(this.label3); this.tabPage1.Controls.Add(this.myColumnHeader); this.tabPage1.Controls.Add(this.myRowHeader); this.tabPage1.Controls.Add(this.label2); this.tabPage1.Controls.Add(this.myDimension); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Controls.Add(this.mySearchPath); this.tabPage1.Controls.Add(this.myPath); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(767, 109); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Data description"; this.tabPage1.UseVisualStyleBackColor = true; // // myReset // this.myReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.myReset.Location = new System.Drawing.Point(607, 83); this.myReset.Name = "myReset"; this.myReset.Size = new System.Drawing.Size(75, 23); this.myReset.TabIndex = 39; this.myReset.Text = "Reset"; this.myReset.UseVisualStyleBackColor = true; this.myReset.Click += new System.EventHandler(this.myReset_Click); // // label8 // this.label8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(626, 9); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(19, 13); this.label8.TabIndex = 38; this.label8.Text = "=>"; // // myValue // this.myValue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.myValue.Location = new System.Drawing.Point(651, 6); this.myValue.Name = "myValue"; this.myValue.Size = new System.Drawing.Size(112, 20); this.myValue.TabIndex = 37; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(0, 11); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(73, 13); this.label7.TabIndex = 36; this.label7.Text = "Selected path"; // // mySkipColumns // this.mySkipColumns.Location = new System.Drawing.Point(349, 85); this.mySkipColumns.Name = "mySkipColumns"; this.mySkipColumns.Size = new System.Drawing.Size(62, 20); this.mySkipColumns.TabIndex = 35; this.mySkipColumns.TextChanged += new System.EventHandler(this.mySkipColumns_TextChanged); // // mySkipRows // this.mySkipRows.Location = new System.Drawing.Point(349, 59); this.mySkipRows.Name = "mySkipRows"; this.mySkipRows.Size = new System.Drawing.Size(62, 20); this.mySkipRows.TabIndex = 34; this.mySkipRows.TextChanged += new System.EventHandler(this.mySkipRows_TextChanged); // // mySeriesName // this.mySeriesName.Location = new System.Drawing.Point(349, 32); this.mySeriesName.Name = "mySeriesName"; this.mySeriesName.Size = new System.Drawing.Size(139, 20); this.mySeriesName.TabIndex = 33; this.mySeriesName.TextChanged += new System.EventHandler(this.mySeriesName_TextChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(235, 88); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(70, 13); this.label6.TabIndex = 32; this.label6.Text = "Skip columns"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(235, 35); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(108, 13); this.label5.TabIndex = 31; this.label5.Text = "Series name contains"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(235, 62); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(53, 13); this.label4.TabIndex = 30; this.label4.Text = "Skip rows"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(0, 88); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(98, 13); this.label3.TabIndex = 29; this.label3.Text = "Column header row"; // // myColumnHeader // this.myColumnHeader.Location = new System.Drawing.Point(108, 85); this.myColumnHeader.Name = "myColumnHeader"; this.myColumnHeader.Size = new System.Drawing.Size(62, 20); this.myColumnHeader.TabIndex = 28; this.myColumnHeader.TextChanged += new System.EventHandler(this.myColumnHeader_TextChanged); // // myRowHeader // this.myRowHeader.Location = new System.Drawing.Point(108, 59); this.myRowHeader.Name = "myRowHeader"; this.myRowHeader.Size = new System.Drawing.Size(62, 20); this.myRowHeader.TabIndex = 27; this.myRowHeader.TextChanged += new System.EventHandler(this.myRowHeader_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(0, 62); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(102, 13); this.label2.TabIndex = 26; this.label2.Text = "Row header column"; // // myDimension // this.myDimension.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.myDimension.FormattingEnabled = true; this.myDimension.Items.AddRange(new object[] { "None", "Row", "Column"}); this.myDimension.Location = new System.Drawing.Point(108, 32); this.myDimension.Name = "myDimension"; this.myDimension.Size = new System.Drawing.Size(115, 21); this.myDimension.TabIndex = 25; this.myDimension.SelectedIndexChanged += new System.EventHandler(this.myDimension_SelectedIndexChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(0, 35); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 13); this.label1.TabIndex = 24; this.label1.Text = "Dimension"; // // mySearchPath // this.mySearchPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.mySearchPath.Location = new System.Drawing.Point(688, 83); this.mySearchPath.Name = "mySearchPath"; this.mySearchPath.Size = new System.Drawing.Size(75, 23); this.mySearchPath.TabIndex = 23; this.mySearchPath.Text = "Search Path"; this.mySearchPath.UseVisualStyleBackColor = true; this.mySearchPath.Click += new System.EventHandler(this.mySearchPath_Click); // // myPath // this.myPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.myPath.Location = new System.Drawing.Point(108, 6); this.myPath.Name = "myPath"; this.myPath.Size = new System.Drawing.Size(512, 20); this.myPath.TabIndex = 22; // // tabPage2 // this.tabPage2.Controls.Add(this.myEditCapture); this.tabPage2.Controls.Add(this.myReplay); this.tabPage2.Controls.Add(this.myNavUrls); this.tabPage2.Controls.Add(this.myCapture); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(767, 109); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Navigation"; this.tabPage2.UseVisualStyleBackColor = true; // // myEditCapture // this.myEditCapture.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.myEditCapture.Location = new System.Drawing.Point(305, 80); this.myEditCapture.Name = "myEditCapture"; this.myEditCapture.Size = new System.Drawing.Size(87, 23); this.myEditCapture.TabIndex = 6; this.myEditCapture.Text = "Edit..."; this.myEditCapture.UseVisualStyleBackColor = true; this.myEditCapture.Click += new System.EventHandler(this.myEditCapture_Click); // // myReplay // this.myReplay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.myReplay.Location = new System.Drawing.Point(305, 35); this.myReplay.Name = "myReplay"; this.myReplay.Size = new System.Drawing.Size(87, 23); this.myReplay.TabIndex = 5; this.myReplay.Text = "Replay"; this.myReplay.UseVisualStyleBackColor = true; this.myReplay.Click += new System.EventHandler(this.myReplay_Click); // // myNavUrls // this.myNavUrls.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.myNavUrls.Location = new System.Drawing.Point(0, 6); this.myNavUrls.Multiline = true; this.myNavUrls.Name = "myNavUrls"; this.myNavUrls.Size = new System.Drawing.Size(299, 100); this.myNavUrls.TabIndex = 4; this.myNavUrls.WordWrap = false; // // myCapture // this.myCapture.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.myCapture.Location = new System.Drawing.Point(305, 6); this.myCapture.Name = "myCapture"; this.myCapture.Size = new System.Drawing.Size(87, 23); this.myCapture.TabIndex = 1; this.myCapture.Text = "Start capturing"; this.myCapture.UseVisualStyleBackColor = true; this.myCapture.Click += new System.EventHandler(this.myCapture_Click); // // menuStrip1 // this.menuStrip1.BackColor = System.Drawing.SystemColors.Menu; this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem2}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(784, 24); this.menuStrip1.TabIndex = 5; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem2 // this.toolStripMenuItem2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.myValidateDatumProvidersMenu}); this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(48, 20); this.toolStripMenuItem2.Text = "&Tools"; // // myValidateDatumProvidersMenu // this.myValidateDatumProvidersMenu.Name = "myValidateDatumProvidersMenu"; this.myValidateDatumProvidersMenu.Size = new System.Drawing.Size(211, 22); this.myValidateDatumProvidersMenu.Text = "Validate datum locators ..."; this.myValidateDatumProvidersMenu.Click += new System.EventHandler(this.myValidateDatumLocatorsMenu_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // BrowserForm // this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.Controls.Add(this.panel1); this.Controls.Add(this.myBrowser); this.Controls.Add(this.myGo); this.Controls.Add(this.myUrlTxt); this.Controls.Add(this.menuStrip1); this.MinimumSize = new System.Drawing.Size(784, 562); this.Name = "BrowserForm"; this.Size = new System.Drawing.Size(0, 0); this.panel1.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox myUrlTxt; private System.Windows.Forms.WebBrowser myBrowser; private System.Windows.Forms.Button myGo; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.Button myReset; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox myValue; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox mySkipColumns; private System.Windows.Forms.TextBox mySkipRows; private System.Windows.Forms.TextBox mySeriesName; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox myColumnHeader; private System.Windows.Forms.TextBox myRowHeader; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox myDimension; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button mySearchPath; private System.Windows.Forms.TextBox myPath; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Button myCapture; private System.Windows.Forms.TextBox myNavUrls; private System.Windows.Forms.Button myReplay; private System.Windows.Forms.Button myEditCapture; private System.Windows.Forms.ToolStripMenuItem myValidateDatumProvidersMenu; } }