context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Piranha.Manager.Models; using Piranha.Manager.Services; namespace Piranha.Manager.Controllers { /// <summary> /// Api controller for content management. /// </summary> [Area("Manager")] [Route("manager/api/content")] [Authorize(Policy = Permission.Admin)] [ApiController] [AutoValidateAntiforgeryToken] public class ContentApiController : Controller { private readonly IApi _api; private readonly ContentService _content; private readonly ContentTypeService _contentType; /// <summary> /// Default constructor. /// </summary> public ContentApiController(ContentService content, ContentTypeService contentType, IApi api) { _api = api; _content = content; _contentType = contentType; } /// <summary> /// Gets the currently available block types for the /// specified page type. /// </summary> /// <param name="pageType">The page type id</param> /// <param name="parentType">The optional parent group type</param> /// <returns>The block list model</returns> [Route("blocktypes/page/{pageType}/{parentType?}")] [HttpGet] public BlockListModel GetBlockTypesForPage(string pageType, string parentType = null) { return _contentType.GetPageBlockTypes(pageType, parentType); } /// <summary> /// Gets the currently available block types for the /// specified post type. /// </summary> /// <param name="postType">The post type id</param> /// <param name="parentType">The optional parent group type</param> /// <returns>The block list model</returns> [Route("blocktypes/post/{postType}/{parentType?}")] [HttpGet] public BlockListModel GetBlockTypesForPost(string postType, string parentType = null) { return _contentType.GetPostBlockTypes(postType, parentType); } /// <summary> /// Gets the currently available block types. /// </summary> /// <param name="parentType">The optional parent group type</param> /// <returns>The block list model</returns> [Route("blocktypes/{parentType?}")] [HttpGet] public BlockListModel GetBlockTypes(string parentType = null) { return _contentType.GetBlockTypes(parentType); } /// <summary> /// Creates a new block of the specified type. /// </summary> /// <param name="type">The block type</param> /// <returns>The new block</returns> [Route("block/{type}")] [HttpGet] public async Task<IActionResult> CreateBlockAsync(string type) { var block = await _contentType.CreateBlockAsync(type); if (block != null) { return Ok(block); } return NotFound(); } /// <summary> /// Creates a new region for the specified content type. /// </summary> /// <param name="content">The type of content</param> /// <param name="type">The content type</param> /// <param name="region">The region id</param> /// <returns>The new region model</returns> [Route("region/{content}/{type}/{region}")] [HttpGet] public async Task<IActionResult> CreateRegionAsync(string content, string type, string region) { if (content == "content") { return Ok(await _contentType.CreateContentRegionAsync(type, region)); } else if (content == "page") { return Ok(await _contentType.CreatePageRegionAsync(type, region)); } else if (content == "post") { return Ok(await _contentType.CreatePostRegionAsync(type, region)); } else if (content == "site") { return Ok(await _contentType.CreateSiteRegionAsync(type, region)); } return NotFound(); } [Route("list")] [HttpGet] [Authorize(Policy = Permission.Content)] public Task<IActionResult> List() { return List(null); } [Route("{contentGroup}/list")] [HttpGet] [Authorize(Policy = Permission.Content)] public async Task<IActionResult> List(string contentGroup) { var model = await _content.GetListAsync(contentGroup); return Ok(model); } /// <summary> /// Gets the post with the given id. /// </summary> /// <param name="id">The unique id</param> /// <param name="languageId">The optional language id</param> /// <returns>The post edit model</returns> [Route("{id}/{languageId?}")] [HttpGet] [Authorize(Policy = Permission.Content)] public async Task<ContentEditModel> Get(Guid id, Guid? languageId = null) { return await _content.GetByIdAsync(id, languageId); } /// <summary> /// Gets the info model for the content with the /// given id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The content info model</returns> [Route("info/{id}")] [HttpGet] [Authorize(Policy = Permission.Content)] public async Task<Piranha.Models.ContentInfo> GetInfo(Guid id) { return await _api.Content.GetByIdAsync<Piranha.Models.ContentInfo>(id); } /// <summary> /// /// </summary> /// <param name="contentType">The content type</param> /// <returns>The edit model</returns> [Route("create/{contentType}")] [HttpGet] [Authorize(Policy = Permission.ContentAdd)] public async Task<ContentEditModel> Create(string contentType) { return await _content.CreateAsync(contentType); } /// <summary> /// Saves the given model /// </summary> /// <param name="model">The model</param> /// <returns>The result of the operation</returns> [Route("save")] [HttpPost] [Authorize(Policy = Permission.ContentSave)] public async Task<ContentEditModel> Save(ContentEditModel model) { try { await _content.SaveAsync(model); } catch (ValidationException e) { model.Status = new StatusMessage { Type = StatusMessage.Error, Body = e.Message }; return model; } var ret = await _content.GetByIdAsync(model.Id, model.LanguageId); ret.Status = new StatusMessage { Type = StatusMessage.Success, Body = "The content was successfully saved" }; return ret; } /// <summary> /// Deletes the content with the given id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The result of the operation</returns> [Route("delete")] [HttpDelete] [Authorize(Policy = Permission.ContentDelete)] public async Task<StatusMessage> Delete([FromBody]Guid id) { try { await _content.DeleteAsync(id); } catch (ValidationException e) { // Validation did not succeed return new StatusMessage { Type = StatusMessage.Error, Body = e.Message }; } catch { return new StatusMessage { Type = StatusMessage.Error, Body = "An error occured while deleting the content" }; } return new StatusMessage { Type = StatusMessage.Success, Body = "The content was successfully deleted" }; } } }
/* Copyright 2011 - 2016 Adrian Popescu. 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.Generic; using System.Globalization; using System.Linq; using System.Web.Script.Serialization; using Redmine.Net.Api.Internals; using Redmine.Net.Api.JSonConverters; using Redmine.Net.Api.Types; namespace Redmine.Net.Api.Extensions { /// <summary> /// /// </summary> public static class JsonExtensions { /// <summary> /// Writes the identifier if not null. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="ident">The ident.</param> /// <param name="key">The key.</param> public static void WriteIdIfNotNull(this Dictionary<string, object> dictionary, IdentifiableName ident, string key) { if (ident != null) dictionary.Add(key, ident.Id); } /// <summary> /// Writes the identifier or empty. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="ident">The ident.</param> /// <param name="key">The key.</param> /// <param name="emptyValue">The empty value.</param> public static void WriteIdOrEmpty(this Dictionary<string, object> dictionary, IdentifiableName ident, string key, string emptyValue = null) { if (ident != null) dictionary.Add(key, ident.Id); else dictionary.Add(key, emptyValue); } /// <summary> /// Writes the array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="col">The col.</param> /// <param name="converter">The converter.</param> /// <param name="serializer">The serializer.</param> public static void WriteArray<T>(this Dictionary<string, object> dictionary, string key, IEnumerable<T> col, JavaScriptConverter converter, JavaScriptSerializer serializer) { if (col != null) { serializer.RegisterConverters(new[] { converter }); dictionary.Add(key, col.ToArray()); } } /// <summary> /// Writes the ids array. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="coll">The coll.</param> public static void WriteIdsArray(this Dictionary<string, object> dictionary, string key, IEnumerable<IdentifiableName> coll) { if (coll != null) dictionary.Add(key, coll.Select(x => x.Id).ToArray()); } /// <summary> /// Writes the names array. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="coll">The coll.</param> public static void WriteNamesArray(this Dictionary<string, object> dictionary, string key, IEnumerable<IdentifiableName> coll) { if (coll != null) dictionary.Add(key, coll.Select(x => x.Name).ToArray()); } /// <summary> /// Writes the date or empty. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="val">The value.</param> /// <param name="tag">The tag.</param> public static void WriteDateOrEmpty(this Dictionary<string, object> dictionary, DateTime? val, string tag) { if (!val.HasValue || val.Value.Equals(default(DateTime))) dictionary.Add(tag, string.Empty); else dictionary.Add(tag, string.Format(NumberFormatInfo.InvariantInfo, "{0}", val.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))); } /// <summary> /// Writes the value or empty. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="val">The value.</param> /// <param name="tag">The tag.</param> public static void WriteValueOrEmpty<T>(this Dictionary<string, object> dictionary, T? val, string tag) where T : struct { if (!val.HasValue || EqualityComparer<T>.Default.Equals(val.Value, default(T))) dictionary.Add(tag, string.Empty); else dictionary.Add(tag, val.Value); } /// <summary> /// Writes the value or default. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="val">The value.</param> /// <param name="tag">The tag.</param> public static void WriteValueOrDefault<T>(this Dictionary<string, object> dictionary, T? val, string tag) where T : struct { dictionary.Add(tag, val ?? default(T)); } /// <summary> /// Gets the value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetValue<T>(this IDictionary<string, object> dictionary, string key) { object val; var dict = dictionary; var type = typeof(T); if (!dict.TryGetValue(key, out val)) return default(T); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (val == null) return default(T); type = Nullable.GetUnderlyingType(type); } if (val.GetType() == typeof(ArrayList)) return (T)val; if (type.IsEnum) val = Enum.Parse(type, val.ToString(), true); return (T)Convert.ChangeType(val, type, CultureInfo.InvariantCulture); } /// <summary> /// Gets the name of the value as identifiable. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns></returns> public static IdentifiableName GetValueAsIdentifiableName(this IDictionary<string, object> dictionary, string key) { object val; if (!dictionary.TryGetValue(key, out val)) return null; var ser = new JavaScriptSerializer(); ser.RegisterConverters(new[] { new IdentifiableNameConverter() }); var result = ser.ConvertToType<IdentifiableName>(val); return result; } /// <summary> /// For Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <returns></returns> public static List<T> GetValueAsCollection<T>(this IDictionary<string, object> dictionary, string key) where T : new() { object val; if (!dictionary.TryGetValue(key, out val)) return null; var ser = new JavaScriptSerializer(); ser.RegisterConverters(new[] { RedmineSerializer.JsonConverters[typeof(T)] }); var list = new List<T>(); var arrayList = val as ArrayList; if (arrayList != null) { list.AddRange(from object item in arrayList select ser.ConvertToType<T>(item)); } else { var dict = val as Dictionary<string, object>; if (dict != null) { list.AddRange(dict.Select(pair => ser.ConvertToType<T>(pair.Value))); } } return list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Globalization; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using OpenQA.Selenium; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Components.E2ETests.Tests { public abstract class GlobalizationTest<TServerFixture> : ServerTestBase<TServerFixture> where TServerFixture : ServerFixture { public GlobalizationTest(BrowserFixture browserFixture, TServerFixture serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { } protected abstract void SetCulture(string culture); [Theory] [InlineData("en-US")] [InlineData("fr-FR")] public virtual void CanSetCultureAndParseCultureSensitiveNumbersAndDates(string culture) { var cultureInfo = CultureInfo.GetCultureInfo(culture); SetCulture(culture); // int var input = Browser.Exists(By.Id("input_type_text_int")); var display = Browser.Exists(By.Id("input_type_text_int_value")); Browser.Equal(42.ToString(cultureInfo), () => display.Text); input.Clear(); input.SendKeys(NormalizeWhitespace(9000.ToString("0,000", cultureInfo))); input.SendKeys("\t"); Browser.Equal(9000.ToString(cultureInfo), () => display.Text); // decimal input = Browser.Exists(By.Id("input_type_text_decimal")); display = Browser.Exists(By.Id("input_type_text_decimal_value")); Browser.Equal(4.2m.ToString(cultureInfo), () => display.Text); input.Clear(); input.SendKeys(NormalizeWhitespace(9000.42m.ToString("0,000.00", cultureInfo))); input.SendKeys("\t"); Browser.Equal(9000.42m.ToString(cultureInfo), () => display.Text); // datetime input = Browser.Exists(By.Id("input_type_text_datetime")); display = Browser.Exists(By.Id("input_type_text_datetime_value")); Browser.Equal(new DateTime(1985, 3, 4).ToString(cultureInfo), () => display.Text); input.ReplaceText(new DateTime(2000, 1, 2).ToString(cultureInfo)); input.SendKeys("\t"); Browser.Equal(new DateTime(2000, 1, 2).ToString(cultureInfo), () => display.Text); // datetimeoffset input = Browser.Exists(By.Id("input_type_text_datetimeoffset")); display = Browser.Exists(By.Id("input_type_text_datetimeoffset_value")); Browser.Equal(new DateTimeOffset(new DateTime(1985, 3, 4)).ToString(cultureInfo), () => display.Text); input.ReplaceText(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo)); input.SendKeys("\t"); Browser.Equal(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo), () => display.Text); } private static string NormalizeWhitespace(string value) { // In some cultures, the number group separator may be a nonbreaking space. Chrome doesn't let you type a nonbreaking space, // so we need to replace it with a normal space. return Regex.Replace(value, "\\s", " "); } // The logic is different for verifying culture-invariant fields. The problem is that the logic for what // kinds of text a field accepts is determined by the browser and language - it's not general. So while // type="number" and type="date" produce fixed-format and culture-invariant input/output via the "value" // attribute - the actual input processing is harder to nail down. In practice this is only a problem // with dates. // // For this reason we avoid sending keys directly to the field, and let two-way binding do its thing instead. // // A brief summary: // 1. Input a value (invariant culture if using number field, or current culture to extra input if using date field) // 2. trigger onchange // 3. Verify "value" field (current culture) // 4. Verify the input field's value attribute (invariant culture) // // We need to do step 4 to make sure that the value we're entering can "stick" in the form field. // We can't use ".Text" because DOM reasons :( [Theory] [InlineData("en-US")] [InlineData("fr-FR")] public void CanSetCultureAndParseCultureInvariantNumbersAndDatesWithInputFields(string culture) { var cultureInfo = CultureInfo.GetCultureInfo(culture); SetCulture(culture); // int var input = Browser.Exists(By.Id("input_type_number_int")); var display = Browser.Exists(By.Id("input_type_number_int_value")); Browser.Equal(42.ToString(cultureInfo), () => display.Text); Browser.Equal(42.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(9000.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(9000.ToString(cultureInfo), () => display.Text); Browser.Equal(9000.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // decimal input = Browser.Exists(By.Id("input_type_number_decimal")); display = Browser.Exists(By.Id("input_type_number_decimal_value")); Browser.Equal(4.2m.ToString(cultureInfo), () => display.Text); Browser.Equal(4.2m.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(9000.42m.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(9000.42m.ToString(cultureInfo), () => display.Text); Browser.Equal(9000.42m.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // datetime input = Browser.Exists(By.Id("input_type_date_datetime")); display = Browser.Exists(By.Id("input_type_date_datetime_value")); var extraInput = Browser.Exists(By.Id("input_type_date_datetime_extrainput")); Browser.Equal(new DateTime(1985, 3, 4).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTime(1985, 3, 4).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); extraInput.ReplaceText(new DateTime(2000, 1, 2).ToString(cultureInfo)); extraInput.SendKeys("\t"); Browser.Equal(new DateTime(2000, 1, 2).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTime(2000, 1, 2).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // datetimeoffset input = Browser.Exists(By.Id("input_type_date_datetimeoffset")); display = Browser.Exists(By.Id("input_type_date_datetimeoffset_value")); extraInput = Browser.Exists(By.Id("input_type_date_datetimeoffset_extrainput")); Browser.Equal(new DateTimeOffset(new DateTime(1985, 3, 4)).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTimeOffset(new DateTime(1985, 3, 4)).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); extraInput.ReplaceText(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo)); extraInput.SendKeys("\t"); Browser.Equal(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); } [Theory] [InlineData("en-US")] [InlineData("fr-FR")] public void CanSetCultureAndParseCultureInvariantNumbersAndDatesWithFormComponents(string culture) { var cultureInfo = CultureInfo.GetCultureInfo(culture); SetCulture(culture); // int var input = Browser.Exists(By.Id("inputnumber_int")); var display = Browser.Exists(By.Id("inputnumber_int_value")); Browser.Equal(42.ToString(cultureInfo), () => display.Text); Browser.Equal(42.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(9000.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(9000.ToString(cultureInfo), () => display.Text); Browser.Equal(9000.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // long input = Browser.Exists(By.Id("inputnumber_long")); display = Browser.Exists(By.Id("inputnumber_long_value")); Browser.Equal(4200.ToString(cultureInfo), () => display.Text); Browser.Equal(4200.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(90000000000.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(90000000000.ToString(cultureInfo), () => display.Text); Browser.Equal(90000000000.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // short input = Browser.Exists(By.Id("inputnumber_short")); display = Browser.Exists(By.Id("inputnumber_short_value")); Browser.Equal(42.ToString(cultureInfo), () => display.Text); Browser.Equal(42.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(127.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(127.ToString(cultureInfo), () => display.Text); Browser.Equal(127.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // decimal input = Browser.Exists(By.Id("inputnumber_decimal")); display = Browser.Exists(By.Id("inputnumber_decimal_value")); Browser.Equal(4.2m.ToString(cultureInfo), () => display.Text); Browser.Equal(4.2m.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); input.Clear(); input.SendKeys(9000.42m.ToString(CultureInfo.InvariantCulture)); input.SendKeys("\t"); Browser.Equal(9000.42m.ToString(cultureInfo), () => display.Text); Browser.Equal(9000.42m.ToString(CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // datetime input = Browser.Exists(By.Id("inputdate_datetime")); display = Browser.Exists(By.Id("inputdate_datetime_value")); var extraInput = Browser.Exists(By.Id("inputdate_datetime_extrainput")); Browser.Equal(new DateTime(1985, 3, 4).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTime(1985, 3, 4).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); extraInput.ReplaceText(new DateTime(2000, 1, 2).ToString(cultureInfo)); extraInput.SendKeys("\t"); Browser.Equal(new DateTime(2000, 1, 2).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTime(2000, 1, 2).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); // datetimeoffset input = Browser.Exists(By.Id("inputdate_datetimeoffset")); display = Browser.Exists(By.Id("inputdate_datetimeoffset_value")); extraInput = Browser.Exists(By.Id("inputdate_datetimeoffset_extrainput")); Browser.Equal(new DateTimeOffset(new DateTime(1985, 3, 4)).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTimeOffset(new DateTime(1985, 3, 4)).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); extraInput.ReplaceText(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo)); extraInput.SendKeys("\t"); Browser.Equal(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString(cultureInfo), () => display.Text); Browser.Equal(new DateTimeOffset(new DateTime(2000, 1, 2)).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), () => input.GetAttribute("value")); } } }
// 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> /// Solution ///<para>SObject Name: Solution</para> ///<para>Custom Object: False</para> ///</summary> public class SfSolution : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "Solution"; } } ///<summary> /// Solution 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> /// 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> /// Solution Number /// <para>Name: SolutionNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "solutionNumber")] [Updateable(false), Createable(false)] public string SolutionNumber { get; set; } ///<summary> /// Title /// <para>Name: SolutionName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "solutionName")] public string SolutionName { get; set; } ///<summary> /// Public /// <para>Name: IsPublished</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isPublished")] public bool? IsPublished { get; set; } ///<summary> /// Visible in Public Knowledge Base /// <para>Name: IsPublishedInPublicKb</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isPublishedInPublicKb")] public bool? IsPublishedInPublicKb { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Reviewed /// <para>Name: IsReviewed</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isReviewed")] [Updateable(false), Createable(false)] public bool? IsReviewed { get; set; } ///<summary> /// Description /// <para>Name: SolutionNote</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "solutionNote")] public string SolutionNote { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: Owner</para> ///</summary> [JsonProperty(PropertyName = "owner")] [Updateable(false), Createable(false)] public SfUser Owner { 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> /// 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> /// 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> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { 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> /// Num Related Cases /// <para>Name: TimesUsed</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "timesUsed")] [Updateable(false), Createable(false)] public int? TimesUsed { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Is Html /// <para>Name: IsHtml</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isHtml")] [Updateable(false), Createable(false)] public bool? IsHtml { get; 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; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedNullableTests { #region Test methods [Fact] public static void CheckLiftedNullableBoolAndTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolAnd(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolAndAlsoTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolAndAlso(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolOrTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolOr(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolOrElseTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolOrElse(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolAndWithMethodTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodAnd(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolAndAlsoWithMethodTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodAndAlso(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolWithMethodOrTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodOr(values[i], values[j]); } } } [Fact] public static void CheckLiftedNullableBoolWithMethodOrElseTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyNullableBoolWithMethodOrElse(values[i], values[j]); } } } #endregion #region Test verifiers private static void VerifyNullableBoolAnd(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.And( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolAndAlso(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.AndAlso( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a == false ? false : a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolOr(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Or( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolOrElse(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.OrElse( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a == true ? true : a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodAnd(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.And( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodAndAlso(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.AndAlso( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a == false ? false : a & b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodOr(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Or( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a | b; Assert.Equal(expected, f()); } private static void VerifyNullableBoolWithMethodOrElse(bool? a, bool? b) { ParameterExpression p0 = Expression.Parameter(typeof(bool), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(bool), "p1"); Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.OrElse( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), null), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); bool? expected = a == true ? true : a | b; Assert.Equal(expected, f()); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Player.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // The player. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using Photon.MmoDemo.Client; using UnityEngine; /// <summary> /// The player. /// </summary> public class Player : MonoBehaviour { /// <summary> /// The change text. /// </summary> private bool changeText = false; /// <summary> /// The engine. /// </summary> private Game engine; /// <summary> /// The last key press. /// </summary> private float lastKeyPress; /// <summary> /// The last move position. /// </summary> private Vector3 lastMovePosition; /// <summary> /// The last move rotation. /// </summary> private Vector3 lastMoveRotation; /// <summary> /// The next move time. /// </summary> private float nextMoveTime; /// <summary> /// The name text. /// </summary> private GUIText nameText; /// <summary> /// The view text. /// </summary> private GUIText viewText; /// <summary> /// The get position. /// </summary> /// <param name="position"> /// The position. /// </param> /// <returns> /// the position as float array /// </returns> public static float[] GetPosition(Vector3 position) { float[] result = new float[3]; result[0] = position.x * MmoEngine.PositionFactorHorizonal; result[1] = position.z * MmoEngine.PositionFactorVertical; result[2] = position.y; return result; } public static float[] GetRotation(Vector3 rotation) { float[] rotationValue = new float[3]; rotationValue[0] = rotation.x; rotationValue[1] = rotation.y; rotationValue[2] = rotation.z; return rotationValue; } /// <summary> /// The initialize. /// </summary> /// <param name="engine"> /// The engine. /// </param> public void Initialize(Game engine) { this.nextMoveTime = 0; this.engine = engine; this.nameText = (GUIText)GameObject.Find("PlayerNamePrefab").GetComponent("GUIText"); this.viewText = (GUIText)GameObject.Find("ViewDistancePrefab").GetComponent("GUIText"); } /// <summary> /// The start. /// </summary> public void Start() { } /// <summary> /// The update. /// </summary> public void Update() { try { if (this.engine != null) { this.nameText.text = this.engine.Avatar.Text; this.viewText.text = string.Format("{0:0} x {1:0}", this.engine.Avatar.ViewDistanceEnter[0], this.engine.Avatar.ViewDistanceEnter[1]); this.Move(); this.ReadKeyboardInput(); } } catch (Exception e) { Debug.Log(e); } } /// <summary> /// The move. /// </summary> private void Move() { if (Time.time > this.nextMoveTime) { Vector3 rotation = this.transform.rotation.eulerAngles; if (this.lastMovePosition != this.transform.position || this.lastMoveRotation != rotation) { this.engine.Avatar.MoveAbsolute(GetPosition(this.transform.position), GetRotation(rotation)); this.lastMovePosition = this.transform.position; this.lastMoveRotation = rotation; } // up to 10 times per second this.nextMoveTime = Time.time + 0.1f; } } /// <summary> /// The read keyboard input. /// </summary> private void ReadKeyboardInput() { if (this.changeText) { if (Input.GetKey(KeyCode.Return)) { this.changeText = false; return; } if (Input.GetKey(KeyCode.Backspace)) { if (this.lastKeyPress + 0.1f < Time.time) { if (this.engine.Avatar.Text.Length > 0) { this.engine.Avatar.SetText(this.engine.Avatar.Text.Remove(this.engine.Avatar.Text.Length - 1)); this.lastKeyPress = Time.time; } } return; } this.engine.Avatar.SetText(this.engine.Avatar.Text + Input.inputString); return; } if (Input.GetKey(KeyCode.F1)) { this.changeText = true; return; } // center if (Input.GetKey(KeyCode.Keypad5) || Input.GetKey(KeyCode.C)) { if (this.lastKeyPress + 0.1f < Time.time) { float height = Terrain.activeTerrain.SampleHeight(new Vector3(1000, 0, 1000)); this.transform.position = new Vector3(1000, height + 1, 1000); this.lastKeyPress = Time.time; } } // view distance if (Input.GetKey(KeyCode.KeypadPlus)) { if (this.lastKeyPress + 0.05f < Time.time) { float[] viewDistance = (float[])this.engine.Avatar.ViewDistanceEnter.Clone(); viewDistance[0] = Mathf.Min(this.engine.WorldData.Width, viewDistance[0] + 1); viewDistance[1] = Mathf.Min(this.engine.WorldData.Height, viewDistance[1] + 1); InterestArea cam; this.engine.TryGetCamera(0, out cam); cam.SetViewDistance(viewDistance); this.lastKeyPress = Time.time; } } if (Input.GetKey(KeyCode.KeypadMinus)) { if (this.lastKeyPress + 0.05f < Time.time) { float[] viewDistance = (float[])this.engine.Avatar.ViewDistanceEnter.Clone(); viewDistance[0] = Mathf.Max(this.engine.WorldData.Width, viewDistance[0] - 1); viewDistance[1] = Mathf.Max(this.engine.WorldData.Height, viewDistance[1] - 1); InterestArea cam; this.engine.TryGetCamera(0, out cam); cam.SetViewDistance(viewDistance); this.lastKeyPress = Time.time; } } if (Input.GetKey(KeyCode.KeypadEnter)) { if (this.lastKeyPress + 0.05f < Time.time) { InterestArea cam; this.engine.TryGetCamera(0, out cam); cam.ResetViewDistance(); this.lastKeyPress = Time.time; } } if (Input.GetKey(KeyCode.F5) || Input.GetKey(KeyCode.E)) { if (this.lastKeyPress + 0.5f < Time.time) { InterestArea area; if (this.engine.TryGetCamera(1, out area)) { GameObject.Find("Sphere").GetComponent<RemoteCam>().Destroy(); } Debug.Log("create interest area"); GameObject actorCube = GameObject.CreatePrimitive(PrimitiveType.Sphere); RemoteCam remoteCam = actorCube.AddComponent<RemoteCam>(); remoteCam.Initialize(this.engine, 1, this.transform.position, UnityEngine.Camera.main.transform.forward); this.lastKeyPress = Time.time; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; using System.Threading; namespace OpenSim.Server.Handlers.Inventory { public class XInventoryInConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private string m_ConfigName = "InventoryService"; public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName); IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); string inventoryService = serverConfig.GetString("LocalServiceModule", String.Empty); if (inventoryService == String.Empty) throw new Exception("No InventoryService in config file"); Object[] args = new Object[] { config, m_ConfigName }; m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args); IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService, auth)); } } public class XInventoryConnectorPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; public XInventoryConnectorPostHandler(IInventoryService service, IServiceAuth auth) : base("POST", "/xinventory", auth) { m_InventoryService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); switch (method) { case "CREATEUSERINVENTORY": return HandleCreateUserInventory(request); case "GETINVENTORYSKELETON": return HandleGetInventorySkeleton(request); case "GETROOTFOLDER": return HandleGetRootFolder(request); case "GETFOLDERFORTYPE": return HandleGetFolderForType(request); case "GETFOLDERCONTENT": return HandleGetFolderContent(request); case "GETMULTIPLEFOLDERSCONTENT": return HandleGetMultipleFoldersContent(request); case "GETFOLDERITEMS": return HandleGetFolderItems(request); case "ADDFOLDER": return HandleAddFolder(request); case "UPDATEFOLDER": return HandleUpdateFolder(request); case "MOVEFOLDER": return HandleMoveFolder(request); case "DELETEFOLDERS": return HandleDeleteFolders(request); case "PURGEFOLDER": return HandlePurgeFolder(request); case "ADDITEM": return HandleAddItem(request); case "UPDATEITEM": return HandleUpdateItem(request); case "MOVEITEMS": return HandleMoveItems(request); case "DELETEITEMS": return HandleDeleteItems(request); case "GETITEM": return HandleGetItem(request); case "GETMULTIPLEITEMS": return HandleGetMultipleItems(request); case "GETFOLDER": return HandleGetFolder(request); case "GETACTIVEGESTURES": return HandleGetActiveGestures(request); case "GETASSETPERMISSIONS": return HandleGetAssetPermissions(request); } m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.Error(string.Format("[XINVENTORY HANDLER]: Exception {0} ", e.Message), e); } return FailureResult(); } private byte[] FailureResult() { return BoolResult(false); } private byte[] SuccessResult() { return BoolResult(true); } private byte[] BoolResult(bool value) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode(value.ToString())); rootElement.AppendChild(result); return Util.DocToBytes(doc); } byte[] HandleCreateUserInventory(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString()))) result["RESULT"] = "True"; else result["RESULT"] = "False"; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetInventorySkeleton(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString())); Dictionary<string, object> sfolders = new Dictionary<string, object>(); if (folders != null) { int i = 0; foreach (InventoryFolderBase f in folders) { sfolders["folder_" + i.ToString()] = EncodeFolder(f); i++; } } result["FOLDERS"] = sfolders; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetRootFolder(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal); if (rfolder != null) result["folder"] = EncodeFolder(rfolder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderForType(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); int type = 0; Int32.TryParse(request["TYPE"].ToString(), out type); InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (FolderType)type); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderContent(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID); if (icoll != null) { result["FID"] = icoll.FolderID.ToString(); result["VERSION"] = icoll.Version.ToString(); Dictionary<string, object> folders = new Dictionary<string, object>(); int i = 0; if (icoll.Folders != null) { foreach (InventoryFolderBase f in icoll.Folders) { folders["folder_" + i.ToString()] = EncodeFolder(f); i++; } result["FOLDERS"] = folders; } if (icoll.Items != null) { i = 0; Dictionary<string, object> items = new Dictionary<string, object>(); foreach (InventoryItemBase it in icoll.Items) { items["item_" + i.ToString()] = EncodeItem(it); i++; } result["ITEMS"] = items; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetMultipleFoldersContent(Dictionary<string, object> request) { Dictionary<string, object> resultSet = new Dictionary<string, object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); string folderIDstr = request["FOLDERS"].ToString(); int count = 0; Int32.TryParse(request["COUNT"].ToString(), out count); UUID[] fids = new UUID[count]; string[] uuids = folderIDstr.Split(','); int i = 0; foreach (string id in uuids) { UUID fid = UUID.Zero; if (UUID.TryParse(id, out fid)) fids[i] = fid; i += 1; } count = 0; InventoryCollection[] icollList = m_InventoryService.GetMultipleFoldersContent(principal, fids); if (icollList != null && icollList.Length > 0) { foreach (InventoryCollection icoll in icollList) { Dictionary<string, object> result = new Dictionary<string, object>(); result["FID"] = icoll.FolderID.ToString(); result["VERSION"] = icoll.Version.ToString(); result["OWNER"] = icoll.OwnerID.ToString(); Dictionary<string, object> folders = new Dictionary<string, object>(); i = 0; if (icoll.Folders != null) { foreach (InventoryFolderBase f in icoll.Folders) { folders["folder_" + i.ToString()] = EncodeFolder(f); i++; } result["FOLDERS"] = folders; } i = 0; if (icoll.Items != null) { Dictionary<string, object> items = new Dictionary<string, object>(); foreach (InventoryItemBase it in icoll.Items) { items["item_" + i.ToString()] = EncodeItem(it); i++; } result["ITEMS"] = items; } resultSet["F_" + fids[count++]] = result; //m_log.DebugFormat("[XXX]: Sending {0} {1}", fids[count-1], icoll.FolderID); } } string xmlString = ServerUtils.BuildXmlResponse(resultSet); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderItems(Dictionary<string, object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID); Dictionary<string, object> sitems = new Dictionary<string, object>(); if (items != null) { int i = 0; foreach (InventoryItemBase item in items) { sitems["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = sitems; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleAddFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.AddFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.UpdateFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveFolder(Dictionary<string,object> request) { UUID parentID = UUID.Zero; UUID.TryParse(request["ParentID"].ToString(), out parentID); UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID); if (m_InventoryService.MoveFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteFolders(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["FOLDERS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteFolders(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandlePurgeFolder(Dictionary<string,object> request) { UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); InventoryFolderBase folder = new InventoryFolderBase(folderID); if (m_InventoryService.PurgeFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleAddItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.AddItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.UpdateItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveItems(Dictionary<string,object> request) { List<string> idlist = (List<string>)request["IDLIST"]; List<string> destlist = (List<string>)request["DESTLIST"]; UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> items = new List<InventoryItemBase>(); int n = 0; try { foreach (string s in idlist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) { UUID fid = UUID.Zero; if (UUID.TryParse(destlist[n++], out fid)) { InventoryItemBase item = new InventoryItemBase(u, principal); item.Folder = fid; items.Add(item); } } } } catch (Exception e) { m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message); return FailureResult(); } if (m_InventoryService.MoveItems(principal, items)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteItems(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["ITEMS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteItems(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandleGetItem(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); UUID user = UUID.Zero; if (request.ContainsKey("PRINCIPAL")) UUID.TryParse(request["PRINCIPAL"].ToString(), out user); InventoryItemBase item = m_InventoryService.GetItem(user, id); if (item != null) result["item"] = EncodeItem(item); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetMultipleItems(Dictionary<string, object> request) { Dictionary<string, object> resultSet = new Dictionary<string, object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); string itemIDstr = request["ITEMS"].ToString(); int count = 0; Int32.TryParse(request["COUNT"].ToString(), out count); UUID[] fids = new UUID[count]; string[] uuids = itemIDstr.Split(','); int i = 0; foreach (string id in uuids) { UUID fid = UUID.Zero; if (UUID.TryParse(id, out fid)) fids[i] = fid; i += 1; } InventoryItemBase[] itemsList = m_InventoryService.GetMultipleItems(principal, fids); if (itemsList != null && itemsList.Length > 0) { count = 0; foreach (InventoryItemBase item in itemsList) resultSet["item_" + count++] = (item == null) ? (object)"NULL" : EncodeItem(item); } string xmlString = ServerUtils.BuildXmlResponse(resultSet); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolder(Dictionary<string,object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); UUID user = UUID.Zero; if (request.ContainsKey("PRINCIPAL")) UUID.TryParse(request["PRINCIPAL"].ToString(), out user); InventoryFolderBase folder = m_InventoryService.GetFolder(user, id); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetActiveGestures(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal); Dictionary<string, object> items = new Dictionary<string, object>(); if (gestures != null) { int i = 0; foreach (InventoryItemBase item in gestures) { items["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = items; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetAssetPermissions(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID assetID = UUID.Zero; UUID.TryParse(request["ASSET"].ToString(), out assetID); int perms = m_InventoryService.GetAssetPermissions(principal, assetID); result["RESULT"] = perms.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private Dictionary<string, object> EncodeFolder(InventoryFolderBase f) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["ParentID"] = f.ParentID.ToString(); ret["Type"] = f.Type.ToString(); ret["Version"] = f.Version.ToString(); ret["Name"] = f.Name; ret["Owner"] = f.Owner.ToString(); ret["ID"] = f.ID.ToString(); return ret; } private Dictionary<string, object> EncodeItem(InventoryItemBase item) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["AssetID"] = item.AssetID.ToString(); ret["AssetType"] = item.AssetType.ToString(); ret["BasePermissions"] = item.BasePermissions.ToString(); ret["CreationDate"] = item.CreationDate.ToString(); if (item.CreatorId != null) ret["CreatorId"] = item.CreatorId.ToString(); else ret["CreatorId"] = String.Empty; if (item.CreatorData != null) ret["CreatorData"] = item.CreatorData; else ret["CreatorData"] = String.Empty; ret["CurrentPermissions"] = item.CurrentPermissions.ToString(); ret["Description"] = item.Description.ToString(); ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString(); ret["Flags"] = item.Flags.ToString(); ret["Folder"] = item.Folder.ToString(); ret["GroupID"] = item.GroupID.ToString(); ret["GroupOwned"] = item.GroupOwned.ToString(); ret["GroupPermissions"] = item.GroupPermissions.ToString(); ret["ID"] = item.ID.ToString(); ret["InvType"] = item.InvType.ToString(); ret["Name"] = item.Name.ToString(); ret["NextPermissions"] = item.NextPermissions.ToString(); ret["Owner"] = item.Owner.ToString(); ret["SalePrice"] = item.SalePrice.ToString(); ret["SaleType"] = item.SaleType.ToString(); return ret; } private InventoryFolderBase BuildFolder(Dictionary<string,object> data) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = new UUID(data["ParentID"].ToString()); folder.Type = short.Parse(data["Type"].ToString()); folder.Version = ushort.Parse(data["Version"].ToString()); folder.Name = data["Name"].ToString(); folder.Owner = new UUID(data["Owner"].ToString()); folder.ID = new UUID(data["ID"].ToString()); return folder; } private InventoryItemBase BuildItem(Dictionary<string,object> data) { InventoryItemBase item = new InventoryItemBase(); item.AssetID = new UUID(data["AssetID"].ToString()); item.AssetType = int.Parse(data["AssetType"].ToString()); item.Name = data["Name"].ToString(); item.Owner = new UUID(data["Owner"].ToString()); item.ID = new UUID(data["ID"].ToString()); item.InvType = int.Parse(data["InvType"].ToString()); item.Folder = new UUID(data["Folder"].ToString()); item.CreatorId = data["CreatorId"].ToString(); item.CreatorData = data["CreatorData"].ToString(); item.Description = data["Description"].ToString(); item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); item.GroupID = new UUID(data["GroupID"].ToString()); item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); item.SalePrice = int.Parse(data["SalePrice"].ToString()); item.SaleType = byte.Parse(data["SaleType"].ToString()); item.Flags = uint.Parse(data["Flags"].ToString()); item.CreationDate = int.Parse(data["CreationDate"].ToString()); return item; } } }
using System; using System.Collections.Generic; using System.IO; namespace ServiceStack.Text { public static class StreamExtensions { public static void WriteTo(this Stream inStream, Stream outStream) { var memoryStream = inStream as MemoryStream; if (memoryStream != null) { memoryStream.WriteTo(outStream); return; } var data = new byte[4096]; int bytesRead; while ((bytesRead = inStream.Read(data, 0, data.Length)) > 0) { outStream.Write(data, 0, bytesRead); } } public static IEnumerable<string> ReadLines(this StreamReader reader) { if (reader == null) throw new ArgumentNullException("reader"); string line; while ((line = reader.ReadLine()) != null) { yield return line; } } /// <summary> /// @jonskeet: Collection of utility methods which operate on streams. /// r285, February 26th 2009: http://www.yoda.arachsys.com/csharp/miscutil/ /// </summary> const int DefaultBufferSize = 8 * 1024; /// <summary> /// Reads the given stream up to the end, returning the data as a byte /// array. /// </summary> public static byte[] ReadFully(this Stream input) { return ReadFully(input, DefaultBufferSize); } /// <summary> /// Reads the given stream up to the end, returning the data as a byte /// array, using the given buffer size. /// </summary> public static byte[] ReadFully(this Stream input, int bufferSize) { if (bufferSize < 1) { throw new ArgumentOutOfRangeException("bufferSize"); } return ReadFully(input, new byte[bufferSize]); } /// <summary> /// Reads the given stream up to the end, returning the data as a byte /// array, using the given buffer for transferring data. Note that the /// current contents of the buffer is ignored, so the buffer needn't /// be cleared beforehand. /// </summary> public static byte[] ReadFully(this Stream input, byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (input == null) { throw new ArgumentNullException("input"); } if (buffer.Length == 0) { throw new ArgumentException("Buffer has length of 0"); } // We could do all our own work here, but using MemoryStream is easier // and likely to be just as efficient. using (var tempStream = new MemoryStream()) { CopyTo(input, tempStream, buffer); // No need to copy the buffer if it's the right size if (tempStream.Length == tempStream.GetBuffer().Length) { return tempStream.GetBuffer(); } // Okay, make a copy that's the right size return tempStream.ToArray(); } } /// <summary> /// Copies all the data from one stream into another. /// </summary> public static void CopyTo(this Stream input, Stream output) { CopyTo(input, output, DefaultBufferSize); } /// <summary> /// Copies all the data from one stream into another, using a buffer /// of the given size. /// </summary> public static void CopyTo(this Stream input, Stream output, int bufferSize) { if (bufferSize < 1) { throw new ArgumentOutOfRangeException("bufferSize"); } CopyTo(input, output, new byte[bufferSize]); } /// <summary> /// Copies all the data from one stream into another, using the given /// buffer for transferring data. Note that the current contents of /// the buffer is ignored, so the buffer needn't be cleared beforehand. /// </summary> public static void CopyTo(this Stream input, Stream output, byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (input == null) { throw new ArgumentNullException("input"); } if (output == null) { throw new ArgumentNullException("output"); } if (buffer.Length == 0) { throw new ArgumentException("Buffer has length of 0"); } int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } } /// <summary> /// Reads exactly the given number of bytes from the specified stream. /// If the end of the stream is reached before the specified amount /// of data is read, an exception is thrown. /// </summary> public static byte[] ReadExactly(this Stream input, int bytesToRead) { return ReadExactly(input, new byte[bytesToRead]); } /// <summary> /// Reads into a buffer, filling it completely. /// </summary> public static byte[] ReadExactly(this Stream input, byte[] buffer) { return ReadExactly(input, buffer, buffer.Length); } /// <summary> /// Reads exactly the given number of bytes from the specified stream, /// into the given buffer, starting at position 0 of the array. /// </summary> public static byte[] ReadExactly(this Stream input, byte[] buffer, int bytesToRead) { return ReadExactly(input, buffer, 0, bytesToRead); } /// <summary> /// Reads exactly the given number of bytes from the specified stream, /// into the given buffer, starting at position 0 of the array. /// </summary> public static byte[] ReadExactly(this Stream input, byte[] buffer, int startIndex, int bytesToRead) { if (input == null) { throw new ArgumentNullException("input"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (startIndex < 0 || startIndex >= buffer.Length) { throw new ArgumentOutOfRangeException("startIndex"); } if (bytesToRead < 1 || startIndex + bytesToRead > buffer.Length) { throw new ArgumentOutOfRangeException("bytesToRead"); } return ReadExactlyFast(input, buffer, startIndex, bytesToRead); } /// <summary> /// Same as ReadExactly, but without the argument checks. /// </summary> private static byte[] ReadExactlyFast(Stream fromStream, byte[] intoBuffer, int startAtIndex, int bytesToRead) { var index = 0; while (index < bytesToRead) { var read = fromStream.Read(intoBuffer, startAtIndex + index, bytesToRead - index); if (read == 0) { throw new EndOfStreamException (String.Format("End of stream reached with {0} byte{1} left to read.", bytesToRead - index, bytesToRead - index == 1 ? "s" : "")); } index += read; } return intoBuffer; } } }
#if !NETFX_CORE && !PCL36 && !XAMARIN //----------------------------------------------------------------------- // <copyright file="CslaDataProvider.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Wraps and creates a CSLA .NET-style object </summary> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Data; using System.Reflection; using Csla.Reflection; using Csla.Properties; namespace Csla.Xaml { /// <summary> /// Wraps and creates a CSLA .NET-style object /// that you can use as a binding source. /// </summary> public class CslaDataProvider : DataSourceProvider { /// <summary> /// Creates an instance of the object. /// </summary> public CslaDataProvider() { _commandManager = new CslaDataProviderCommandManager(this); _factoryParameters = new ObservableCollection<object>(); _factoryParameters.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_factoryParameters_CollectionChanged); } /// <summary> /// Event raised when the object has been saved. /// </summary> public event EventHandler<Csla.Core.SavedEventArgs> Saved; /// <summary> /// Raise the Saved event when the object has been saved. /// </summary> /// <param name="newObject">New object reference as a result /// of the save operation.</param> /// <param name="error">Reference to an exception object if /// an error occurred.</param> /// <param name="userState">Reference to a userstate object.</param> protected virtual void OnSaved(object newObject, Exception error, object userState) { if (Saved != null) Saved(this, new Csla.Core.SavedEventArgs(newObject, error, userState)); } void _factoryParameters_CollectionChanged( object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { BeginQuery(); } #region Properties private Type _objectType = null; private bool _manageLifetime; private string _factoryMethod = string.Empty; private ObservableCollection<object> _factoryParameters; private bool _isAsynchronous; private CslaDataProviderCommandManager _commandManager; private bool _isBusy; /// <summary> /// Gets an object that can be used to execute /// Save and Undo commands on this CslaDataProvider /// through XAML command bindings. /// </summary> public CslaDataProviderCommandManager CommandManager { get { return _commandManager; } } /// <summary> /// Gets or sets the type of object /// to create an instance of. /// </summary> public Type ObjectType { get { return _objectType; } set { _objectType = value; OnPropertyChanged(new PropertyChangedEventArgs("ObjectType")); } } /// <summary> /// Gets or sets a value indicating whether the /// data control should manage the lifetime of /// the business object, including using n-level /// undo. /// </summary> public bool ManageObjectLifetime { get { return _manageLifetime; } set { _manageLifetime = value; OnPropertyChanged(new PropertyChangedEventArgs("ManageObjectLifetime")); } } private object _dataChangedHandler; /// <summary> /// Gets or sets a reference to an object that /// will handle the DataChanged event raised /// by this data provider. /// </summary> /// <remarks> /// This property is designed to /// reference an IErrorDialog control. /// </remarks> public object DataChangedHandler { get { return _dataChangedHandler; } set { _dataChangedHandler = value; var dialog = value as IErrorDialog; if (dialog != null) dialog.Register(this); OnPropertyChanged(new PropertyChangedEventArgs("DataChangedHandler")); } } /// <summary> /// Gets or sets the name of the static /// (Shared in Visual Basic) factory method /// that should be called to create the /// object instance. /// </summary> public string FactoryMethod { get { return _factoryMethod; } set { _factoryMethod = value; OnPropertyChanged(new PropertyChangedEventArgs("FactoryMethod")); } } /// <summary> /// Get the list of parameters to pass /// to the factory method. /// </summary> public IList FactoryParameters { get { return _factoryParameters; } } /// <summary> /// Gets or sets a value that indicates /// whether to perform object creation in /// a worker thread or in the active context. /// </summary> public bool IsAsynchronous { get { return _isAsynchronous; } set { _isAsynchronous = value; } } /// <summary> /// Gets or sets a reference to the data /// object. /// </summary> public object ObjectInstance { get { return Data; } set { OnQueryFinished(value, null, null, null); OnPropertyChanged(new PropertyChangedEventArgs("ObjectInstance")); } } /// <summary> /// Gets a value indicating if this object is busy. /// </summary> public bool IsBusy { get { return _isBusy; } protected set { _isBusy = value; OnPropertyChanged(new PropertyChangedEventArgs("IsBusy")); } } /// <summary> /// Triggers WPF data binding to rebind to the /// data object. /// </summary> public void Rebind() { object tmp = ObjectInstance; ObjectInstance = null; ObjectInstance = tmp; } #endregion #region Query private bool _firstRun = true; private bool _init = false; private bool _endInitCompete = false; private bool _endInitError = false; /// <summary> /// Indicates that the control is about to initialize. /// </summary> protected override void BeginInit() { _init = true; base.BeginInit(); } /// <summary> /// Indicates that the control has initialized. /// </summary> protected override void EndInit() { _init = false; base.EndInit(); _endInitCompete = true; } /// <summary> /// Overridden. Starts to create the requested object, /// either immediately or on a background thread, /// based on the value of the IsAsynchronous property. /// </summary> protected override void BeginQuery() { if (_init) return; if (_firstRun) { _firstRun = false; if (!IsInitialLoadEnabled) return; } if (_endInitError) { // this handles a case where the WPF form initilizer // invokes the data provider twice when an exception // occurs - we really don't want to try the query twice // or report the error twice _endInitError = false; OnQueryFinished(null); return; } if (this.IsRefreshDeferred) return; QueryRequest request = new QueryRequest(); request.ObjectType = _objectType; request.FactoryMethod = _factoryMethod; request.FactoryParameters = _factoryParameters; request.ManageObjectLifetime = _manageLifetime; IsBusy = true; if (IsAsynchronous) System.Threading.ThreadPool.QueueUserWorkItem(DoQuery, request); else DoQuery(request); } private void DoQuery(object state) { QueryRequest request = (QueryRequest)state; object result = null; Exception exceptionResult = null; object[] parameters = new List<object>(request.FactoryParameters).ToArray(); try { // get factory method info BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy; System.Reflection.MethodInfo factory = request.ObjectType.GetMethod( request.FactoryMethod, flags, null, MethodCaller.GetParameterTypes(parameters), null); if (factory == null) { // strongly typed factory couldn't be found // so find one with the correct number of // parameters int parameterCount = parameters.Length; System.Reflection.MethodInfo[] methods = request.ObjectType.GetMethods(flags); foreach (System.Reflection.MethodInfo method in methods) if (method.Name == request.FactoryMethod && method.GetParameters().Length == parameterCount) { factory = method; break; } } if (factory == null) { // no matching factory could be found // so throw exception throw new InvalidOperationException( string.Format(Resources.NoSuchFactoryMethod, request.FactoryMethod)); } // invoke factory method try { result = factory.Invoke(null, parameters); } catch (Csla.DataPortalException ex) { exceptionResult = ex.BusinessException; } catch (System.Reflection.TargetInvocationException ex) { if (ex.InnerException != null) { exceptionResult = ex.InnerException; var dpe = exceptionResult as Csla.DataPortalException; if (dpe != null && dpe.BusinessException != null) exceptionResult = dpe.BusinessException; } else exceptionResult = ex; } catch (Exception ex) { exceptionResult = ex; } } catch (Exception ex) { exceptionResult = ex; } if (request.ManageObjectLifetime && result != null) { Csla.Core.ISupportUndo undo = result as Csla.Core.ISupportUndo; if (undo != null) undo.BeginEdit(); } //if (!System.Windows.Application.Current.Dispatcher.CheckAccess()) // System.Windows.Application.Current.Dispatcher.Invoke( // new Action(() => { IsBusy = false; }), // new object[] { }); if (!_endInitCompete && exceptionResult != null) _endInitError = true; // return result to base class OnQueryFinished(result, exceptionResult, (o) => { IsBusy = false; return null; }, null); } #region QueryRequest Class private class QueryRequest { private Type _objectType; public Type ObjectType { get { return _objectType; } set { _objectType = value; } } private string _factoryMethod; public string FactoryMethod { get { return _factoryMethod; } set { _factoryMethod = value; } } private ObservableCollection<object> _factoryParameters; public ObservableCollection<object> FactoryParameters { get { return _factoryParameters; } set { _factoryParameters = new ObservableCollection<object>(new List<object>(value)); } } private bool _manageLifetime; public bool ManageObjectLifetime { get { return _manageLifetime; } set { _manageLifetime = value; } } } #endregion #endregion #region Cancel/Update/New/Remove /// <summary> /// Cancels changes to the business object, returning /// it to its previous state. /// </summary> /// <remarks> /// This metod does nothing unless ManageLifetime is /// set to true and the object supports n-level undo. /// </remarks> public void Cancel() { Csla.Core.ISupportUndo undo = this.Data as Csla.Core.ISupportUndo; if (undo != null && _manageLifetime) { IsBusy = true; undo.CancelEdit(); undo.BeginEdit(); IsBusy = false; } } /// <summary> /// Accepts changes to the business object, and /// commits them by calling the object's Save() /// method. /// </summary> /// <remarks> /// <para> /// This method does nothing unless the object /// implements Csla.Core.ISavable. /// </para><para> /// If the object implements IClonable, it /// will be cloned, and the clone will be /// saved. /// </para><para> /// If the object supports n-level undo and /// ManageLifetime is true, then this method /// will automatically call ApplyEdit() and /// BeginEdit() appropriately. /// </para> /// </remarks> public void Save() { // only do something if the object implements // ISavable Csla.Core.ISavable savable = this.Data as Csla.Core.ISavable; if (savable != null) { object result = savable; Exception exceptionResult = null; try { IsBusy = true; // clone the object if possible ICloneable clonable = savable as ICloneable; if (clonable != null) savable = (Csla.Core.ISavable)clonable.Clone(); // apply edits in memory Csla.Core.ISupportUndo undo = savable as Csla.Core.ISupportUndo; if (undo != null && _manageLifetime) undo.ApplyEdit(); // save the clone result = savable.Save(); if (!ReferenceEquals(savable, this.Data) && !Csla.ApplicationContext.AutoCloneOnUpdate) { // raise Saved event from original object Core.ISavable original = this.Data as Core.ISavable; if (original != null) original.SaveComplete(result); } // start editing the resulting object undo = result as Csla.Core.ISupportUndo; if (undo != null && _manageLifetime) undo.BeginEdit(); } catch (Exception ex) { exceptionResult = ex; } // clear previous object OnQueryFinished(null, exceptionResult, null, null); // return result to base class OnQueryFinished(result, null, null, null); IsBusy = false; OnSaved(result, exceptionResult, null); } } /// <summary> /// Adds a new item to the object if the object /// implements IBindingList and AllowNew is true. /// </summary> public object AddNew() { // only do something if the object implements // IBindingList IBindingList list = this.Data as IBindingList; if (list != null && list.AllowNew) return list.AddNew(); else return null; } /// <summary> /// Removes an item from the list if the object /// implements IBindingList and AllowRemove is true. /// </summary> /// <param name="sender">Object invoking this method.</param> /// <param name="e"> /// ExecuteEventArgs, where MethodParameter contains /// the item to be removed from the list. /// </param> public void RemoveItem(object sender, ExecuteEventArgs e) { var item = e.MethodParameter; // only do something if the object implements // IBindingList IBindingList list; Csla.Core.BusinessBase bb = item as Csla.Core.BusinessBase; if (bb != null) list = bb.Parent as IBindingList; else list = this.Data as IBindingList; if (list != null && list.AllowRemove) list.Remove(item); } #endregion } } #endif
using System; using System.IO; using System.Net; using System.Text; using AsterNET.FastAGI.MappingStrategies; using AsterNET.IO; using AsterNET.Util; namespace AsterNET.FastAGI { public class AsteriskFastAGI { #region Flags /// <summary> /// If set to true, causes the AGIChannel to throw an exception when a status code of 511 (Channel Dead) is returned. /// This is set to false by default to maintain backwards compatibility /// </summary> public bool SC511_CAUSES_EXCEPTION = false; /// <summary> /// If set to true, causes the AGIChannel to throw an exception when return status is 0 and reply is HANGUP. /// This is set to false by default to maintain backwards compatibility /// </summary> public bool SCHANGUP_CAUSES_EXCEPTION = false; #endregion #region Variables #if LOGGER private readonly Logger logger = Logger.Instance(); #endif private ServerSocket serverSocket; /// <summary> The port to listen on.</summary> private int port; /// <summary> The address to listen on.</summary> private readonly string address; /// <summary>The thread pool that contains the worker threads to process incoming requests.</summary> private ThreadPool pool; /// <summary> /// The number of worker threads in the thread pool. This equals the maximum number of concurrent requests this /// AGIServer can serve. /// </summary> private int poolSize; /// <summary> True while this server is shut down. </summary> private bool stopped; /// <summary> /// The strategy to use for bind AGIRequests to AGIScripts that serve them. /// </summary> private IMappingStrategy mappingStrategy; private Encoding socketEncoding = Encoding.ASCII; #endregion #region PoolSize /// <summary> /// Sets the number of worker threads in the thread pool.<br /> /// This equals the maximum number of concurrent requests this AGIServer can serve.<br /> /// The default pool size is 10. /// </summary> public int PoolSize { set { poolSize = value; } } #endregion #region BindPort /// <summary> /// Sets the TCP port to listen on for new connections.<br /> /// The default bind port is 4573. /// </summary> public int BindPort { set { port = value; } } #endregion #region MappingStrategy /// <summary> /// Sets the strategy to use for mapping AGIRequests to AGIScripts that serve them.<br /> /// The default mapping is a MappingStrategy. /// </summary> /// <seealso cref="MappingStrategy" /> public IMappingStrategy MappingStrategy { set { mappingStrategy = value; } } #endregion #region SocketEncoding public Encoding SocketEncoding { get { return socketEncoding; } set { socketEncoding = value; } } #endregion #region Constructor - AsteriskFastAGI() /// <summary> /// Creates a new AsteriskFastAGI. /// </summary> public AsteriskFastAGI() { address = Common.AGI_BIND_ADDRESS; port = Common.AGI_BIND_PORT; poolSize = Common.AGI_POOL_SIZE; mappingStrategy = new ResourceMappingStrategy(); } #endregion #region Constructor - AsteriskFastAGI() /// <summary> /// Creates a new AsteriskFastAGI. /// </summary> public AsteriskFastAGI(string mappingStrategy) { address = Common.AGI_BIND_ADDRESS; port = Common.AGI_BIND_PORT; poolSize = Common.AGI_POOL_SIZE; this.mappingStrategy = new ResourceMappingStrategy(mappingStrategy); } #endregion #region Constructor - AsteriskFastAGI() /// <summary> /// Creates a new AsteriskFastAGI. /// </summary> public AsteriskFastAGI(IMappingStrategy mappingStrategy) { address = Common.AGI_BIND_ADDRESS; port = Common.AGI_BIND_PORT; poolSize = Common.AGI_POOL_SIZE; this.mappingStrategy = mappingStrategy; } public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize) { address = ipaddress; this.port = port; this.poolSize = poolSize; this.mappingStrategy = mappingStrategy; } #endregion #region Constructor - AsteriskFastAGI(int port, int poolSize) /// <summary> /// Creates a new AsteriskFastAGI. /// </summary> /// <param name="port">The port to listen on.</param> /// <param name="poolSize"> /// The number of worker threads in the thread pool. /// This equals the maximum number of concurrent requests this AGIServer can serve. /// </param> public AsteriskFastAGI(int port, int poolSize) { address = Common.AGI_BIND_ADDRESS; this.port = port; this.poolSize = poolSize; mappingStrategy = new ResourceMappingStrategy(); } #endregion #region Constructor - AsteriskFastAGI(string address, int port, int poolSize) /// <summary> /// Creates a new AsteriskFastAGI. /// </summary> /// <param name="ipaddress">The address to listen on.</param> /// <param name="port">The port to listen on.</param> /// <param name="poolSize"> /// The number of worker threads in the thread pool. /// This equals the maximum number of concurrent requests this AGIServer can serve. /// </param> public AsteriskFastAGI(string ipaddress, int port, int poolSize) { address = ipaddress; this.port = port; this.poolSize = poolSize; mappingStrategy = new ResourceMappingStrategy(); } #endregion public AsteriskFastAGI(string ipaddress = Common.AGI_BIND_ADDRESS, int port = Common.AGI_BIND_PORT, int poolSize = Common.AGI_POOL_SIZE, bool sc511_CausesException = false, bool scHangUp_CausesException = false) { address = ipaddress; this.port = port; this.poolSize = poolSize; mappingStrategy = new ResourceMappingStrategy(); SC511_CAUSES_EXCEPTION = sc511_CausesException; SCHANGUP_CAUSES_EXCEPTION = scHangUp_CausesException; } #region Start() public void Start() { stopped = false; mappingStrategy.Load(); pool = new ThreadPool("AGIServer", poolSize); #if LOGGER logger.Info("Thread pool started."); #endif try { var ipAddress = IPAddress.Parse(address); serverSocket = new ServerSocket(port, ipAddress, SocketEncoding); } catch (Exception ex) { #if LOGGER if (ex is IOException) { logger.Error("Unable start AGI Server: cannot to bind to " + address + ":" + port + ".", ex); } #endif if (serverSocket != null) { serverSocket.Close(); serverSocket = null; } pool.Shutdown(); #if LOGGER logger.Info("AGI Server shut down."); #endif throw ex; } #if LOGGER logger.Info("Listening on " + address + ":" + port + "."); #endif try { SocketConnection socket; while ((socket = serverSocket.Accept()) != null) { #if LOGGER logger.Info("Received connection."); #endif var connectionHandler = new AGIConnectionHandler(socket, mappingStrategy, SC511_CAUSES_EXCEPTION, SCHANGUP_CAUSES_EXCEPTION); pool.AddJob(connectionHandler); } } catch (IOException ex) { if (!stopped) { #if LOGGER logger.Error("IOException while waiting for connections (1).", ex); #endif throw ex; } } finally { if (serverSocket != null) { try { serverSocket.Close(); } #if LOGGER catch (IOException ex) { logger.Error("IOException while waiting for connections (2).", ex); } #else catch { } #endif } serverSocket = null; pool.Shutdown(); #if LOGGER logger.Info("AGI Server shut down."); #endif } } #endregion #region Stop() public void Stop() { stopped = true; if (serverSocket != null) serverSocket.Close(); } #endregion } }
/* * Copyright (c) 2017 Richard Vallett * * 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.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Windows.Forms; using URDF; using Inventor; namespace URDFConverter { public partial class Form1 : Form { Inventor.Application _invApp; bool _started = false; public Form1() { InitializeComponent(); #region Get Inventor session try { _invApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application"); } catch (Exception ex) { try { Type invAppType = Type.GetTypeFromProgID("Inventor.Application"); _invApp = (Inventor.Application)System.Activator.CreateInstance(invAppType); _invApp.Visible = true; /* Note: if the Inventor session is left running after this * form is closed, there will still an be and Inventor.exe * running. We will use this Boolean to test in Form1.Designer.cs * in the dispose method whether or not the Inventor App should * be shut down when the form is closed. */ _started = true; } catch (Exception ex2) { MessageBox.Show(ex2.ToString()); MessageBox.Show("Unable to get or start Inventor"); } } #endregion #region Test code /* // Define a new Robot, robot, with the name "HuboPlus" Robot robot = new Robot("HuboPlus"); // Define a new Link, link1, with the name "link1". Link link1 = new Link("link1"); // Set the Visual attributes, geometric and material, of the link. link1.Visual = new Visual(new Mesh("package://link1.stl"), new URDF.Material("Red", new double[] { 255, 0, 0, 1.0 })); // Set the Collision attributes of the link. link1.Collision = new Collision(new URDF.Cylinder(1, 2)); // Set the Inertial attributes of the link. link1.Inertial = new Inertial(5, new double[] { 1, 0, 0, 1, 0, 1 }); // Add the link to the list of links within the robot. robot.Links.Add(link1); // Make a clone of link1 and add it to the robot model. robot.Links.Add((Link)link1.Clone()); // Define a new Joint, joint1, with the name "joint1". Joint joint1 = new Joint("joint1", JointType.Prismatic, link1, link1); robot.Joints.Add(joint1); robot.Joints.Add((Joint)joint1.Clone()); robot.WriteURDFToFile("hubo.xml"); */ #endregion WriteURDF("HuboPlus.xml"); } public void WriteURDF(string xmlfilename) { UnitsOfMeasure oUOM = _invApp.ActiveDocument.UnitsOfMeasure; AssemblyDocument oAsmDoc = (AssemblyDocument)_invApp.ActiveDocument; AssemblyComponentDefinition oAsmCompDef = oAsmDoc.ComponentDefinition; ComponentOccurrence Parent; string ParentName, AbsolutePosition, name, mirname, mirParentName; double[] ParentCOM, Offset; Robot hubo = new Robot("HuboPlus"); foreach (ComponentOccurrence oCompOccur in oAsmCompDef.Occurrences) { // Generate links from available subassemblies in main assembly. hubo.Links.Add(new Link(oCompOccur.Name)); int c = hubo.Links.Count - 1; for (int i = 0; i < hubo.Links.Count; i++) { if (String.Equals(hubo.Links[i].Name, ReturnParentName(oCompOccur))) hubo.Links[c].Parent = hubo.Links[i]; } if (hubo.Links[c].Parent != null) { hubo.Joints.Add(new Joint(FormatJointName(hubo.Links[c].Name), JointType.Revolute, hubo.Links[c].Parent, hubo.Links[c])); int j = hubo.Joints.Count - 1; switch (hubo.Joints[j].Name[hubo.Joints[j].Name.Length - 1]) { case 'R': hubo.Joints[j].Axis = new double[] { 1, 0, 0 }; break; case 'P': hubo.Joints[j].Axis = new double[] { 0, 1, 0 }; break; case 'Y': hubo.Joints[j].Axis = new double[] { 0, 0, 1 }; break; default: break; } } // Get mass properties for each link. double[] iXYZ = new double[6]; oCompOccur.MassProperties.XYZMomentsOfInertia(out iXYZ[0], out iXYZ[3], out iXYZ[5], out iXYZ[1], out iXYZ[4], out iXYZ[2]); // Ixx, Iyy, Izz, Ixy, Iyz, Ixz -> Ixx, Ixy, Ixz, Iyy, Iyz, Izz hubo.Links[c].Inertial = new Inertial(oCompOccur.MassProperties.Mass, iXYZ); hubo.Links[c].Inertial.XYZ = FindCenterOfMassOffset(oCompOccur); // Set shape properties for each link. hubo.Links[c].Visual = new Visual(new Mesh("package://" + hubo.Name + "/" + hubo.Links[c].Name + ".stl")); } } public double[] ComputeRelativeOffset(ComponentOccurrence Child, ComponentOccurrence Parent) { double[] c1 = FindOrigin(Parent); double[] c2 = FindOrigin(Child); double[] c3 = new double[3]; for (int k = 0; k < 3; k++) { c3[k] = c2[k] - c1[k]; } return c3; } public double[] FindOrigin(ComponentOccurrence oCompOccur) { UnitsOfMeasure oUOM = _invApp.ActiveDocument.UnitsOfMeasure; AssemblyComponentDefinition oCompDef = (AssemblyComponentDefinition)oCompOccur.Definition; object oWorkPointProxy; double[] c = new double[3]; WorkPoint oWP = oCompDef.WorkPoints[1]; oCompOccur.CreateGeometryProxy(oWP, out oWorkPointProxy); c[0] = ((WorkPointProxy)oWorkPointProxy).Point.X; c[1] = ((WorkPointProxy)oWorkPointProxy).Point.Y; c[2] = ((WorkPointProxy)oWorkPointProxy).Point.Z; for (int k = 0; k < 3; k++) { c[k] = oUOM.ConvertUnits(c[k], "cm", "m"); } string AbsolutePosition, name; name = FormatName(oCompOccur.Name); return c; } public int CheckBody(string strData) { // Match Bodies to actually export based on naming convention MatchCollection REMatches = Regex.Matches(strData, "^Body_", RegexOptions.IgnoreCase); return REMatches.Count; } public double[] FindCenterOfMassOffset(ComponentOccurrence oDoc) { // Store temporary variables and names MassProperties oMassProps = oDoc.MassProperties; double[] c = new double[3]; c[0] = oMassProps.CenterOfMass.X; c[1] = oMassProps.CenterOfMass.Y; c[2] = oMassProps.CenterOfMass.Z; UnitsOfMeasure oUOM = _invApp.ActiveDocument.UnitsOfMeasure; for (int k = 0; k < 3; k++) { c[k] = oUOM.ConvertUnits(c[k], "cm", "m"); } return c; } public string ReturnParentName(ComponentOccurrence occur) { try { return occur.Definition.Document.PropertySets.Item("Inventor User Defined Properties").Item("Parent").Value; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } public string FormatName(string strData) { // Match Bodies to actually export based on naming convention string res = strData; try { res = res.Split(':')[0]; } catch (Exception ex) { MessageBox.Show(ex.Message); } return res; } public string FormatJointName(string strData) { // Match Bodies to actually export based on naming convention int Count; Match REMatches = Regex.Match(strData, "[LRTH][HSKAEWNRPYBD][RPY]", RegexOptions.IgnoreCase); Count = REMatches.Length; return REMatches.Value; } public ComponentOccurrence FindComponentOccurrence(ComponentOccurrences Comp, string name) { foreach (ComponentOccurrence occur in Comp) { if (occur.Name.IndexOf(name) >= 0) { return occur; } } return null; } } }
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 Grauenwolf.TravellerTools.Web.Areas.HelpPage.ModelDescriptions; using Grauenwolf.TravellerTools.Web.Areas.HelpPage.Models; namespace Grauenwolf.TravellerTools.Web.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); } } } }
#region License // Copyright 2014 MorseCode Software // 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 namespace MorseCode.RxMvvm.Observable.Property.Internal { using System; using System.Diagnostics.Contracts; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using MorseCode.RxMvvm.Common; using MorseCode.RxMvvm.Common.DiscriminatedUnion; [Serializable] internal class AsyncCalculatedPropertyWithContext<TContext, TFirst, TSecond, TThird, TFourth, T> : CalculatedPropertyBase<T>, ISerializable { private readonly TContext context; private readonly IObservable<TFirst> firstProperty; private readonly IObservable<TSecond> secondProperty; private readonly IObservable<TThird> thirdProperty; private readonly IObservable<TFourth> fourthProperty; private readonly TimeSpan throttleTime; private readonly Func<TContext, TFirst, TSecond, TThird, TFourth, T> calculateValue; private readonly bool isLongRunningCalculation; private IDisposable scheduledTask; internal AsyncCalculatedPropertyWithContext( TContext context, IObservable<TFirst> firstProperty, IObservable<TSecond> secondProperty, IObservable<TThird> thirdProperty, IObservable<TFourth> fourthProperty, TimeSpan throttleTime, Func<TContext, TFirst, TSecond, TThird, TFourth, T> calculateValue, bool isLongRunningCalculation) { Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty"); Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty"); Contract.Requires<ArgumentNullException>(thirdProperty != null, "thirdProperty"); Contract.Requires<ArgumentNullException>(fourthProperty != null, "fourthProperty"); Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue"); Contract.Ensures(this.firstProperty != null); Contract.Ensures(this.secondProperty != null); Contract.Ensures(this.thirdProperty != null); Contract.Ensures(this.fourthProperty != null); Contract.Ensures(this.calculateValue != null); RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue); this.context = context; this.firstProperty = firstProperty; this.secondProperty = secondProperty; this.thirdProperty = thirdProperty; this.fourthProperty = fourthProperty; this.throttleTime = throttleTime; this.calculateValue = calculateValue; this.isLongRunningCalculation = isLongRunningCalculation; Func<TFirst, TSecond, TThird, TFourth, IDiscriminatedUnion<object, T, Exception>> calculate = (first, second, third, fourth) => { IDiscriminatedUnion<object, T, Exception> discriminatedUnion; try { discriminatedUnion = DiscriminatedUnion.First<object, T, Exception>( calculateValue(context, first, second, third, fourth)); } catch (Exception e) { discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e); } return discriminatedUnion; }; this.SetHelper(new CalculatedPropertyHelper( (resultSubject, isCalculatingSubject) => { CompositeDisposable d = new CompositeDisposable(); IScheduler scheduler = isLongRunningCalculation ? RxMvvmConfiguration.GetLongRunningCalculationScheduler() : RxMvvmConfiguration.GetCalculationScheduler(); IObservable<Tuple<TFirst, TSecond, TThird, TFourth>> o = firstProperty.CombineLatest(secondProperty, thirdProperty, fourthProperty, Tuple.Create); o = throttleTime > TimeSpan.Zero ? o.Throttle(throttleTime, scheduler) : o.ObserveOn(scheduler); d.Add( o.Subscribe( v => { using (this.scheduledTask) { } isCalculatingSubject.OnNext(true); this.scheduledTask = scheduler.ScheduleAsync( async (s, t) => { try { await s.Yield(t).ConfigureAwait(true); IDiscriminatedUnion<object, T, Exception> result = calculate(v.Item1, v.Item2, v.Item3, v.Item4); await s.Yield(t).ConfigureAwait(true); resultSubject.OnNext(result); } catch (OperationCanceledException) { } catch (Exception e) { resultSubject.OnNext( DiscriminatedUnion.Second<object, T, Exception>(e)); } isCalculatingSubject.OnNext(false); }); })); return d; })); } /// <summary> /// Initializes a new instance of the <see cref="AsyncCalculatedPropertyWithContext{TContext,TFirst,TSecond,TThird,TFourth,T}"/> class. /// Initializes a new instance of the <see cref="AsyncCalculatedProperty{TFirst,TSecond,TThird,TFourth,T}"/> class. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="context"> /// The serialization context. /// </param> [ContractVerification(false)] // ReSharper disable UnusedParameter.Local protected AsyncCalculatedPropertyWithContext(SerializationInfo info, StreamingContext context) // ReSharper restore UnusedParameter.Local : this( (TContext)(info.GetValue("c", typeof(TContext)) ?? default(TContext)), (IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)), (IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)), (IObservable<TThird>)info.GetValue("p3", typeof(IObservable<TThird>)), (IObservable<TFourth>)info.GetValue("p4", typeof(IObservable<TFourth>)), (TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)), (Func<TContext, TFirst, TSecond, TThird, TFourth, T>)info.GetValue("f", typeof(Func<TContext, TFirst, TSecond, TThird, TFourth, T>)), (bool)info.GetValue("l", typeof(bool))) { } /// <summary> /// Gets the object data to serialize. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="streamingContext"> /// The serialization context. /// </param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext streamingContext) { info.AddValue("c", this.context); info.AddValue("p1", this.firstProperty); info.AddValue("p2", this.secondProperty); info.AddValue("p3", this.thirdProperty); info.AddValue("p4", this.fourthProperty); info.AddValue("t", this.throttleTime); info.AddValue("f", this.calculateValue); info.AddValue("l", this.isLongRunningCalculation); } /// <summary> /// Disposes of the property. /// </summary> protected override void Dispose() { base.Dispose(); using (this.scheduledTask) { } } [ContractInvariantMethod] private void CodeContractsInvariants() { Contract.Invariant(this.firstProperty != null); Contract.Invariant(this.secondProperty != null); Contract.Invariant(this.thirdProperty != null); Contract.Invariant(this.fourthProperty != null); Contract.Invariant(this.calculateValue != null); } } }
using Signum.Entities.Basics; using Signum.Entities.DynamicQuery; using System.ComponentModel; using Signum.Entities.UserAssets; using Signum.Entities.Templating; using System.Xml.Linq; using Signum.Entities.UserQueries; namespace Signum.Entities.Mailing; [EntityKind(EntityKind.Main, EntityData.Master)] public class EmailTemplateEntity : Entity, IUserAssetEntity { public EmailTemplateEntity() { RebindEvents(); } [UniqueIndex] public Guid Guid { get; set; } = Guid.NewGuid(); public EmailTemplateEntity(object queryName) : this() { this.queryName = queryName; } [Ignore] internal object queryName; [UniqueIndex] [StringLengthValidator(Min = 3, Max = 100)] public string Name { get; set; } public bool EditableMessage { get; set; } = true; public bool DisableAuthorization { get; set; } public QueryEntity Query { get; set; } public EmailModelEntity? Model { get; set; } public EmailTemplateFromEmbedded? From { get; set; } [NoRepeatValidator] public MList<EmailTemplateRecipientEmbedded> Recipients { get; set; } = new MList<EmailTemplateRecipientEmbedded>(); public bool GroupResults { get; set; } [PreserveOrder] public MList<QueryFilterEmbedded> Filters { get; set; } = new MList<QueryFilterEmbedded>(); [PreserveOrder] public MList<QueryOrderEmbedded> Orders { get; set; } = new MList<QueryOrderEmbedded>(); [PreserveOrder] [NoRepeatValidator, ImplementedBy(typeof(ImageAttachmentEntity)), NotifyChildProperty] public MList<IAttachmentGeneratorEntity> Attachments { get; set; } = new MList<IAttachmentGeneratorEntity>(); public Lite<EmailMasterTemplateEntity>? MasterTemplate { get; set; } public bool IsBodyHtml { get; set; } = true; [NotifyCollectionChanged, NotifyChildProperty] public MList<EmailTemplateMessageEmbedded> Messages { get; set; } = new MList<EmailTemplateMessageEmbedded>(); [NotifyChildProperty] public TemplateApplicableEval? Applicable { get; set; } protected override string? PropertyValidation(System.Reflection.PropertyInfo pi) { if (pi.Name == nameof(Messages)) { if (Messages == null || !Messages.Any()) return EmailTemplateMessage.ThereAreNoMessagesForTheTemplate.NiceToString(); if (Messages.GroupCount(m => m.CultureInfo).Any(c => c.Value > 1)) return EmailTemplateMessage.TheresMoreThanOneMessageForTheSameLanguage.NiceToString(); } return base.PropertyValidation(pi); } [AutoExpressionField] public override string ToString() => As.Expression(() => Name); internal void ParseData(QueryDescription description) { var canAggregate = this.GroupResults ? SubTokensOptions.CanAggregate : 0; foreach (var r in Recipients.Where(r => r.Token != null)) r.Token!.ParseData(this, description, SubTokensOptions.CanElement); if (From != null && From.Token != null) From.Token.ParseData(this, description, SubTokensOptions.CanElement); foreach (var f in Filters) f.ParseData(this, description, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | canAggregate); foreach (var o in Orders) o.ParseData(this, description, SubTokensOptions.CanElement | canAggregate); } public bool IsApplicable(Entity? entity) { if (Applicable == null) return true; try { return Applicable.Algorithm!.ApplicableUntyped(entity); } catch (Exception e) { throw new ApplicationException($"Error evaluating Applicable for EmailTemplate '{Name}' with entity '{entity}': " + e.Message, e); } } public XElement ToXml(IToXmlContext ctx) { if(this.Attachments != null && this.Attachments.Count() > 0) { throw new NotImplementedException("Attachments are not yet exportable"); } return new XElement("EmailTemplate", new XAttribute("Name", Name), new XAttribute("Guid", Guid), new XAttribute("DisableAuthorization", DisableAuthorization), new XAttribute("Query", Query.Key), new XAttribute("EditableMessage", EditableMessage), Model == null ? null! /*FIX all null! -> null*/ : new XAttribute("Model", Model.FullClassName), MasterTemplate == null ? null! : new XAttribute("MasterTemplate", ctx.Include(MasterTemplate)), new XAttribute("GroupResults", GroupResults), Filters.IsNullOrEmpty() ? null! : new XElement("Filters", Filters.Select(f => f.ToXml(ctx)).ToList()), Orders.IsNullOrEmpty() ? null! : new XElement("Orders", Orders.Select(o => o.ToXml(ctx)).ToList()), new XAttribute("IsBodyHtml", IsBodyHtml), From == null ? null! : new XElement("From", From.DisplayName != null ? new XAttribute("DisplayName", From.DisplayName) : null!, From.EmailAddress != null ? new XAttribute("EmailAddress", From.EmailAddress) : null!, From.Token != null ? new XAttribute("Token", From.Token.Token.FullKey()) : null!, new XAttribute("WhenMany", From.WhenMany), new XAttribute("WhenNone", From.WhenNone) ), new XElement("Recipients", Recipients.Select(rec => new XElement("Recipient", rec.DisplayName.HasText()? new XAttribute("DisplayName", rec.DisplayName) : null!, rec.EmailAddress.HasText()? new XAttribute("EmailAddress", rec.EmailAddress) : null!, new XAttribute("Kind", rec.Kind), rec.Token != null ? new XAttribute("Token", rec.Token?.Token.FullKey()!) : null!, new XAttribute("WhenMany", rec.WhenMany), new XAttribute("WhenNone", rec.WhenNone) ) )), new XElement("Messages", Messages.Select(x => new XElement("Message", new XAttribute("CultureInfo", x.CultureInfo.Name), new XAttribute("Subject", x.Subject), new XCData(x.Text) ))), this.Applicable?.Let(app => new XElement("Applicable", new XCData(app.Script)))! ); } public void FromXml(XElement element, IFromXmlContext ctx) { Guid = Guid.Parse(element.Attribute("Guid")!.Value); Name = element.Attribute("Name")!.Value; DisableAuthorization = element.Attribute("DisableAuthorization")?.Let(a => bool.Parse(a.Value)) ?? false; Query = ctx.GetQuery(element.Attribute("Query")!.Value); EditableMessage = bool.Parse(element.Attribute("EditableMessage")!.Value); Model = element.Attribute("Model")?.Let(at => ctx.GetEmailModel(at.Value)); MasterTemplate = element.Attribute("MasterTemplate")?.Let(a=>(Lite<EmailMasterTemplateEntity>)ctx.GetEntity(Guid.Parse(a.Value)).ToLite()); GroupResults = bool.Parse(element.Attribute("GroupResults")!.Value); Filters.Synchronize(element.Element("Filters")?.Elements().ToList(), (f, x) => f.FromXml(x, ctx)); Orders.Synchronize(element.Element("Orders")?.Elements().ToList(), (o, x) => o.FromXml(x, ctx)); IsBodyHtml = bool.Parse(element.Attribute("IsBodyHtml")!.Value); From = element.Element("From")?.Let(from => new EmailTemplateFromEmbedded { DisplayName = from.Attribute("DisplayName")?.Value, EmailAddress = from.Attribute("EmailAddress")?.Value, Token = from.Attribute("Token")?.Let(t => new QueryTokenEmbedded(t.Value)), WhenMany = from.Attribute("WhenMany")?.Value.ToEnum<WhenManyFromBehaviour>() ?? WhenManyFromBehaviour.FistResult, WhenNone = from.Attribute("WhenNone")?.Value.ToEnum<WhenNoneFromBehaviour>() ?? WhenNoneFromBehaviour.NoMessage, }); Recipients = element.Element("Recipients")!.Elements("Recipient").Select(rep => new EmailTemplateRecipientEmbedded { DisplayName = rep.Attribute("DisplayName")?.Value, EmailAddress = rep.Attribute("EmailAddress")?.Value, Kind = rep.Attribute("Kind")!.Value.ToEnum<EmailRecipientKind>(), Token = rep.Attribute("Token")?.Let(a => new QueryTokenEmbedded(a.Value)), WhenMany = rep.Attribute("WhenMany")?.Value?.ToEnum<WhenManyRecipiensBehaviour>() ?? WhenManyRecipiensBehaviour.KeepOneMessageWithManyRecipients, WhenNone = rep.Attribute("WhenNone")?.Value?.ToEnum<WhenNoneRecipientsBehaviour>() ?? WhenNoneRecipientsBehaviour.ThrowException, }).ToMList(); Messages = element.Element("Messages")!.Elements("Message").Select(elem => new EmailTemplateMessageEmbedded(ctx.GetCultureInfoEntity(elem.Attribute("CultureInfo")!.Value)) { Subject = elem.Attribute("Subject")!.Value, Text = elem.Value }).ToMList(); Applicable = element.Element("Applicable")?.Let(app => new TemplateApplicableEval { Script = app.Value}); ParseData(ctx.GetQueryDescription(Query)); } } public abstract class EmailTemplateAddressEmbedded : EmbeddedEntity { public string? EmailAddress { get; set; } public string? DisplayName { get; set; } public QueryTokenEmbedded? Token { get; set; } public override string ToString() { return "{0} <{1}>".FormatWith(DisplayName, EmailAddress); } protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(Token)) { if (Token == null && EmailAddress.IsNullOrEmpty()) return EmailTemplateMessage.TokenOrEmailAddressMustBeSet.NiceToString(); if (Token != null && !EmailAddress.IsNullOrEmpty()) return EmailTemplateMessage.TokenAndEmailAddressCanNotBeSetAtTheSameTime.NiceToString(); if (Token != null && Token.Token.Type != typeof(EmailOwnerData)) return EmailTemplateMessage.TokenMustBeA0.NiceToString(typeof(EmailOwnerData).NiceName()); } return null; } } public class EmailTemplateRecipientEmbedded : EmailTemplateAddressEmbedded { public EmailRecipientKind Kind { get; set; } public WhenNoneRecipientsBehaviour WhenNone { get; set; } public WhenManyRecipiensBehaviour WhenMany { get; set; } public override string ToString() { return "{0} {1} <{2}>".FormatWith(Kind.NiceToString(), DisplayName, EmailAddress); } } public enum WhenNoneRecipientsBehaviour { ThrowException, NoMessage, NoRecipients } public enum WhenManyRecipiensBehaviour { SplitMessages, KeepOneMessageWithManyRecipients, } public class EmailTemplateFromEmbedded : EmailTemplateAddressEmbedded { public WhenNoneFromBehaviour WhenNone { get; set; } public WhenManyFromBehaviour WhenMany { get; set; } public Guid? AzureUserId { get; set; } } public enum WhenNoneFromBehaviour { ThrowException, NoMessage, DefaultFrom } public enum WhenManyFromBehaviour { SplitMessages, FistResult, } public class EmailTemplateMessageEmbedded : EmbeddedEntity { private EmailTemplateMessageEmbedded() { } public EmailTemplateMessageEmbedded(CultureInfoEntity culture) { this.CultureInfo = culture; } public CultureInfoEntity CultureInfo { get; set; } [DbType(Size = int.MaxValue)] string text; [StringLengthValidator(MultiLine=true)] public string Text { get { return text; } set { if (Set(ref text, value)) TextParsedNode = null; } } [Ignore] internal object? TextParsedNode; string subject; [StringLengthValidator(Min = 3, Max = 200)] public string Subject { get { return subject; } set { if (Set(ref subject, value)) SubjectParsedNode = null; } } [Ignore] internal object? SubjectParsedNode; public override string ToString() { return CultureInfo?.ToString() ?? EmailTemplateMessage.NewCulture.NiceToString(); } } public interface IAttachmentGeneratorEntity : IEntity { } [AutoInit] public static class EmailTemplateOperation { public static ConstructSymbol<EmailTemplateEntity>.From<EmailModelEntity> CreateEmailTemplateFromModel; public static ConstructSymbol<EmailTemplateEntity>.Simple Create; public static ExecuteSymbol<EmailTemplateEntity> Save; public static DeleteSymbol<EmailTemplateEntity> Delete; } public enum EmailTemplateMessage { [Description("End date must be higher than start date")] EndDateMustBeHigherThanStartDate, [Description("There are no messages for the template")] ThereAreNoMessagesForTheTemplate, [Description("There must be a message for {0}")] ThereMustBeAMessageFor0, [Description("There's more than one message for the same language")] TheresMoreThanOneMessageForTheSameLanguage, [Description("The text must contain {0} indicating replacement point")] TheTextMustContain0IndicatingReplacementPoint, [Description("Impossible to access {0} because the template has no {1}")] ImpossibleToAccess0BecauseTheTemplateHAsNo1, NewCulture, TokenOrEmailAddressMustBeSet, TokenAndEmailAddressCanNotBeSetAtTheSameTime, [Description("Token must be a {0}")] TokenMustBeA0, ShowPreview, HidePreview } public enum EmailTemplateViewMessage { [Description("Insert message content")] InsertMessageContent, [Description("Insert")] Insert, [Description("Language")] Language } [InTypeScript(true)] public enum EmailTemplateVisibleOn { Single = 1, Multiple = 2, Query = 4 }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Implementation details of CLR Contracts. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { // For better diagnostics, report which assembly is at fault. Walk up stack and // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); Assembly probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; if (caller != thisAssembly) { probablyNotRewritten = caller; break; } } if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; String simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [System.Diagnostics.DebuggerNonUserCode] static void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endregion FailureBehavior } public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Debug.Assert(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } public void SetUnwind() { _unwind = true; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] #if CORERT public // On CoreRT this must be public to support binary serialization with type forwarding. #else internal #endif sealed class ContractException : Exception { private readonly ContractFailureKind _kind; private readonly string _userMessage; private readonly string _condition; public ContractFailureKind Kind { get { return _kind; } } public string Failure { get { return this.Message; } } public string UserMessage { get { return _userMessage; } } public string Condition { get { return _condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; _kind = kind; _userMessage = userMessage; _condition = condition; } private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _kind = (ContractFailureKind)info.GetInt32("Kind"); _userMessage = info.GetString("UserMessage"); _condition = info.GetString("Condition"); } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _kind); info.AddValue("UserMessage", _userMessage); info.AddValue("Condition", _condition); } } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent; private static readonly Object lockObject = new Object(); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); lock (lockObject) { contractFailedEvent += value; } } remove { lock (lockObject) { contractFailedEvent -= value; } } } /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [System.Diagnostics.DebuggerNonUserCode] public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... ContractFailedEventArgs eventArgs = null; // In case of OOM. try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent; if (contractFailedEventLocal != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } } finally { if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else { returnValue = displayMessage; } } return returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { if (string.IsNullOrEmpty(displayMessage)) { displayMessage = GetDisplayMessage(kind, userMessage, conditionText); } System.Diagnostics.Debug.ContractFailure(false, displayMessage, string.Empty, GetResourceNameForFailure(kind)); } private static String GetResourceNameForFailure(ContractFailureKind failureKind) { String resourceName = null; switch (failureKind) { case ContractFailureKind.Assert: resourceName = "AssertionFailed"; break; case ContractFailureKind.Assume: resourceName = "AssumptionFailed"; break; case ContractFailureKind.Precondition: resourceName = "PreconditionFailed"; break; case ContractFailureKind.Postcondition: resourceName = "PostconditionFailed"; break; case ContractFailureKind.Invariant: resourceName = "InvariantFailed"; break; case ContractFailureKind.PostconditionOnException: resourceName = "PostconditionOnExceptionFailed"; break; default: Debug.Fail("Unreachable code"); resourceName = "AssumptionFailed"; break; } return resourceName; } private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { String resourceName = GetResourceNameForFailure(failureKind); // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage; if (!String.IsNullOrEmpty(conditionText)) { resourceName += "_Cnd"; failureMessage = SR.Format(SR.GetResourceString(resourceName), conditionText); } else { failureMessage = SR.GetResourceString(resourceName); } // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } } } // namespace System.Runtime.CompilerServices
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace haxe.xml { public class Parser : global::haxe.lang.HxObject { static Parser() { #line 51 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { global::haxe.ds.StringMap<object> h = new global::haxe.ds.StringMap<object>(); h.@set("lt", "<"); h.@set("gt", ">"); h.@set("amp", "&"); h.@set("quot", "\""); h.@set("apos", "\'"); h.@set("nbsp", new string(((char) (160) ), 1)); global::haxe.xml.Parser.escapes = h; } } public Parser(global::haxe.lang.EmptyObject empty) { unchecked { #line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { } } #line default } public Parser() { unchecked { #line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" global::haxe.xml.Parser.__hx_ctor_haxe_xml_Parser(this); } #line default } public static void __hx_ctor_haxe_xml_Parser(global::haxe.xml.Parser __temp_me48) { unchecked { #line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { } } #line default } public static global::haxe.ds.StringMap<object> escapes; public static global::Xml parse(string str) { unchecked { #line 64 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" global::Xml doc = global::Xml.createDocument(); global::haxe.xml.Parser.doParse(str, new global::haxe.lang.Null<int>(0, true), doc); return doc; } #line default } public static int doParse(string str, global::haxe.lang.Null<int> p, global::Xml parent) { unchecked { #line 70 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_p47 = ( (global::haxe.lang.Runtime.eq((p).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (0) )) : (p.@value) ); global::Xml xml = default(global::Xml); int state = 1; int next = 1; string aname = default(string); int start = 0; int nsubs = 0; int nbrackets = 0; int c = default(int); #line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( ((uint) (__temp_p47) ) < str.Length )) { #line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" c = ((int) (global::haxe.lang.Runtime.toInt(str[__temp_p47])) ); } else { #line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" c = -1; } global::StringBuf buf = new global::StringBuf(); while ( ! ((( c == -1 ))) ) { #line 82 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (state) { case 0: { #line 85 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 10:case 13:case 9:case 32: { #line 88 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { } #line 88 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 93 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = next; continue; } } #line 85 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 1: { #line 97 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 60: { #line 100 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 0; next = 2; #line 99 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 103 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" start = __temp_p47; state = 13; continue; } } #line 97 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 13: { #line 108 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( c == 60 )) { #line 113 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" global::Xml child = global::Xml.createPCData(global::haxe.lang.Runtime.concat(buf.toString(), global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)))); #line 115 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" buf = new global::StringBuf(); parent.addChild(child); nsubs++; state = 0; next = 2; } else { #line 122 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( c == 38 )) { buf.addSub(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)); state = 18; next = 13; start = ( __temp_p47 + 1 ); } } #line 108 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 17: { #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv264 = ( c == 93 ); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv263 = false; #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv262 = false; #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_boolv264) { #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt265 = default(int); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index = ( __temp_p47 + 1 ); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt265 = ( (( ((uint) (index) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index])) )) : (-1) ); } #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv263 = ( __temp_stmt265 == 93 ); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_boolv263) { #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt266 = default(int); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index1 = ( __temp_p47 + 2 ); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt266 = ( (( ((uint) (index1) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index1])) )) : (-1) ); } #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv262 = ( __temp_stmt266 == 62 ); } } #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt261 = ( ( __temp_boolv264 && __temp_boolv263 ) && __temp_boolv262 ); #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_stmt261) { #line 132 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" global::Xml child1 = global::Xml.createCData(global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true))); parent.addChild(child1); nsubs++; __temp_p47 += 2; state = 1; } #line 130 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 2: { #line 139 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 33: { #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt267 = default(int); #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index2 = ( __temp_p47 + 1 ); #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt267 = ( (( ((uint) (index2) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index2])) )) : (-1) ); } #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( __temp_stmt267 == 91 )) { #line 144 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_p47 += 2; if ( ! (string.Equals(global::haxe.lang.StringExt.substr(str, __temp_p47, new global::haxe.lang.Null<int>(6, true)).ToUpper(), "CDATA[")) ) { throw global::haxe.lang.HaxeException.wrap("Expected <![CDATA["); } __temp_p47 += 5; state = 17; start = ( __temp_p47 + 1 ); } else { #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt270 = default(int); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index3 = ( __temp_p47 + 1 ); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt270 = ( (( ((uint) (index3) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index3])) )) : (-1) ); } #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt269 = ( __temp_stmt270 == 68 ); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv271 = false; #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! (__temp_stmt269) ) { #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt272 = default(int); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index4 = ( __temp_p47 + 1 ); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt272 = ( (( ((uint) (index4) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index4])) )) : (-1) ); } #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv271 = ( __temp_stmt272 == 100 ); } #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt268 = ( __temp_stmt269 || __temp_boolv271 ); #line 151 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_stmt268) { #line 153 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! (string.Equals(global::haxe.lang.StringExt.substr(str, ( __temp_p47 + 2 ), new global::haxe.lang.Null<int>(6, true)).ToUpper(), "OCTYPE")) ) { throw global::haxe.lang.HaxeException.wrap("Expected <!DOCTYPE"); } __temp_p47 += 8; state = 16; start = ( __temp_p47 + 1 ); } else { #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt275 = default(int); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index5 = ( __temp_p47 + 1 ); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt275 = ( (( ((uint) (index5) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index5])) )) : (-1) ); } #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt274 = ( __temp_stmt275 != 45 ); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv276 = false; #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! (__temp_stmt274) ) { #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt277 = default(int); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index6 = ( __temp_p47 + 2 ); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt277 = ( (( ((uint) (index6) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index6])) )) : (-1) ); } #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv276 = ( __temp_stmt277 != 45 ); } #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt273 = ( __temp_stmt274 || __temp_boolv276 ); #line 159 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_stmt273) { throw global::haxe.lang.HaxeException.wrap("Expected <!--"); } else { #line 163 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_p47 += 2; state = 15; start = ( __temp_p47 + 1 ); } } } #line 142 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 63: { #line 168 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 14; start = __temp_p47; #line 167 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 47: { #line 171 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( parent == default(global::Xml) )) { throw global::haxe.lang.HaxeException.wrap("Expected node name"); } start = ( __temp_p47 + 1 ); state = 0; next = 10; #line 170 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 177 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 3; start = __temp_p47; continue; } } #line 139 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 3: { #line 182 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! ((( ( ( ( ( ( ( ( c >= 97 ) && ( c <= 122 ) ) || ( ( c >= 65 ) && ( c <= 90 ) ) ) || ( ( c >= 48 ) && ( c <= 57 ) ) ) || ( c == 58 ) ) || ( c == 46 ) ) || ( c == 95 ) ) || ( c == 45 ) ))) ) { #line 184 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( __temp_p47 == start )) { throw global::haxe.lang.HaxeException.wrap("Expected node name"); } xml = global::Xml.createElement(global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true))); parent.addChild(xml); state = 0; next = 4; continue; } #line 182 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 4: { #line 193 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 47: { #line 196 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 11; nsubs++; #line 195 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 62: { #line 199 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 9; nsubs++; #line 198 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 202 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 5; start = __temp_p47; continue; } } #line 193 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 5: { #line 207 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! ((( ( ( ( ( ( ( ( c >= 97 ) && ( c <= 122 ) ) || ( ( c >= 65 ) && ( c <= 90 ) ) ) || ( ( c >= 48 ) && ( c <= 57 ) ) ) || ( c == 58 ) ) || ( c == 46 ) ) || ( c == 95 ) ) || ( c == 45 ) ))) ) { #line 209 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" string tmp = default(string); if (( start == __temp_p47 )) { throw global::haxe.lang.HaxeException.wrap("Expected attribute name"); } tmp = global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)); aname = tmp; if (xml.exists(aname)) { throw global::haxe.lang.HaxeException.wrap("Duplicate attribute"); } state = 0; next = 6; continue; } #line 207 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 6: { #line 221 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 61: { #line 224 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 0; next = 7; #line 223 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 227 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" throw global::haxe.lang.HaxeException.wrap("Expected ="); } } #line 221 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 7: { #line 230 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 34:case 39: { #line 233 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 8; start = __temp_p47; #line 232 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 236 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" throw global::haxe.lang.HaxeException.wrap("Expected \""); } } #line 230 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 8: { #line 239 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( c == (( (( ((uint) (start) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[start])) )) : (-1) )) )) { #line 241 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" string val = global::haxe.lang.StringExt.substr(str, ( start + 1 ), new global::haxe.lang.Null<int>(( ( __temp_p47 - start ) - 1 ), true)); xml.@set(aname, val); state = 0; next = 4; } #line 239 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 9: { #line 247 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_p47 = global::haxe.xml.Parser.doParse(str, new global::haxe.lang.Null<int>(__temp_p47, true), xml); start = __temp_p47; state = 1; #line 246 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 11: { #line 251 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 62: { #line 254 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 1; #line 254 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } default: { #line 256 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" throw global::haxe.lang.HaxeException.wrap("Expected >"); } } #line 251 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 12: { #line 259 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" switch (c) { case 62: { #line 262 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( nsubs == 0 )) { parent.addChild(global::Xml.createPCData("")); } return __temp_p47; } default: { #line 266 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" throw global::haxe.lang.HaxeException.wrap("Expected >"); } } } case 10: { #line 269 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if ( ! ((( ( ( ( ( ( ( ( c >= 97 ) && ( c <= 122 ) ) || ( ( c >= 65 ) && ( c <= 90 ) ) ) || ( ( c >= 48 ) && ( c <= 57 ) ) ) || ( c == 58 ) ) || ( c == 46 ) ) || ( c == 95 ) ) || ( c == 45 ) ))) ) { #line 271 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( start == __temp_p47 )) { throw global::haxe.lang.HaxeException.wrap("Expected node name"); } #line 274 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" string v = global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)); if ( ! (string.Equals(v, parent._get_nodeName())) ) { throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat("Expected </", parent._get_nodeName()), ">")); } #line 278 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" state = 0; next = 12; continue; } #line 269 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 15: { #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv281 = ( c == 45 ); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv280 = false; #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv279 = false; #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_boolv281) { #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt282 = default(int); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index7 = ( __temp_p47 + 1 ); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt282 = ( (( ((uint) (index7) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index7])) )) : (-1) ); } #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv280 = ( __temp_stmt282 == 45 ); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_boolv280) { #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt283 = default(int); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index8 = ( __temp_p47 + 2 ); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt283 = ( (( ((uint) (index8) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index8])) )) : (-1) ); } #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv279 = ( __temp_stmt283 == 62 ); } } #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt278 = ( ( __temp_boolv281 && __temp_boolv280 ) && __temp_boolv279 ); #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_stmt278) { #line 285 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" parent.addChild(global::Xml.createComment(global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)))); __temp_p47 += 2; state = 1; } #line 283 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 16: { #line 290 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( c == 91 )) { nbrackets++; } else { if (( c == 93 )) { nbrackets--; } else { if (( ( c == 62 ) && ( nbrackets == 0 ) )) { #line 296 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" parent.addChild(global::Xml.createDocType(global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)))); state = 1; } } } #line 290 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 14: { #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv286 = ( c == 63 ); #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_boolv285 = false; #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_boolv286) { #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int __temp_stmt287 = default(int); #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index9 = ( __temp_p47 + 1 ); #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_stmt287 = ( (( ((uint) (index9) ) < str.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(str[index9])) )) : (-1) ); } #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_boolv285 = ( __temp_stmt287 == 62 ); } #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" bool __temp_stmt284 = ( __temp_boolv286 && __temp_boolv285 ); #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (__temp_stmt284) { #line 302 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" __temp_p47++; string str1 = global::haxe.lang.StringExt.substr(str, ( start + 1 ), new global::haxe.lang.Null<int>(( ( __temp_p47 - start ) - 2 ), true)); parent.addChild(global::Xml.createProcessingInstruction(str1)); state = 1; } #line 300 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } case 18: { #line 308 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( c == 59 )) { #line 310 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" string s = global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true)); if (( (( (( ((uint) (0) ) < s.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(s[0])) )) : (-1) )) == 35 )) { global::haxe.lang.Null<int> i = default(global::haxe.lang.Null<int>); #line 312 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( (( (( ((uint) (1) ) < s.Length )) ? (((int) (global::haxe.lang.Runtime.toInt(s[1])) )) : (-1) )) == 120 )) { i = new global::haxe.lang.Null<int>(global::Std.parseInt(global::haxe.lang.Runtime.concat("0", global::haxe.lang.StringExt.substr(s, 1, new global::haxe.lang.Null<int>(( s.Length - 1 ), true)))).@value, true); } else { i = new global::haxe.lang.Null<int>(global::Std.parseInt(global::haxe.lang.StringExt.substr(s, 1, new global::haxe.lang.Null<int>(( s.Length - 1 ), true))).@value, true); } { #line 315 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" object x = new string(((char) (i.@value) ), 1); #line 315 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" buf.b.Append(((object) (global::Std.@string(x)) )); } } else { if ( ! (global::haxe.xml.Parser.escapes.exists(s)) ) { buf.b.Append(((object) (global::Std.@string(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat("&", s), ";"))) )); } else { #line 319 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" object x1 = global::haxe.lang.Runtime.toString(global::haxe.xml.Parser.escapes.@get(s).@value); #line 319 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" buf.b.Append(((object) (global::Std.@string(x1)) )); } } start = ( __temp_p47 + 1 ); state = next; } #line 308 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" break; } } #line 324 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" { #line 324 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" int index10 = ++ __temp_p47; #line 324 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( ((uint) (index10) ) < str.Length )) { #line 324 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" c = ((int) (global::haxe.lang.Runtime.toInt(str[index10])) ); } else { #line 324 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" c = -1; } } } #line 327 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( state == 1 )) { #line 329 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" start = __temp_p47; state = 13; } #line 333 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( state == 13 )) { #line 335 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" if (( ( __temp_p47 != start ) || ( nsubs == 0 ) )) { parent.addChild(global::Xml.createPCData(global::haxe.lang.Runtime.concat(buf.toString(), global::haxe.lang.StringExt.substr(str, start, new global::haxe.lang.Null<int>(( __temp_p47 - start ), true))))); } return __temp_p47; } #line 340 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" throw global::haxe.lang.HaxeException.wrap("Unexpected end"); } #line default } public static new object __hx_createEmpty() { unchecked { #line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" return new global::haxe.xml.Parser(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 49 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Parser.hx" return new global::haxe.xml.Parser(); } #line default } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Runtime_CompilerServices_AsyncTaskMethodBuilder_1_ILTypeInstance_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>); args = new Type[]{}; method = type.GetMethod("Create", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Create_0); Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>(); List<MethodInfo> lst = null; foreach(var m in type.GetMethods()) { if(m.IsGenericMethodDefinition) { if (!genericMethods.TryGetValue(m.Name, out lst)) { lst = new List<MethodInfo>(); genericMethods[m.Name] = lst; } lst.Add(m); } } args = new Type[]{typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("Start", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, Start_1); break; } } } args = new Type[]{}; method = type.GetMethod("get_Task", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Task_2); args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_3); break; } } } args = new Type[]{typeof(System.Exception)}; method = type.GetMethod("SetException", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetException_4); args = new Type[]{typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance)}; method = type.GetMethod("SetResult", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetResult_5); args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_6); break; } } } app.RegisterCLRCreateDefaultInstance(type, () => new System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>()); } static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* Create_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>.Create(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* Start_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.Start<Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* get_Task_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.Task; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* AwaitUnsafeOnCompleted_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance> @awaiter = (System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* SetException_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Exception @exception = (System.Exception)typeof(System.Exception).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.SetException(@exception); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* SetResult_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ILRuntime.Runtime.Intepreter.ILTypeInstance @result = (ILRuntime.Runtime.Intepreter.ILTypeInstance)typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.SetResult(@result); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* AwaitUnsafeOnCompleted_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Runtime.CompilerServices.TaskAwaiter @awaiter = (System.Runtime.CompilerServices.TaskAwaiter)typeof(System.Runtime.CompilerServices.TaskAwaiter).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } } }
/* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ************************************************************************* */ using System.Text; using HANDLE = System.IntPtr; using i16 = System.Int16; using sqlite3_int64 = System.Int64; using u32 = System.UInt32; namespace Community.CsharpSqlite { using DbPage = Sqlite3.PgHdr; using sqlite3_pcache = Sqlite3.PCache1; using sqlite3_stmt = Sqlite3.Vdbe; using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { public delegate void dxAuth(object pAuthArg, int b, string c, string d, string e, string f); public delegate int dxBusy(object pBtShared, int iValue); public delegate void dxFreeAux(object pAuxArg); public delegate int dxCallback(object pCallbackArg, sqlite3_int64 argc, object p2, object p3); public delegate void dxalarmCallback(object pNotUsed, sqlite3_int64 iNotUsed, int size); public delegate void dxCollNeeded(object pCollNeededArg, sqlite3 db, int eTextRep, string collationName); public delegate int dxCommitCallback(object pCommitArg); public delegate int dxCompare(object pCompareArg, int size1, string Key1, int size2, string Key2); public delegate bool dxCompare4(string Key1, int size1, string Key2, int size2); public delegate void dxDel(ref string pDelArg); // needs ref public delegate void dxDelCollSeq(ref object pDelArg); // needs ref public delegate void dxLog(object pLogArg, int i, string msg); public delegate void dxLogcallback(object pCallbackArg, int argc, string p2); public delegate void dxProfile(object pProfileArg, string msg, sqlite3_int64 time); public delegate int dxProgress(object pProgressArg); public delegate void dxRollbackCallback(object pRollbackArg); public delegate void dxTrace(object pTraceArg, string msg); public delegate void dxUpdateCallback(object pUpdateArg, int b, string c, string d, sqlite3_int64 e); public delegate int dxWalCallback(object pWalArg, sqlite3 db, string zDb, int nEntry); /* * FUNCTIONS * */ public delegate void dxFunc(sqlite3_context ctx, int intValue, sqlite3_value[] value); public delegate void dxStep(sqlite3_context ctx, int intValue, sqlite3_value[] value); public delegate void dxFinal(sqlite3_context ctx); public delegate void dxFDestroy(object pArg); // public delegate string dxColname(sqlite3_value pVal); public delegate int dxFuncBtree(Btree p); public delegate int dxExprTreeFunction(ref int pArg, Expr pExpr); public delegate int dxExprTreeFunction_NC(NameContext pArg, ref Expr pExpr); public delegate int dxExprTreeFunction_OBJ(object pArg, Expr pExpr); /* VFS Delegates */ public delegate int dxClose(sqlite3_file File_ID); public delegate int dxCheckReservedLock(sqlite3_file File_ID, ref int pRes); public delegate int dxDeviceCharacteristics(sqlite3_file File_ID); public delegate int dxFileControl(sqlite3_file File_ID, int op, ref sqlite3_int64 pArgs); public delegate int dxFileSize(sqlite3_file File_ID, ref long size); public delegate int dxLock(sqlite3_file File_ID, int locktype); public delegate int dxRead(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset); public delegate int dxSectorSize(sqlite3_file File_ID); public delegate int dxSync(sqlite3_file File_ID, int flags); public delegate int dxTruncate(sqlite3_file File_ID, sqlite3_int64 size); public delegate int dxUnlock(sqlite3_file File_ID, int locktype); public delegate int dxWrite(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset); public delegate int dxShmMap(sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile); public delegate int dxShmLock(sqlite3_file File_ID, int offset, int n, int flags); public delegate void dxShmBarrier(sqlite3_file File_ID); public delegate int dxShmUnmap(sqlite3_file File_ID, int deleteFlag); /* sqlite_vfs Delegates */ public delegate int dxOpen(sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags); public delegate int dxDelete(sqlite3_vfs vfs, string zName, int syncDir); public delegate int dxAccess(sqlite3_vfs vfs, string zName, int flags, out int pResOut); public delegate int dxFullPathname(sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut); public delegate HANDLE dxDlOpen(sqlite3_vfs vfs, string zFilename); public delegate int dxDlError(sqlite3_vfs vfs, int nByte, string zErrMsg); public delegate HANDLE dxDlSym(sqlite3_vfs vfs, HANDLE data, string zSymbol); public delegate int dxDlClose(sqlite3_vfs vfs, HANDLE data); public delegate int dxRandomness(sqlite3_vfs vfs, int nByte, byte[] buffer); public delegate int dxSleep(sqlite3_vfs vfs, int microseconds); public delegate int dxCurrentTime(sqlite3_vfs vfs, ref double currenttime); public delegate int dxGetLastError(sqlite3_vfs pVfs, int nBuf, ref string zBuf); public delegate int dxCurrentTimeInt64(sqlite3_vfs pVfs, ref sqlite3_int64 pTime); public delegate int dxSetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr); public delegate int dxGetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr); public delegate int dxNextSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr); /* * Pager Delegates */ public delegate void dxDestructor(DbPage dbPage); /* Call this routine when freeing pages */ public delegate int dxBusyHandler(object pBusyHandlerArg); public delegate void dxReiniter(DbPage dbPage); /* Call this routine when reloading pages */ public delegate void dxFreeSchema(Schema schema); #if SQLITE_HAS_CODEC public delegate byte[] dxCodec(codec_ctx pCodec, byte[] D, uint pageNumber, int X); //void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ public delegate void dxCodecSizeChng(codec_ctx pCodec, int pageSize, i16 nReserve); //void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ public delegate void dxCodecFree(ref codec_ctx pCodec); //void (*xCodecFree)(void); /* Destructor for the codec */ #endif //Module public delegate void dxDestroy(ref PgHdr pDestroyArg); public delegate int dxStress(object obj, PgHdr pPhHdr); //sqlite3_module public delegate int smdxCreateConnect(sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError); public delegate int smdxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndex); public delegate int smdxDisconnect(ref object pVTab); public delegate int smdxDestroy(ref object pVTab); public delegate int smdxOpen(sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor); public delegate int smdxClose(ref sqlite3_vtab_cursor pCursor); public delegate int smdxFilter(sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv); public delegate int smdxNext(sqlite3_vtab_cursor pCursor); public delegate int smdxEof(sqlite3_vtab_cursor pCursor); public delegate int smdxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3); public delegate int smdxRowid(sqlite3_vtab_cursor pCursor, out sqlite3_int64 pRowid); public delegate int smdxUpdate(sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3); public delegate int smdxFunction(sqlite3_vtab pVTab); public delegate int smdxFindFunction(sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg); public delegate int smdxRename(sqlite3_vtab pVtab, string zNew); public delegate int smdxFunctionArg(sqlite3_vtab pVTab, int nArg); //AutoExtention public delegate int dxInit(sqlite3 db, ref string zMessage, sqlite3_api_routines sar); #if !SQLITE_OMIT_VIRTUALTABLE public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); public delegate int dmxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndexInfo); public delegate int dmxDisconnect(sqlite3_vtab pVTab); public delegate int dmxDestroy(sqlite3_vtab pVTab); public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor); public delegate int dmxClose(sqlite3_vtab_cursor pCursor); public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv); public delegate int dmxNext(sqlite3_vtab_cursor pCursor); public delegate int dmxEof(sqlite3_vtab_cursor pCursor); public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3); public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid); public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4); public delegate int dmxBegin(sqlite3_vtab pVTab); public delegate int dmxSync(sqlite3_vtab pVTab); public delegate int dmxCommit(sqlite3_vtab pVTab); public delegate int dmxRollback(sqlite3_vtab pVTab); public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName); public delegate int dmxRename(sqlite3_vtab pVtab, string zNew); #endif //Faults public delegate void void_function(); //Mem Methods public delegate int dxMemInit(object o); public delegate void dxMemShutdown(object o); public delegate byte[] dxMalloc(int nSize); public delegate int[] dxMallocInt(int nSize); public delegate Mem dxMallocMem(Mem pMem); public delegate void dxFree(ref byte[] pOld); public delegate void dxFreeInt(ref int[] pOld); public delegate void dxFreeMem(ref Mem pOld); public delegate byte[] dxRealloc(byte[] pOld, int nSize); public delegate int dxSize(byte[] pArray); public delegate int dxRoundup(int nSize); //Mutex Methods public delegate int dxMutexInit(); public delegate int dxMutexEnd(); public delegate sqlite3_mutex dxMutexAlloc(int iNumber); public delegate void dxMutexFree(sqlite3_mutex sm); public delegate void dxMutexEnter(sqlite3_mutex sm); public delegate int dxMutexTry(sqlite3_mutex sm); public delegate void dxMutexLeave(sqlite3_mutex sm); public delegate bool dxMutexHeld(sqlite3_mutex sm); public delegate bool dxMutexNotheld(sqlite3_mutex sm); public delegate object dxColumn(sqlite3_stmt pStmt, int i); public delegate int dxColumn_I(sqlite3_stmt pStmt, int i); // Walker Methods public delegate int dxExprCallback(Walker W, ref Expr E); /* Callback for expressions */ public delegate int dxSelectCallback(Walker W, Select S); /* Callback for SELECTs */ // pcache Methods public delegate int dxPC_Init(object NotUsed); public delegate void dxPC_Shutdown(object NotUsed); public delegate sqlite3_pcache dxPC_Create(int szPage, bool bPurgeable); public delegate void dxPC_Cachesize(sqlite3_pcache pCache, int nCachesize); public delegate int dxPC_Pagecount(sqlite3_pcache pCache); public delegate PgHdr dxPC_Fetch(sqlite3_pcache pCache, u32 key, int createFlag); public delegate void dxPC_Unpin(sqlite3_pcache pCache, PgHdr p2, bool discard); public delegate void dxPC_Rekey(sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey); public delegate void dxPC_Truncate(sqlite3_pcache pCache, u32 iLimit); public delegate void dxPC_Destroy(ref sqlite3_pcache pCache); public delegate void dxIter(PgHdr p); #if NET_35 || NET_40 //API Simplifications -- Actions public static Action<sqlite3_context, String, Int32, dxDel> ResultBlob = sqlite3_result_blob; public static Action<sqlite3_context, Double> ResultDouble = sqlite3_result_double; public static Action<sqlite3_context, String, Int32> ResultError = sqlite3_result_error; public static Action<sqlite3_context, Int32> ResultErrorCode = sqlite3_result_error_code; public static Action<sqlite3_context> ResultErrorNoMem = sqlite3_result_error_nomem; public static Action<sqlite3_context> ResultErrorTooBig = sqlite3_result_error_toobig; public static Action<sqlite3_context, Int32> ResultInt = sqlite3_result_int; public static Action<sqlite3_context, Int64> ResultInt64 = sqlite3_result_int64; public static Action<sqlite3_context> ResultNull = sqlite3_result_null; public static Action<sqlite3_context, String, Int32, dxDel> ResultText = sqlite3_result_text; public static Action<sqlite3_context, String, Int32, Int32, dxDel> ResultText_Offset = sqlite3_result_text; public static Action<sqlite3_context, sqlite3_value> ResultValue = sqlite3_result_value; public static Action<sqlite3_context, Int32> ResultZeroblob = sqlite3_result_zeroblob; public static Action<sqlite3_context, Int32, String> SetAuxdata = sqlite3_set_auxdata; //API Simplifications -- Functions public delegate Int32 FinalizeDelegate( sqlite3_stmt pStmt ); public static FinalizeDelegate Finalize = sqlite3_finalize; public static Func<sqlite3_stmt, Int32> ClearBindings = sqlite3_clear_bindings; public static Func<sqlite3_stmt, Int32, Byte[]> ColumnBlob = sqlite3_column_blob; public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes = sqlite3_column_bytes; public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes16 = sqlite3_column_bytes16; public static Func<sqlite3_stmt, Int32> ColumnCount = sqlite3_column_count; public static Func<sqlite3_stmt, Int32, String> ColumnDecltype = sqlite3_column_decltype; public static Func<sqlite3_stmt, Int32, Double> ColumnDouble = sqlite3_column_double; public static Func<sqlite3_stmt, Int32, Int32> ColumnInt = sqlite3_column_int; public static Func<sqlite3_stmt, Int32, Int64> ColumnInt64 = sqlite3_column_int64; public static Func<sqlite3_stmt, Int32, String> ColumnName = sqlite3_column_name; public static Func<sqlite3_stmt, Int32, String> ColumnText = sqlite3_column_text; public static Func<sqlite3_stmt, Int32, Int32> ColumnType = sqlite3_column_type; public static Func<sqlite3_stmt, Int32, sqlite3_value> ColumnValue = sqlite3_column_value; public static Func<sqlite3_stmt, Int32> DataCount = sqlite3_data_count; public static Func<sqlite3_stmt, Int32> Reset = sqlite3_reset; public static Func<sqlite3_stmt, Int32> Step = sqlite3_step; public static Func<sqlite3_stmt, Int32, Byte[], Int32, dxDel, Int32> BindBlob = sqlite3_bind_blob; public static Func<sqlite3_stmt, Int32, Double, Int32> BindDouble = sqlite3_bind_double; public static Func<sqlite3_stmt, Int32, Int32, Int32> BindInt = sqlite3_bind_int; public static Func<sqlite3_stmt, Int32, Int64, Int32> BindInt64 = sqlite3_bind_int64; public static Func<sqlite3_stmt, Int32, Int32> BindNull = sqlite3_bind_null; public static Func<sqlite3_stmt, Int32> BindParameterCount = sqlite3_bind_parameter_count; public static Func<sqlite3_stmt, String, Int32> BindParameterIndex = sqlite3_bind_parameter_index; public static Func<sqlite3_stmt, Int32, String> BindParameterName = sqlite3_bind_parameter_name; public static Func<sqlite3_stmt, Int32, String, Int32, dxDel, Int32> BindText = sqlite3_bind_text; public static Func<sqlite3_stmt, Int32, sqlite3_value, Int32> BindValue = sqlite3_bind_value; public static Func<sqlite3_stmt, Int32, Int32, Int32> BindZeroblob = sqlite3_bind_zeroblob; public delegate Int32 OpenDelegate( string zFilename, out sqlite3 ppDb ); public static Func<sqlite3, Int32> Close = sqlite3_close; public static Func<sqlite3_stmt, sqlite3> DbHandle = sqlite3_db_handle; public static Func<sqlite3, String> Errmsg = sqlite3_errmsg; public static OpenDelegate Open = sqlite3_open; public static Func<sqlite3, sqlite3_stmt, sqlite3_stmt> NextStmt = sqlite3_next_stmt; public static Func<Int32> Shutdown = sqlite3_shutdown; public static Func<sqlite3_stmt, Int32, Int32, Int32> StmtStatus = sqlite3_stmt_status; public delegate Int32 PrepareDelegate( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail ); public delegate Int32 PrepareDelegateNoTail( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy ); public static PrepareDelegate Prepare = sqlite3_prepare; public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2; public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2; public static Func<sqlite3_context, Int32, Mem> AggregateContext = sqlite3_aggregate_context; public static Func<sqlite3_context, Int32, Object> GetAuxdata = sqlite3_get_auxdata; public static Func<sqlite3_context, sqlite3> ContextDbHandle = sqlite3_context_db_handle; public static Func<sqlite3_context, Object> UserData = sqlite3_user_data; public static Func<sqlite3_value, Byte[]> ValueBlob = sqlite3_value_blob; public static Func<sqlite3_value, Int32> ValueBytes = sqlite3_value_bytes; public static Func<sqlite3_value, Int32> ValueBytes16 = sqlite3_value_bytes16; public static Func<sqlite3_value, Double> ValueDouble = sqlite3_value_double; public static Func<sqlite3_value, Int32> ValueInt = sqlite3_value_int; public static Func<sqlite3_value, Int64> ValueInt64 = sqlite3_value_int64; public static Func<sqlite3_value, String> ValueText = sqlite3_value_text; public static Func<sqlite3_value, Int32> ValueType = sqlite3_value_type; #endif } } #if( NET_35 && !NET_40) || WINDOWS_PHONE namespace System { // Summary: // Encapsulates a method that has four parameters and does not return a value. // // Parameters: // arg1: // The first parameter of the method that this delegate encapsulates. // // arg2: // The second parameter of the method that this delegate encapsulates. // // arg3: // The third parameter of the method that this delegate encapsulates. // // arg4: // The fourth parameter of the method that this delegate encapsulates. // // arg5: // The fifth parameter of the method that this delegate encapsulates. // // Type parameters: // T1: // The type of the first parameter of the method that this delegate encapsulates. // // T2: // The type of the second parameter of the method that this delegate encapsulates. // // T3: // The type of the third parameter of the method that this delegate encapsulates. // // T4: // The type of the fourth parameter of the method that this delegate encapsulates. // // T5: // The type of the fifth parameter of the method that this delegate encapsulates. public delegate void Action<T1, T2, T3, T4, T5>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 ); // Summary: // Encapsulates a method that has three parameters and returns a value of the // type specified by the TResult parameter. // // Parameters: // arg1: // The first parameter of the method that this delegate encapsulates. // // arg2: // The second parameter of the method that this delegate encapsulates. // // arg3: // The third parameter of the method that this delegate encapsulates. // // arg4: // The fourth parameter of the method that this delegate encapsulates. // // arg5: // The fifth parameter of the method that this delegate encapsulates. // // Type parameters: // T1: // The type of the first parameter of the method that this delegate encapsulates. // // T2: // The type of the second parameter of the method that this delegate encapsulates. // // T3: // The type of the third parameter of the method that this delegate encapsulates. // // T4: // The type of the fourth parameter of the method that this delegate encapsulates. // // T5: // The type of the fifth parameter of the method that this delegate encapsulates. // // TResult: // The type of the return value of the method that this delegate encapsulates. // // Returns: // The return value of the method that this delegate encapsulates. public delegate TResult Func<T1, T2, T3, T4, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4 ); public delegate TResult Func<T1, T2, T3, T4, T5, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 ); } #endif
/// /// Copyright (c) 2004 Thong Nguyen ([email protected]) /// using System; using System.Threading; namespace ThreadsDemo { /// <summary> /// The state of a developer. /// </summary> public enum DeveloperState { Thinking, Waiting, Coding } /// <summary> /// Abstract representation of a developer and "coding developer" algorithm. /// </summary> public abstract class Developer { /// <summary> /// Raised when the developer's state changes. /// </summary> public event EventHandler StateChanged; /// <summary> /// Thread the developer runs on. /// </summary> private Thread thread; /// <summary> /// The controller the developer listens to. /// </summary> protected DeveloperController m_controller; /// <summary> /// Name of the developer. /// </summary> public virtual string Name { get { return m_Name; } set { m_Name = value; } } private string m_Name; /// <summary> /// Gets the count of how many times the developer has entered the Coding state. /// </summary> public virtual int CodingCount { get { return m_CodingCount; } } private int m_CodingCount; /// <summary> /// Gets the developer's state. /// </summary> public virtual DeveloperState State { get { return m_state; } } private DeveloperState m_state; /// <summary> /// Sets the developer's state. /// </summary> /// <param name="state">The new state</param> protected virtual void SetState(DeveloperState state) { lock (this) { m_state = state; if (state == DeveloperState.Coding) { m_CodingCount++; } OnStateChanged(); } } /// <summary> /// Gets a description of the developer. /// </summary> public override string ToString() { return String.Format("{0} ({1}) [{2}]", Name, State, CodingCount); } /// <summary> /// Raises a StateChanged event. /// </summary> protected virtual void OnStateChanged() { if (StateChanged != null) { StateChanged(this, EventArgs.Empty); } } /// <summary> /// The developer to the immediate left of the current developer. /// </summary> public Developer Left { get { return m_Left; } set { m_Left = value; } } protected Developer m_Left; /// <summary> /// The developer to the immediate right of the current developer. /// </summary> public Developer Right { get { return m_Right; } set { m_Right = value; } } protected Developer m_Right; /// <summary> /// Gets/Sets the number of milliseconds to a developer sepnds coding. /// </summary> public virtual int CodingDelay { get { return m_CodingDelay; } set { m_CodingDelay = value; } } private int m_CodingDelay; /// <summary> /// Gets/Sets the number of milliseconds to a developer spends thinking. /// </summary> public virtual int ThinkingDelay { get { return m_ThinkingDelay; } set { m_ThinkingDelay = value; } } private int m_ThinkingDelay; /// <summary> /// Gets/Sets whether the coding/thinking delay should be a random /// number within the range or the exact delay specified. /// </summary> public virtual bool UseRandomDelay { get { return m_UseRandomDelay; } set { m_UseRandomDelay = value; } } private bool m_UseRandomDelay; /// <summary> /// Implementers should return when both the keyboard & mouse have been picked up. /// </summary> protected abstract void Pickup(); /// <summary> /// Implementers should release both the keyboard & mouse and return. /// </summary> protected abstract void Putdown(); /// <summary> /// Construct a new developer. /// </summary> protected Developer(string name, Developer left, Developer right, DeveloperController controller) { m_Left = left; m_Right = right; m_controller = controller; m_Name = name; m_CodingDelay = 1000; m_ThinkingDelay = 1000; m_CodingCount = 0; m_UseRandomDelay = true; m_controller.Start += new EventHandler(Controller_Start); SetState(DeveloperState.Thinking); } /// <summary> /// Invoked by the controller when we should start. /// </summary> protected virtual void Controller_Start(object sender, EventArgs eventArgs) { if (thread == null) { thread = new Thread(new ThreadStart(Run)); thread.IsBackground = true; thread.Start(); } } /// <summary> /// Thread run procedure. /// </summary> private void Run() { Random random = new Random(); for (;;) { // Try to aquire the keyboard & mouse. Pickup(); // Developer is coding here.. if (UseRandomDelay) { Thread.Sleep(random.Next(CodingDelay)); } else { Thread.Sleep(CodingDelay); } // Put down keyboard and mouse Putdown(); // Developer is thinking here.. if (m_UseRandomDelay) { Thread.Sleep(random.Next(ThinkingDelay)); } else { Thread.Sleep(ThinkingDelay); } } } } }
// ------------------------------------------------------------------------------ // 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. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt 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 CalendarRequest. /// </summary> public partial class CalendarRequest : BaseRequest, ICalendarRequest { /// <summary> /// Constructs a new CalendarRequest. /// </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 CalendarRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Calendar using POST. /// </summary> /// <param name="calendarToCreate">The Calendar to create.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> CreateAsync(Calendar calendarToCreate) { return this.CreateAsync(calendarToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Calendar using POST. /// </summary> /// <param name="calendarToCreate">The Calendar to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> CreateAsync(Calendar calendarToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Calendar>(calendarToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Calendar. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Calendar. /// </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<Calendar>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Calendar. /// </summary> /// <returns>The Calendar.</returns> public System.Threading.Tasks.Task<Calendar> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Calendar. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Calendar>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Calendar using PATCH. /// </summary> /// <param name="calendarToUpdate">The Calendar to update.</param> /// <returns>The updated Calendar.</returns> public System.Threading.Tasks.Task<Calendar> UpdateAsync(Calendar calendarToUpdate) { return this.UpdateAsync(calendarToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Calendar using PATCH. /// </summary> /// <param name="calendarToUpdate">The Calendar to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> UpdateAsync(Calendar calendarToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Calendar>(calendarToUpdate, 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 ICalendarRequest 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 ICalendarRequest Expand(Expression<Func<Calendar, 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 ICalendarRequest 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 ICalendarRequest Select(Expression<Func<Calendar, 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="calendarToInitialize">The <see cref="Calendar"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Calendar calendarToInitialize) { if (calendarToInitialize != null && calendarToInitialize.AdditionalData != null) { if (calendarToInitialize.Events != null && calendarToInitialize.Events.CurrentPage != null) { calendarToInitialize.Events.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.Events.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (calendarToInitialize.CalendarView != null && calendarToInitialize.CalendarView.CurrentPage != null) { calendarToInitialize.CalendarView.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.CalendarView.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (calendarToInitialize.SingleValueExtendedProperties != null && calendarToInitialize.SingleValueExtendedProperties.CurrentPage != null) { calendarToInitialize.SingleValueExtendedProperties.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.SingleValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (calendarToInitialize.MultiValueExtendedProperties != null && calendarToInitialize.MultiValueExtendedProperties.CurrentPage != null) { calendarToInitialize.MultiValueExtendedProperties.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.MultiValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// 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.Globalization; using Xunit; public static class DecimalTests { [Fact] public static void TestEquals() { // Boolean Decimal.Equals(Decimal) Assert.True(Decimal.Zero.Equals(Decimal.Zero)); Assert.False(Decimal.Zero.Equals(Decimal.One)); Assert.True(Decimal.MaxValue.Equals(Decimal.MaxValue)); Assert.True(Decimal.MinValue.Equals(Decimal.MinValue)); Assert.False(Decimal.MaxValue.Equals(Decimal.MinValue)); Assert.False(Decimal.MinValue.Equals(Decimal.MaxValue)); } [Fact] public static void TestEqualsDecDec() { // Boolean Decimal.Equals(Decimal, Decimal) Assert.True(Decimal.Equals(Decimal.Zero, Decimal.Zero)); Assert.False(Decimal.Equals(Decimal.Zero, Decimal.One)); Assert.True(Decimal.Equals(Decimal.MaxValue, Decimal.MaxValue)); Assert.True(Decimal.Equals(Decimal.MinValue, Decimal.MinValue)); Assert.False(Decimal.Equals(Decimal.MinValue, Decimal.MaxValue)); Assert.False(Decimal.Equals(Decimal.MaxValue, Decimal.MinValue)); } [Fact] public static void TestEqualsObj() { // Boolean Decimal.Equals(Object) Assert.True(Decimal.Zero.Equals((object)Decimal.Zero)); Assert.False(Decimal.Zero.Equals((object)Decimal.One)); Assert.True(Decimal.MaxValue.Equals((object)Decimal.MaxValue)); Assert.True(Decimal.MinValue.Equals((object)Decimal.MinValue)); Assert.False(Decimal.MinValue.Equals((object)Decimal.MaxValue)); Assert.False(Decimal.MaxValue.Equals((object)Decimal.MinValue)); Assert.False(Decimal.One.Equals(null)); Assert.False(Decimal.One.Equals("one")); Assert.False(Decimal.One.Equals((object)1)); } [Fact] public static void Testop_Equality() { // Boolean Decimal.op_Equality(Decimal, Decimal) Assert.True(Decimal.Zero == Decimal.Zero); Assert.False(Decimal.Zero == Decimal.One); Assert.True(Decimal.MaxValue == Decimal.MaxValue); Assert.True(Decimal.MinValue == Decimal.MinValue); Assert.False(Decimal.MinValue == Decimal.MaxValue); Assert.False(Decimal.MaxValue == Decimal.MinValue); } [Fact] public static void Testop_GreaterThan() { // Boolean Decimal.op_GreaterThan(Decimal, Decimal) Assert.False(Decimal.Zero > Decimal.Zero); Assert.False(Decimal.Zero > Decimal.One); Assert.True(Decimal.One > Decimal.Zero); Assert.False(Decimal.MaxValue > Decimal.MaxValue); Assert.False(Decimal.MinValue > Decimal.MinValue); Assert.False(Decimal.MinValue > Decimal.MaxValue); Assert.True(Decimal.MaxValue > Decimal.MinValue); } [Fact] public static void Testop_GreaterThanOrEqual() { // Boolean Decimal.op_GreaterThanOrEqual(Decimal, Decimal) Assert.True(Decimal.Zero >= Decimal.Zero); Assert.False(Decimal.Zero >= Decimal.One); Assert.True(Decimal.One >= Decimal.Zero); Assert.True(Decimal.MaxValue >= Decimal.MaxValue); Assert.True(Decimal.MinValue >= Decimal.MinValue); Assert.False(Decimal.MinValue >= Decimal.MaxValue); Assert.True(Decimal.MaxValue >= Decimal.MinValue); } [Fact] public static void Testop_Inequality() { // Boolean Decimal.op_Inequality(Decimal, Decimal) Assert.False(Decimal.Zero != Decimal.Zero); Assert.True(Decimal.Zero != Decimal.One); Assert.True(Decimal.One != Decimal.Zero); Assert.False(Decimal.MaxValue != Decimal.MaxValue); Assert.False(Decimal.MinValue != Decimal.MinValue); Assert.True(Decimal.MinValue != Decimal.MaxValue); Assert.True(Decimal.MaxValue != Decimal.MinValue); } [Fact] public static void Testop_LessThan() { // Boolean Decimal.op_LessThan(Decimal, Decimal) Assert.False(Decimal.Zero < Decimal.Zero); Assert.True(Decimal.Zero < Decimal.One); Assert.False(Decimal.One < Decimal.Zero); Assert.True(5m < 15m); decimal d5 = 5; decimal d3 = 3; Assert.False(d5 < d3); Assert.False(Decimal.MaxValue < Decimal.MaxValue); Assert.False(Decimal.MinValue < Decimal.MinValue); Assert.True(Decimal.MinValue < Decimal.MaxValue); Assert.False(Decimal.MaxValue < Decimal.MinValue); } [Fact] public static void Testop_LessThanOrEqual() { // Boolean Decimal.op_LessThanOrEqual(Decimal, Decimal) Assert.True(Decimal.Zero <= Decimal.Zero); Assert.True(Decimal.Zero <= Decimal.One); Assert.False(Decimal.One <= Decimal.Zero); Assert.True(Decimal.MaxValue <= Decimal.MaxValue); Assert.True(Decimal.MinValue <= Decimal.MinValue); Assert.True(Decimal.MinValue <= Decimal.MaxValue); Assert.False(Decimal.MaxValue <= Decimal.MinValue); } [Fact] public static void TestToByte() { // Byte Decimal.ToByte(Decimal) Assert.Equal(0, Decimal.ToByte(0)); Assert.Equal(1, Decimal.ToByte(1)); Assert.Equal(255, Decimal.ToByte(255)); Assert.Throws<OverflowException>(() => Decimal.ToByte(256)); } private static void VerifyAdd<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception { bool expectFailure = typeof(T) != typeof(Exception); try { Decimal result1 = Decimal.Add(d1, d2); Decimal result2 = d1 + d2; Assert.False(expectFailure, "Expected an exception to be thrown"); Assert.Equal(result1, result2); Assert.Equal(expected, result1); } catch (T) { Assert.True(expectFailure, "Didn't expect an exception to be thrown"); } } [Fact] public static void TestAdd() { // Decimal Decimal.Add(Decimal, Decimal) // Decimal Decimal.op_Addition(Decimal, Decimal) VerifyAdd<Exception>(1, 1, 2); VerifyAdd<Exception>(-1, 1, 0); VerifyAdd<Exception>(1, -1, 0); VerifyAdd<Exception>(Decimal.MaxValue, Decimal.Zero, Decimal.MaxValue); VerifyAdd<Exception>(Decimal.MinValue, Decimal.Zero, Decimal.MinValue); VerifyAdd<Exception>(79228162514264337593543950330m, 5, Decimal.MaxValue); VerifyAdd<Exception>(79228162514264337593543950330m, -5, 79228162514264337593543950325m); VerifyAdd<Exception>(-79228162514264337593543950330m, -5, Decimal.MinValue); VerifyAdd<Exception>(-79228162514264337593543950330m, 5, -79228162514264337593543950325m); VerifyAdd<Exception>(1234.5678m, 0.00009m, 1234.56789m); VerifyAdd<Exception>(-1234.5678m, 0.00009m, -1234.56771m); VerifyAdd<Exception>(0.1111111111111111111111111111m, 0.1111111111111111111111111111m, 0.2222222222222222222222222222m); VerifyAdd<Exception>(0.5555555555555555555555555555m, 0.5555555555555555555555555555m, 1.1111111111111111111111111110m); // Exceptions VerifyAdd<OverflowException>(Decimal.MaxValue, Decimal.MaxValue); VerifyAdd<OverflowException>(79228162514264337593543950330m, 6); VerifyAdd<OverflowException>(-79228162514264337593543950330m, -6, Decimal.MinValue); } [Fact] public static void TestCeiling() { // Decimal Decimal.Ceiling(Decimal) Assert.Equal<Decimal>(123, Decimal.Ceiling((Decimal)123)); Assert.Equal<Decimal>(124, Decimal.Ceiling((Decimal)123.123)); Assert.Equal<Decimal>(-123, Decimal.Ceiling((Decimal)(-123.123))); Assert.Equal<Decimal>(124, Decimal.Ceiling((Decimal)123.567)); Assert.Equal<Decimal>(-123, Decimal.Ceiling((Decimal)(-123.567))); } private static void VerifyDivide<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception { bool expectFailure = typeof(T) != typeof(Exception); try { Decimal result1 = Decimal.Divide(d1, d2); Decimal result2 = d1 / d2; Assert.False(expectFailure, "Expected an exception to be thrown"); Assert.Equal(result1, result2); Assert.Equal(expected, result1); } catch (T) { Assert.True(expectFailure, "Didn't expect an exception to be thrown"); } } [Fact] public static void TestDivide() { // Decimal Decimal.Divide(Decimal, Decimal) // Decimal Decimal.op_Division(Decimal, Decimal) // Vanilla cases VerifyDivide<Exception>(Decimal.One, Decimal.One, Decimal.One); VerifyDivide<Exception>(Decimal.MaxValue, Decimal.MinValue, Decimal.MinusOne); VerifyDivide<Exception>(0.9214206543486529434634231456m, Decimal.MaxValue, Decimal.Zero); VerifyDivide<Exception>(38214206543486529434634231456m, 0.49214206543486529434634231456m, 77648730371625094566866001277m); VerifyDivide<Exception>(-78228162514264337593543950335m, Decimal.MaxValue, -0.987378225516463811113412343m); VerifyDivide<Exception>(5m + 10m, 2m, 7.5m); VerifyDivide<Exception>(10m, 2m, 5m); // Tests near MaxValue (VSWhidbey #389382) VerifyDivide<Exception>(792281625142643375935439503.4m, 0.1m, 7922816251426433759354395034m); VerifyDivide<Exception>(79228162514264337593543950.34m, 0.1m, 792281625142643375935439503.4m); VerifyDivide<Exception>(7922816251426433759354395.034m, 0.1m, 79228162514264337593543950.34m); VerifyDivide<Exception>(792281625142643375935439.5034m, 0.1m, 7922816251426433759354395.034m); VerifyDivide<Exception>(79228162514264337593543950335m, 10m, 7922816251426433759354395033.5m); VerifyDivide<Exception>(79228162514264337567774146561m, 10m, 7922816251426433756777414656.1m); VerifyDivide<Exception>(79228162514264337567774146560m, 10m, 7922816251426433756777414656m); VerifyDivide<Exception>(79228162514264337567774146559m, 10m, 7922816251426433756777414655.9m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.1m, 72025602285694852357767227577m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.01m, 78443725261647859003508861718m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.001m, 79149013500763574019524425909.091m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0001m, 79220240490215316061937756559.344m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00001m, 79227370240561931974224208092.919m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000001m, 79228083286181051412492537842.462m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000001m, 79228154591448878448656105469.389m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000001m, 79228161721982720373716746597.833m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000001m, 79228162435036175158507775176.492m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000001m, 79228162506341521342909798200.709m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000001m, 79228162513472055968409229775.316m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000001m, 79228162514185109431029765225.569m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000001m, 79228162514256414777292524693.522m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000001m, 79228162514263545311918807699.547m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000001m, 79228162514264258365381436070.742m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000001m, 79228162514264329670727698908.567m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000001m, 79228162514264336801262325192.357m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000001m, 79228162514264337514315787820.736m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000001m, 79228162514264337585621134083.574m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000001m, 79228162514264337592751668709.857m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000001m, 79228162514264337593464722172.486m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000001m, 79228162514264337593536027518.749m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000000001m, 79228162514264337593543158053.375m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000000001m, 79228162514264337593543871106.837m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000000001m, 79228162514264337593543942412.184m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000000000001m, 79228162514264337593543949542.718m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000000000001m, 79228162514264337593543950255.772m); VerifyDivide<Exception>(7922816251426433759354395033.5m, 0.9999999999999999999999999999m, 7922816251426433759354395034m); VerifyDivide<Exception>(79228162514264337593543950335m, 10000000m, 7922816251426433759354.3950335m); VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.000001m, 7922808328618105141249253784.2m); VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.0000000000000000000000000001m, 7922816251426433759354395032.7m); VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.0000000000000000000000000002m, 7922816251426433759354395031.9m); VerifyDivide<Exception>(7922816251426433759354395033.5m, 0.9999999999999999999999999999m, 7922816251426433759354395034m); VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000000000001m, 79228162514264337593543950327m); Decimal boundary7 = new Decimal((int)429u, (int)2133437386u, 0, false, 0); Decimal boundary71 = new Decimal((int)429u, (int)2133437387u, 0, false, 0); Decimal maxValueBy7 = Decimal.MaxValue * 0.0000001m; VerifyDivide<Exception>(maxValueBy7, 1m, maxValueBy7); VerifyDivide<Exception>(maxValueBy7, 1m, maxValueBy7); VerifyDivide<Exception>(maxValueBy7, 0.0000001m, Decimal.MaxValue); VerifyDivide<Exception>(boundary7, 1m, boundary7); VerifyDivide<Exception>(boundary7, 0.000000100000000000000000001m, 91630438009337286849083695.62m); VerifyDivide<Exception>(boundary71, 0.000000100000000000000000001m, 91630438052286959809083695.62m); VerifyDivide<Exception>(7922816251426433759354.3950335m, 1m, 7922816251426433759354.3950335m); VerifyDivide<Exception>(7922816251426433759354.3950335m, 0.0000001m, 79228162514264337593543950335m); //[] DivideByZero exceptions VerifyDivide<DivideByZeroException>(Decimal.One, Decimal.Zero); VerifyDivide<DivideByZeroException>(Decimal.Zero, Decimal.Zero); VerifyDivide<DivideByZeroException>(-5.00m, (-1m) * Decimal.Zero); VerifyDivide<DivideByZeroException>(0.0m, -0.00m); //[] Overflow exceptions VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.9999999999999999999999999m); VerifyDivide<OverflowException>(792281625142643.37593543950335m, 0.0000000000000079228162514264337593543950335m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.1m); VerifyDivide<OverflowException>(7922816251426433759354395034m, 0.1m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999999999m); VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.1m); VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.9999999999999999999999999m); VerifyDivide<OverflowException>(Decimal.MaxValue / 2, 0.5m); } [Fact] public static void TestFloor() { // Decimal Decimal.Floor(Decimal) Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123)); Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123.123)); Assert.Equal<Decimal>(-124, Decimal.Floor((Decimal)(-123.123))); Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123.567)); Assert.Equal<Decimal>(-124, Decimal.Floor((Decimal)(-123.567))); } [Fact] public static void TestMaxValue() { // Decimal Decimal.MaxValue Assert.Equal(Decimal.MaxValue, 79228162514264337593543950335m); } [Fact] public static void TestMinusOne() { // Decimal Decimal.MinusOne Assert.Equal(Decimal.MinusOne, -1); } [Fact] public static void TestZero() { // Decimal Decimal.Zero Assert.Equal(Decimal.Zero, 0); } [Fact] public static void TestOne() { // Decimal Decimal.One Assert.Equal(Decimal.One, 1); } [Fact] public static void TestMinValue() { // Decimal Decimal.MinValue Assert.Equal(Decimal.MinValue, -79228162514264337593543950335m); } private static void VerifyMultiply<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception { bool expectFailure = typeof(T) != typeof(Exception); try { Decimal result1 = Decimal.Multiply(d1, d2); Decimal result2 = d1 * d2; Assert.False(expectFailure, "Expected an exception to be thrown"); Assert.Equal(result1, result2); Assert.Equal(expected, result1); } catch (T) { Assert.True(expectFailure, "Didn't expect an exception to be thrown"); } } [Fact] public static void TestMultiply() { // Decimal Decimal.Multiply(Decimal, Decimal) // Decimal Decimal.op_Multiply(Decimal, Decimal) VerifyMultiply<Exception>(Decimal.One, Decimal.One, Decimal.One); VerifyMultiply<Exception>(7922816251426433759354395033.5m, new Decimal(10), Decimal.MaxValue); VerifyMultiply<Exception>(0.2352523523423422342354395033m, 56033525474612414574574757495m, 13182018677937129120135020796m); VerifyMultiply<Exception>(46161363632634613634.093453337m, 461613636.32634613634083453337m, 21308714924243214928823669051m); VerifyMultiply<Exception>(0.0000000000000345435353453563m, .0000000000000023525235234234m, 0.0000000000000000000000000001m); // Near MaxValue VerifyMultiply<Exception>(79228162514264337593543950335m, 0.9m, 71305346262837903834189555302m); VerifyMultiply<Exception>(79228162514264337593543950335m, 0.99m, 78435880889121694217608510832m); VerifyMultiply<Exception>(79228162514264337593543950335m, 0.9999999999999999999999999999m, 79228162514264337593543950327m); VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.9m, -71305346262837903834189555302m); VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.99m, -78435880889121694217608510832m); VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.9999999999999999999999999999m, -79228162514264337593543950327m); // Exceptions VerifyMultiply<OverflowException>(Decimal.MaxValue, Decimal.MinValue); VerifyMultiply<OverflowException>(Decimal.MinValue, 1.1m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.1m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.01m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000000000001m); VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000000000001m); VerifyMultiply<OverflowException>(Decimal.MaxValue / 2, 2m); } [Fact] public static void TestNegate() { // Decimal Decimal.Negate(Decimal) Assert.Equal(0, Decimal.Negate(0)); Assert.Equal(1, Decimal.Negate(-1)); Assert.Equal(-1, Decimal.Negate(1)); } [Fact] public static void Testop_Decrement() { // Decimal Decimal.op_Decrement(Decimal) Decimal d = 12345; Assert.Equal(12344, --d); d = 12345.678m; Assert.Equal(12344.678m, --d); d = -12345; Assert.Equal(-12346, --d); d = -12345.678m; Assert.Equal(-12346.678m, --d); } [Fact] public static void Testop_Increment() { // Decimal Decimal.op_Increment(Decimal) Decimal d = 12345; Assert.Equal(12346, ++d); d = 12345.678m; Assert.Equal(12346.678m, ++d); d = -12345; Assert.Equal(-12344m, ++d); d = -12345.678m; Assert.Equal(-12344.678m, ++d); } [Fact] public static void TestParse() { // Boolean Decimal.TryParse(String, NumberStyles, IFormatProvider, Decimal) Assert.Equal(123, Decimal.Parse("123")); Assert.Equal(-123, Decimal.Parse("-123")); Assert.Equal(123.123m, Decimal.Parse((123.123).ToString())); Assert.Equal(-123.123m, Decimal.Parse((-123.123).ToString())); Decimal d; Assert.True(Decimal.TryParse("79228162514264337593543950335", out d)); Assert.Equal(Decimal.MaxValue, d); Assert.True(Decimal.TryParse("-79228162514264337593543950335", out d)); Assert.Equal(Decimal.MinValue, d); var nfi = new NumberFormatInfo() { NumberGroupSeparator = "," }; Assert.True(Decimal.TryParse("79,228,162,514,264,337,593,543,950,335", NumberStyles.AllowThousands, nfi, out d)); Assert.Equal(Decimal.MaxValue, d); Assert.False(Decimal.TryParse("ysaidufljasdf", out d)); Assert.False(Decimal.TryParse("79228162514264337593543950336", out d)); } private static void VerifyRemainder(Decimal d1, Decimal d2, Decimal expectedResult) { Decimal result1 = Decimal.Remainder(d1, d2); Decimal result2 = d1 % d2; Assert.Equal(result1, result2); Assert.Equal(expectedResult, result1); } [Fact] public static void TestRemainder() { // Decimal Decimal.Remainder(Decimal, Decimal) // Decimal Decimal.op_Modulus(Decimal, Decimal) Decimal NegativeZero = new Decimal(0, 0, 0, true, 0); VerifyRemainder(5m, 3m, 2m); VerifyRemainder(5m, -3m, 2m); VerifyRemainder(-5m, 3m, -2m); VerifyRemainder(-5m, -3m, -2m); VerifyRemainder(3m, 5m, 3m); VerifyRemainder(3m, -5m, 3m); VerifyRemainder(-3m, 5m, -3m); VerifyRemainder(-3m, -5m, -3m); VerifyRemainder(10m, -3m, 1m); VerifyRemainder(-10m, 3m, -1m); VerifyRemainder(-2.0m, 0.5m, -0.0m); VerifyRemainder(2.3m, 0.531m, 0.176m); VerifyRemainder(0.00123m, 3242m, 0.00123m); VerifyRemainder(3242m, 0.00123m, 0.00044m); VerifyRemainder(17.3m, 3m, 2.3m); VerifyRemainder(8.55m, 2.25m, 1.80m); VerifyRemainder(0.00m, 3m, 0.00m); VerifyRemainder(NegativeZero, 2.2m, NegativeZero); // [] Max/Min VerifyRemainder(Decimal.MaxValue, Decimal.MaxValue, 0m); VerifyRemainder(Decimal.MaxValue, Decimal.MinValue, 0m); VerifyRemainder(Decimal.MaxValue, 1, 0m); VerifyRemainder(Decimal.MaxValue, 2394713m, 1494647m); VerifyRemainder(Decimal.MaxValue, -32768m, 32767m); VerifyRemainder(-0.00m, Decimal.MaxValue, -0.00m); VerifyRemainder(1.23984m, Decimal.MaxValue, 1.23984m); VerifyRemainder(2398412.12983m, Decimal.MaxValue, 2398412.12983m); VerifyRemainder(-0.12938m, Decimal.MaxValue, -0.12938m); VerifyRemainder(Decimal.MinValue, Decimal.MinValue, NegativeZero); VerifyRemainder(Decimal.MinValue, Decimal.MaxValue, NegativeZero); VerifyRemainder(Decimal.MinValue, 1, NegativeZero); VerifyRemainder(Decimal.MinValue, 2394713m, -1494647m); VerifyRemainder(Decimal.MinValue, -32768m, -32767m); // ASURT #90921 VerifyRemainder(0.0m, Decimal.MinValue, 0.0m); VerifyRemainder(1.23984m, Decimal.MinValue, 1.23984m); VerifyRemainder(2398412.12983m, Decimal.MinValue, 2398412.12983m); VerifyRemainder(-0.12938m, Decimal.MinValue, -0.12938m); VerifyRemainder(57675350989891243676868034225m, 7m, 5m); // VSWhidbey #325142 VerifyRemainder(-57675350989891243676868034225m, 7m, -5m); VerifyRemainder(57675350989891243676868034225m, -7m, 5m); VerifyRemainder(-57675350989891243676868034225m, -7m, -5m); // VSWhidbey #389382 VerifyRemainder(792281625142643375935439503.4m, 0.1m, 0.0m); VerifyRemainder(79228162514264337593543950.34m, 0.1m, 0.04m); VerifyRemainder(7922816251426433759354395.034m, 0.1m, 0.034m); VerifyRemainder(792281625142643375935439.5034m, 0.1m, 0.0034m); VerifyRemainder(79228162514264337593543950335m, 10m, 5m); VerifyRemainder(79228162514264337567774146561m, 10m, 1m); VerifyRemainder(79228162514264337567774146560m, 10m, 0m); VerifyRemainder(79228162514264337567774146559m, 10m, 9m); } private static void VerifySubtract<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception { bool expectFailure = typeof(T) != typeof(Exception); try { Decimal result1 = Decimal.Subtract(d1, d2); Decimal result2 = d1 - d2; Assert.False(expectFailure, "Expected an exception to be thrown"); Assert.Equal(result1, result2); Assert.Equal(expected, result1); } catch (T) { Assert.True(expectFailure, "Didn't expect an exception to be thrown"); } } [Fact] public static void TestSubtract() { // Decimal Decimal.Subtract(Decimal, Decimal) // Decimal Decimal.op_Subtraction(Decimal, Decimal) VerifySubtract<Exception>(1, 1, 0); VerifySubtract<Exception>(-1, 1, -2); VerifySubtract<Exception>(1, -1, 2); VerifySubtract<Exception>(Decimal.MaxValue, Decimal.Zero, Decimal.MaxValue); VerifySubtract<Exception>(Decimal.MinValue, Decimal.Zero, Decimal.MinValue); VerifySubtract<Exception>(79228162514264337593543950330m, -5, Decimal.MaxValue); VerifySubtract<Exception>(79228162514264337593543950330m, 5, 79228162514264337593543950325m); VerifySubtract<Exception>(-79228162514264337593543950330m, 5, Decimal.MinValue); VerifySubtract<Exception>(-79228162514264337593543950330m, -5, -79228162514264337593543950325m); VerifySubtract<Exception>(1234.5678m, 0.00009m, 1234.56771m); VerifySubtract<Exception>(-1234.5678m, 0.00009m, -1234.56789m); VerifySubtract<Exception>(0.1111111111111111111111111111m, 0.1111111111111111111111111111m, 0); VerifySubtract<Exception>(0.2222222222222222222222222222m, 0.1111111111111111111111111111m, 0.1111111111111111111111111111m); VerifySubtract<Exception>(1.1111111111111111111111111110m, 0.5555555555555555555555555555m, 0.5555555555555555555555555555m); } [Fact] public static void TestTruncate() { // Decimal Decimal.Truncate(Decimal) Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123)); Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123.123)); Assert.Equal<Decimal>(-123, Decimal.Truncate((Decimal)(-123.123))); Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123.567)); Assert.Equal<Decimal>(-123, Decimal.Truncate((Decimal)(-123.567))); } [Fact] public static void TestRound() { // Decimal Decimal.Truncate(Decimal) // Assert.AreEqual<Decimal>(123, Decimal.Round((Decimal)123, 2)); // Assert.AreEqual<Decimal>((Decimal)123.123, Decimal.Round((Decimal)123.123, 3)); // Assert.AreEqual<Decimal>((Decimal)(-123.1), Decimal.Round((Decimal)(-123.123), 1)); // Assert.AreEqual<Decimal>(124, Decimal.Round((Decimal)123.567, 0)); // Assert.AreEqual<Decimal>((Decimal)(-123.567), Decimal.Round((Decimal)(-123.567), 4)); } [Fact] public static void TestCompare() { // Int32 Decimal.Compare(Decimal, Decimal) Assert.True(Decimal.Compare(Decimal.Zero, Decimal.Zero) == 0); Assert.True(Decimal.Compare(Decimal.Zero, Decimal.One) < 0); Assert.True(Decimal.Compare(Decimal.One, Decimal.Zero) > 0); Assert.True(Decimal.Compare(Decimal.MinusOne, Decimal.Zero) < 0); Assert.True(Decimal.Compare(Decimal.Zero, Decimal.MinusOne) > 0); Assert.True(Decimal.Compare(5, 3) > 0); Assert.True(Decimal.Compare(5, 5) == 0); Assert.True(Decimal.Compare(5, 9) < 0); Assert.True(Decimal.Compare(-123.123m, 123.123m) < 0); Assert.True(Decimal.Compare(Decimal.MaxValue, Decimal.MaxValue) == 0); Assert.True(Decimal.Compare(Decimal.MinValue, Decimal.MinValue) == 0); Assert.True(Decimal.Compare(Decimal.MinValue, Decimal.MaxValue) < 0); Assert.True(Decimal.Compare(Decimal.MaxValue, Decimal.MinValue) > 0); } [Fact] public static void TestCompareTo() { // Int32 Decimal.CompareTo(Decimal) Decimal d = 456; Assert.True(d.CompareTo(456m) == 0); Assert.True(d.CompareTo(457m) < 0); Assert.True(d.CompareTo(455m) > 0); } [Fact] public static void TestSystemIComparableCompareTo() { // Int32 Decimal.System.IComparable.CompareTo(Object) IComparable d = (Decimal)248; Assert.True(d.CompareTo(248m) == 0); Assert.True(d.CompareTo(249m) < 0); Assert.True(d.CompareTo(247m) > 0); Assert.True(d.CompareTo(null) > 0); Assert.Throws<ArgumentException>(() => d.CompareTo("248")); } [Fact] public static void TestGetHashCode() { // Int32 Decimal.GetHashCode() Assert.NotEqual(Decimal.MinusOne.GetHashCode(), Decimal.One.GetHashCode()); } [Fact] public static void TestToSingle() { // Single Decimal.ToSingle(Decimal) Single s = 12345.12f; Assert.Equal(s, Decimal.ToSingle((Decimal)s)); Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s))); s = 1e20f; Assert.Equal(s, Decimal.ToSingle((Decimal)s)); Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s))); s = 1e27f; Assert.Equal(s, Decimal.ToSingle((Decimal)s)); Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s))); } [Fact] public static void TestToDouble() { Double d = Decimal.ToDouble(new Decimal(0, 0, 1, false, 0)); // Double Decimal.ToDouble(Decimal) Double dbl = 123456789.123456; Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl)); Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl))); dbl = 1e20; Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl)); Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl))); dbl = 1e27; Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl)); Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl))); dbl = Int64.MaxValue; // Need to pass in the Int64.MaxValue to ToDouble and not dbl because the conversion to double is a little lossy and we want precision Assert.Equal(dbl, Decimal.ToDouble((Decimal)Int64.MaxValue)); Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-Int64.MaxValue))); } [Fact] public static void TestToInt16() { // Int16 Decimal.ToInt16(Decimal) Assert.Equal(Int16.MaxValue, Decimal.ToInt16((Decimal)Int16.MaxValue)); Assert.Equal(Int16.MinValue, Decimal.ToInt16((Decimal)Int16.MinValue)); } [Fact] public static void TestToInt32() { // Int32 Decimal.ToInt32(Decimal) Assert.Equal(Int32.MaxValue, Decimal.ToInt32((Decimal)Int32.MaxValue)); Assert.Equal(Int32.MinValue, Decimal.ToInt32((Decimal)Int32.MinValue)); } [Fact] public static void TestGetBits() { // Int32[] Decimal.GetBits(Decimal) } [Fact] public static void TestToInt64() { // Int64 Decimal.ToInt64(Decimal) Assert.Equal(Int64.MaxValue, Decimal.ToInt64((Decimal)Int64.MaxValue)); Assert.Equal(Int64.MinValue, Decimal.ToInt64((Decimal)Int64.MinValue)); } [Fact] public static void TestToSByte() { // SByte Decimal.ToSByte(Decimal) Assert.Equal(SByte.MaxValue, Decimal.ToSByte((Decimal)SByte.MaxValue)); Assert.Equal(SByte.MinValue, Decimal.ToSByte((Decimal)SByte.MinValue)); } [Fact] public static void TestToUInt16() { // UInt16 Decimal.ToUInt16(Decimal) Assert.Equal(UInt16.MaxValue, Decimal.ToUInt16((Decimal)UInt16.MaxValue)); Assert.Equal(UInt16.MinValue, Decimal.ToUInt16((Decimal)UInt16.MinValue)); } [Fact] public static void TestToUInt32() { // UInt32 Decimal.ToUInt32(Decimal) Assert.Equal(UInt32.MaxValue, Decimal.ToUInt32((Decimal)UInt32.MaxValue)); Assert.Equal(UInt32.MinValue, Decimal.ToUInt32((Decimal)UInt32.MinValue)); } [Fact] public static void TestToUInt64() { // UInt64 Decimal.ToUInt64(Decimal) Assert.Equal(UInt64.MaxValue, Decimal.ToUInt64((Decimal)UInt64.MaxValue)); Assert.Equal(UInt64.MinValue, Decimal.ToUInt64((Decimal)UInt64.MinValue)); } [Fact] public static void TestToString() { // String Decimal.ToString() Decimal d1 = 6310.23m; Assert.Equal(string.Format("{0}", 6310.23), d1.ToString()); Decimal d2 = -8249.000003m; Assert.Equal(string.Format("{0}", -8249.000003), d2.ToString()); Assert.Equal("79228162514264337593543950335", Decimal.MaxValue.ToString()); Assert.Equal("-79228162514264337593543950335", Decimal.MinValue.ToString()); } [Fact] public static void Testctor() { Decimal d; // Void Decimal..ctor(Double) d = new Decimal((Double)123456789.123456); Assert.Equal<Decimal>(d, (Decimal)123456789.123456); // Void Decimal..ctor(Int32) d = new Decimal((Int32)Int32.MaxValue); Assert.Equal<Decimal>(d, Int32.MaxValue); // Void Decimal..ctor(Int64) d = new Decimal((Int64)Int64.MaxValue); Assert.Equal<Decimal>(d, Int64.MaxValue); // Void Decimal..ctor(Single) d = new Decimal((Single)123.123); Assert.Equal<Decimal>(d, (Decimal)123.123); // Void Decimal..ctor(UInt32) d = new Decimal((UInt32)UInt32.MaxValue); Assert.Equal<Decimal>(d, UInt32.MaxValue); // Void Decimal..ctor(UInt64) d = new Decimal((UInt64)UInt64.MaxValue); Assert.Equal<Decimal>(d, UInt64.MaxValue); // Void Decimal..ctor(Int32, Int32, Int32, Boolean, Byte) d = new Decimal(1, 1, 1, false, 0); Decimal d2 = 3; d2 += UInt32.MaxValue; d2 += UInt64.MaxValue; Assert.Equal(d, d2); // Void Decimal..ctor(Int32[]) d = new Decimal(new Int32[] { 1, 1, 1, 0 }); Assert.Equal(d, d2); } [Fact] public static void TestNumberBufferLimit() { Decimal dE = 1234567890123456789012345.6785m; string s1 = "1234567890123456789012345.678456"; var nfi = new NumberFormatInfo() { NumberDecimalSeparator = "." }; Decimal d1 = Decimal.Parse(s1, nfi); Assert.Equal(d1, dE); return; } }
using System; using HalconDotNet; using HDisplayControl.ViewROI; using System.Collections; namespace HDisplayControl.ViewROI { public delegate void FuncROIDelegate(); /// <summary> /// This class creates and manages ROI objects. It responds /// to mouse device inputs using the methods mouseDownAction and /// mouseMoveAction. You don't have to know this class in detail when you /// build your own C# project. But you must consider a few things if /// you want to use interactive ROIs in your application: There is a /// quite close connection between the ROIController and the HWndCtrl /// class, which means that you must 'register' the ROIController /// with the HWndCtrl, so the HWndCtrl knows it has to forward user input /// (like mouse events) to the ROIController class. /// The visualization and manipulation of the ROI objects is done /// by the ROIController. /// This class provides special support for the matching /// applications by calculating a model region from the list of ROIs. For /// this, ROIs are added and subtracted according to their sign. /// </summary> public class ROIController { /// <summary> /// Constant for setting the ROI mode: positive ROI sign. /// </summary> public const int MODE_ROI_POS = 21; /// <summary> /// Constant for setting the ROI mode: negative ROI sign. /// </summary> public const int MODE_ROI_NEG = 22; /// <summary> /// Constant for setting the ROI mode: no model region is computed as /// the sum of all ROI objects. /// </summary> public const int MODE_ROI_NONE = 23; /// <summary>Constant describing an update of the region of interest</summary> public const int EVENT_UPDATE_ROI = 50; public const int EVENT_CHANGED_ROI_SIGN = 51; /// <summary>Constant describing an update of the region of interest</summary> public const int EVENT_MOVING_ROI = 52; public const int EVENT_DELETED_ACTROI = 53; public const int EVENT_DELETED_ALL_ROIS = 54; public const int EVENT_ACTIVATED_ROI = 55; public const int EVENT_CREATED_ROI = 56; public const int EVENT_REPAINT_ROI = 57; private ROI roiMode; private int stateROI; private double currX, currY; /// <summary>Index of the active ROI object</summary> public int activeROIidx; public int deletedIdx; /// <summary>List containing all created ROI objects so far</summary> public ArrayList ROIList; /// <summary> /// Region obtained by summing up all negative /// and positive ROI objects from the ROIList /// </summary> public HRegion ModelROI; private string activeCol = "green"; private string activeHdlCol = "red"; private string inactiveCol = "yellow"; /// <summary> /// Reference to the HWndCtrl, the ROI Controller is registered to /// </summary> public HWndCtrl viewController; /// <summary> /// Delegate that notifies about changes made in the model region /// </summary> public IconicDelegate NotifyRCObserver; /// <summary>Constructor</summary> public ROIController() { stateROI = MODE_ROI_NONE; ROIList = new ArrayList(); activeROIidx = -1; ModelROI = new HRegion(); NotifyRCObserver = new IconicDelegate(dummyI); deletedIdx = -1; currX = currY = -1; } /// <summary>Registers the HWndCtrl to this ROIController instance</summary> public void setViewController(HWndCtrl view) { viewController = view; } /// <summary>Gets the ModelROI object</summary> public HRegion getModelRegion() { return ModelROI; } /// <summary>Gets the List of ROIs created so far</summary> public ArrayList getROIList() { return ROIList; } /// <summary>Get the active ROI</summary> public ROI getActiveROI() { if (activeROIidx != -1) return ((ROI)ROIList[activeROIidx]); return null; } public int getActiveROIIdx() { return activeROIidx; } public void setActiveROIIdx(int active) { activeROIidx = active; } public int getDelROIIdx() { return deletedIdx; } /// <summary> /// To create a new ROI object the application class initializes a /// 'seed' ROI instance and passes it to the ROIController. /// The ROIController now responds by manipulating this new ROI /// instance. /// </summary> /// <param name="r"> /// 'Seed' ROI object forwarded by the application forms class. /// </param> public void setROIShape(ROI r) { roiMode = r; roiMode.setOperatorFlag(stateROI); } /// <summary> /// Sets the sign of a ROI object to the value 'mode' (MODE_ROI_NONE, /// MODE_ROI_POS,MODE_ROI_NEG) /// </summary> public void setROISign(int mode) { stateROI = mode; if ((activeROIidx != -1)) { ((ROI)ROIList[activeROIidx]).setOperatorFlag(stateROI); NotifyRCObserver(ROIController.EVENT_REPAINT_ROI); NotifyRCObserver(ROIController.EVENT_CHANGED_ROI_SIGN); } } /// <summary> /// Removes the ROI object that is marked as active. /// If no ROI object is active, then nothing happens. /// </summary> public void removeActive() { if (activeROIidx != -1) { ROIList.RemoveAt(activeROIidx); deletedIdx = activeROIidx; activeROIidx = -1; //viewController.repaint(); NotifyRCObserver(EVENT_REPAINT_ROI); NotifyRCObserver(EVENT_DELETED_ACTROI); } } /// <summary> /// Calculates the ModelROI region for all objects contained /// in ROIList, by adding and subtracting the positive and /// negative ROI objects. /// </summary> public bool defineModelROI() { HRegion tmpAdd, tmpDiff, tmp; double row, col; double rowDiff, colDiff; if (stateROI == MODE_ROI_NONE) return true; tmp = new HRegion(); tmpAdd = new HRegion(); tmpDiff = new HRegion(); tmpAdd.GenEmptyRegion(); tmpDiff.GenEmptyRegion(); for (int i=0; i < ROIList.Count; i++) { switch (((ROI)ROIList[i]).getOperatorFlag()) { case ROI.POSITIVE_FLAG: tmp = ((ROI)ROIList[i]).getRegion(); tmpAdd = tmp.Union2(tmpAdd); break; case ROI.NEGATIVE_FLAG: tmp = ((ROI)ROIList[i]).getRegion(); tmpDiff = tmp.Union2(tmpDiff); break; default: break; }//end of switch }//end of for ModelROI = null; if (tmpAdd.AreaCenter(out row, out col) > 0) { if (tmpDiff.AreaCenter(out rowDiff, out colDiff) > 0) tmp = tmpAdd.Difference(tmpDiff); else tmp = tmpAdd; if (tmp.AreaCenter(out row, out col) > 0) ModelROI = tmp; } //in case the set of positiv and negative ROIs dissolve if (ModelROI == null || ROIList.Count == 0) return false; return true; } /// <summary> /// Clears all variables managing ROI objects /// </summary> public void reset() { ROIList.Clear(); activeROIidx = -1; ModelROI = null; roiMode = null; NotifyRCObserver(EVENT_DELETED_ALL_ROIS); } /// <summary> /// Deletes this ROI instance if a 'seed' ROI object has been passed /// to the ROIController by the application class. /// /// </summary> public void resetROI() { activeROIidx = -1; roiMode = null; } /// <summary>Defines the colors for the ROI objects</summary> /// <param name="aColor">Color for the active ROI object</param> /// <param name="inaColor">Color for the inactive ROI objects</param> /// <param name="aHdlColor"> /// Color for the active handle of the active ROI object /// </param> public void setDrawColor(string aColor, string aHdlColor, string inaColor) { if (aColor != "") activeCol = aColor; if (aHdlColor != "") activeHdlCol = aHdlColor; if (inaColor != "") inactiveCol = inaColor; } /// <summary> /// Paints all objects from the ROIList into the HALCON window /// </summary> /// <param name="window">HALCON window</param> public void paintData(HalconDotNet.HWindow window) { window.SetDraw("margin"); window.SetLineWidth(1); if (ROIList.Count > 0) { window.SetDraw("fill"); window.SetLineStyle(new HTuple()); window.SetColor("blue"); defineModelROI(); if (ModelROI != null) window.DispRegion(ModelROI); window.SetColor(inactiveCol); window.SetDraw("margin"); for (int i=0; i < ROIList.Count; i++) { window.SetLineStyle(((ROI)ROIList[i]).flagLineStyle); ((ROI)ROIList[i]).draw(window); } if (activeROIidx != -1) { window.SetColor(activeCol); window.SetLineStyle(((ROI)ROIList[activeROIidx]).flagLineStyle); ((ROI)ROIList[activeROIidx]).draw(window); window.SetColor(activeHdlCol); ((ROI)ROIList[activeROIidx]).displayActive(window); } } } /// <summary> /// Paints specified region from the ROIList into the HALCON window /// </summary> /// <param name="window">HALCON window</param> public void paintSpecifiedROI(HalconDotNet.HWindow window, int RegionID) { window.SetDraw("margin"); window.SetLineWidth(1); if ((ROIList.Count > 0) && (ROIList.Count > RegionID)) { window.SetColor(inactiveCol); window.SetDraw("margin"); window.SetLineStyle(((ROI)ROIList[RegionID]).flagLineStyle); ((ROI)ROIList[RegionID]).draw(window); if ((activeROIidx != -1) && (activeROIidx == RegionID)) { window.SetColor(activeCol); window.SetLineStyle(((ROI)ROIList[activeROIidx]).flagLineStyle); ((ROI)ROIList[activeROIidx]).draw(window); window.SetColor(activeHdlCol); ((ROI)ROIList[activeROIidx]).displayActive(window); } } } public HRegion getSpecifiedRegion(int RegionID) { HRegion reg; if ((RegionID > -1) && (ROIList.Count > RegionID)) { reg = ((ROI)ROIList[RegionID]).getRegion(); return reg; } else return null; } /// <summary> /// Reaction of ROI objects to the 'mouse button down' event: changing /// the shape of the ROI and adding it to the ROIList if it is a 'seed' /// ROI. /// </summary> /// <param name="imgX">x coordinate of mouse event</param> /// <param name="imgY">y coordinate of mouse event</param> /// <returns></returns> public int mouseDownAction(double imgX, double imgY) { int idxROI= -1; double max = 10000, dist = 0; double epsilon = 35.0; //maximal shortest distance to one of //the handles if (roiMode != null) //either a new ROI object is created { roiMode.createROI(imgX, imgY); ROIList.Add(roiMode); roiMode = null; activeROIidx = ROIList.Count - 1; viewController.repaint(); NotifyRCObserver(ROIController.EVENT_CREATED_ROI); } else if (ROIList.Count > 0) // ... or an existing one is manipulated { // identify activated ROI activeROIidx = -1; for (int i =0; i < ROIList.Count; i++) { dist = ((ROI)ROIList[i]).distToClosestHandle(imgX, imgY); if ((dist < max) && (dist < epsilon)) { max = dist; idxROI = i; } }//end of for // if (idxROI >= 0) { activeROIidx = idxROI; NotifyRCObserver(ROIController.EVENT_ACTIVATED_ROI); } //viewController.repaint(); NotifyRCObserver(ROIController.EVENT_REPAINT_ROI); } return activeROIidx; } /// <summary> /// Reaction of ROI objects to the 'mouse button move' event: moving /// the active ROI. /// </summary> /// <param name="newX">x coordinate of mouse event</param> /// <param name="newY">y coordinate of mouse event</param> public void mouseMoveAction(double newX, double newY) { if ((newX == currX) && (newY == currY)) return; if (activeROIidx < ROIList.Count) { ((ROI)ROIList[activeROIidx]).moveByHandle(newX, newY); viewController.repaint(); currX = newX; currY = newY; NotifyRCObserver(ROIController.EVENT_MOVING_ROI); } } /***********************************************************/ public void dummyI(int v) { } }//end of class }//end of namespace
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { // Soon to be dismissed [Serializable] public class ChildAgentDataUpdate { public Guid ActiveGroupID; public Guid AgentID; public bool alwaysrun; public float AVHeight; public Vector3 cameraPosition; public float drawdistance; public float godlevel; public uint GroupAccess; public Vector3 Position; public ulong regionHandle; public byte[] throttles; public Vector3 Velocity; public ChildAgentDataUpdate() { } } public interface IAgentData { UUID AgentID { get; set; } OSDMap Pack(); void Unpack(OSDMap map); } /// <summary> /// Replacement for ChildAgentDataUpdate. Used over RESTComms and LocalComms. /// </summary> public class AgentPosition : IAgentData { private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public ulong RegionHandle; public uint CircuitCode; public UUID SessionID; public float Far; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; // This probably shouldn't be here public byte[] Throttles; public OSDMap Pack() { OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentPosition"); args["region_handle"] = OSD.FromString(RegionHandle.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["far"] = OSD.FromReal(Far); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); return args; } public void Unpack(OSDMap args) { if (args.ContainsKey("region_handle")) UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle); if (args["circuit_code"] != null) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args["agent_uuid"] != null) AgentID = args["agent_uuid"].AsUUID(); if (args["session_uuid"] != null) SessionID = args["session_uuid"].AsUUID(); if (args["position"] != null) Vector3.TryParse(args["position"].AsString(), out Position); if (args["velocity"] != null) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args["center"] != null) Vector3.TryParse(args["center"].AsString(), out Center); if (args["size"] != null) Vector3.TryParse(args["size"].AsString(), out Size); if (args["at_axis"] != null) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args["left_axis"] != null) Vector3.TryParse(args["left_axis"].AsString(), out LeftAxis); if (args["up_axis"] != null) Vector3.TryParse(args["up_axis"].AsString(), out UpAxis); if (args["changed_grid"] != null) ChangedGrid = args["changed_grid"].AsBoolean(); if (args["far"] != null) Far = (float)(args["far"].AsReal()); if (args["throttles"] != null) Throttles = args["throttles"].AsBinary(); } /// <summary> /// Soon to be decommissioned /// </summary> /// <param name="cAgent"></param> public void CopyFrom(ChildAgentDataUpdate cAgent) { AgentID = new UUID(cAgent.AgentID); // next: ??? Size = new Vector3(); Size.Z = cAgent.AVHeight; Center = cAgent.cameraPosition; Far = cAgent.drawdistance; Position = cAgent.Position; RegionHandle = cAgent.regionHandle; Throttles = cAgent.throttles; Velocity = cAgent.Velocity; } } public class AgentGroupData { public UUID GroupID; public ulong GroupPowers; public bool AcceptNotices; public AgentGroupData(UUID id, ulong powers, bool notices) { GroupID = id; GroupPowers = powers; AcceptNotices = notices; } public AgentGroupData(OSDMap args) { UnpackUpdateMessage(args); } public OSDMap PackUpdateMessage() { OSDMap groupdata = new OSDMap(); groupdata["group_id"] = OSD.FromUUID(GroupID); groupdata["group_powers"] = OSD.FromString(GroupPowers.ToString()); groupdata["accept_notices"] = OSD.FromBoolean(AcceptNotices); return groupdata; } public void UnpackUpdateMessage(OSDMap args) { if (args["group_id"] != null) GroupID = args["group_id"].AsUUID(); if (args["group_powers"] != null) UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers); if (args["accept_notices"] != null) AcceptNotices = args["accept_notices"].AsBoolean(); } } public class ControllerData { public UUID ItemID; public uint IgnoreControls; public uint EventControls; public ControllerData(UUID item, uint ignore, uint ev) { ItemID = item; IgnoreControls = ignore; EventControls = ev; } public ControllerData(OSDMap args) { UnpackUpdateMessage(args); } public OSDMap PackUpdateMessage() { OSDMap controldata = new OSDMap(); controldata["item"] = OSD.FromUUID(ItemID); controldata["ignore"] = OSD.FromInteger(IgnoreControls); controldata["event"] = OSD.FromInteger(EventControls); return controldata; } public void UnpackUpdateMessage(OSDMap args) { if (args["item"] != null) ItemID = args["item"].AsUUID(); if (args["ignore"] != null) IgnoreControls = (uint)args["ignore"].AsInteger(); if (args["event"] != null) EventControls = (uint)args["event"].AsInteger(); } } public class AgentData : IAgentData { private UUID m_id; public UUID AgentID { get { return m_id; } set { m_id = value; } } public UUID RegionID; public uint CircuitCode; public UUID SessionID; public Vector3 Position; public Vector3 Velocity; public Vector3 Center; public Vector3 Size; public Vector3 AtAxis; public Vector3 LeftAxis; public Vector3 UpAxis; public bool ChangedGrid; public float Far; public float Aspect; //public int[] Throttles; public byte[] Throttles; public uint LocomotionState; public Quaternion HeadRotation; public Quaternion BodyRotation; public uint ControlFlags; public float EnergyLevel; public Byte GodLevel; public bool AlwaysRun; public UUID PreyAgent; public Byte AgentAccess; public UUID ActiveGroupID; public AgentGroupData[] Groups; public Animation[] Anims; public UUID GranterID; // Appearance public AvatarAppearance Appearance; // DEBUG ON private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // DEBUG OFF /* public byte[] AgentTextures; public byte[] VisualParams; public UUID[] Wearables; public AvatarAttachment[] Attachments; */ // Scripted public ControllerData[] Controllers; public string CallbackURI; public virtual OSDMap Pack() { // DEBUG ON m_log.WarnFormat("[CHILDAGENTDATAUPDATE] Pack data"); // DEBUG OFF OSDMap args = new OSDMap(); args["message_type"] = OSD.FromString("AgentData"); args["region_id"] = OSD.FromString(RegionID.ToString()); args["circuit_code"] = OSD.FromString(CircuitCode.ToString()); args["agent_uuid"] = OSD.FromUUID(AgentID); args["session_uuid"] = OSD.FromUUID(SessionID); args["position"] = OSD.FromString(Position.ToString()); args["velocity"] = OSD.FromString(Velocity.ToString()); args["center"] = OSD.FromString(Center.ToString()); args["size"] = OSD.FromString(Size.ToString()); args["at_axis"] = OSD.FromString(AtAxis.ToString()); args["left_axis"] = OSD.FromString(LeftAxis.ToString()); args["up_axis"] = OSD.FromString(UpAxis.ToString()); args["changed_grid"] = OSD.FromBoolean(ChangedGrid); args["far"] = OSD.FromReal(Far); args["aspect"] = OSD.FromReal(Aspect); if ((Throttles != null) && (Throttles.Length > 0)) args["throttles"] = OSD.FromBinary(Throttles); args["locomotion_state"] = OSD.FromString(LocomotionState.ToString()); args["head_rotation"] = OSD.FromString(HeadRotation.ToString()); args["body_rotation"] = OSD.FromString(BodyRotation.ToString()); args["control_flags"] = OSD.FromString(ControlFlags.ToString()); args["energy_level"] = OSD.FromReal(EnergyLevel); args["god_level"] = OSD.FromString(GodLevel.ToString()); args["always_run"] = OSD.FromBoolean(AlwaysRun); args["prey_agent"] = OSD.FromUUID(PreyAgent); args["agent_access"] = OSD.FromString(AgentAccess.ToString()); args["active_group_id"] = OSD.FromUUID(ActiveGroupID); if ((Groups != null) && (Groups.Length > 0)) { OSDArray groups = new OSDArray(Groups.Length); foreach (AgentGroupData agd in Groups) groups.Add(agd.PackUpdateMessage()); args["groups"] = groups; } if ((Anims != null) && (Anims.Length > 0)) { OSDArray anims = new OSDArray(Anims.Length); foreach (Animation aanim in Anims) anims.Add(aanim.PackUpdateMessage()); args["animations"] = anims; } if (Appearance != null) args["packed_appearance"] = Appearance.Pack(); //if ((AgentTextures != null) && (AgentTextures.Length > 0)) //{ // OSDArray textures = new OSDArray(AgentTextures.Length); // foreach (UUID uuid in AgentTextures) // textures.Add(OSD.FromUUID(uuid)); // args["agent_textures"] = textures; //} // The code to pack textures, visuals, wearables and attachments // should be removed; packed appearance contains the full appearance // This is retained for backward compatibility only if (Appearance.Texture != null) { byte[] rawtextures = Appearance.Texture.GetBytes(); args["texture_entry"] = OSD.FromBinary(rawtextures); } if ((Appearance.VisualParams != null) && (Appearance.VisualParams.Length > 0)) args["visual_params"] = OSD.FromBinary(Appearance.VisualParams); // We might not pass this in all cases... if ((Appearance.Wearables != null) && (Appearance.Wearables.Length > 0)) { OSDArray wears = new OSDArray(Appearance.Wearables.Length); foreach (AvatarWearable awear in Appearance.Wearables) wears.Add(awear.Pack()); args["wearables"] = wears; } List<AvatarAttachment> attachments = Appearance.GetAttachments(); if ((attachments != null) && (attachments.Count > 0)) { OSDArray attachs = new OSDArray(attachments.Count); foreach (AvatarAttachment att in attachments) attachs.Add(att.Pack()); args["attachments"] = attachs; } // End of code to remove if ((Controllers != null) && (Controllers.Length > 0)) { OSDArray controls = new OSDArray(Controllers.Length); foreach (ControllerData ctl in Controllers) controls.Add(ctl.PackUpdateMessage()); args["controllers"] = controls; } if ((CallbackURI != null) && (!CallbackURI.Equals(""))) args["callback_uri"] = OSD.FromString(CallbackURI); return args; } /// <summary> /// Deserialization of agent data. /// Avoiding reflection makes it painful to write, but that's the price! /// </summary> /// <param name="hash"></param> public virtual void Unpack(OSDMap args) { // DEBUG ON m_log.WarnFormat("[CHILDAGENTDATAUPDATE] Unpack data"); // DEBUG OFF if (args.ContainsKey("region_id")) UUID.TryParse(args["region_id"].AsString(), out RegionID); if (args["circuit_code"] != null) UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode); if (args["agent_uuid"] != null) AgentID = args["agent_uuid"].AsUUID(); if (args["session_uuid"] != null) SessionID = args["session_uuid"].AsUUID(); if (args["position"] != null) Vector3.TryParse(args["position"].AsString(), out Position); if (args["velocity"] != null) Vector3.TryParse(args["velocity"].AsString(), out Velocity); if (args["center"] != null) Vector3.TryParse(args["center"].AsString(), out Center); if (args["size"] != null) Vector3.TryParse(args["size"].AsString(), out Size); if (args["at_axis"] != null) Vector3.TryParse(args["at_axis"].AsString(), out AtAxis); if (args["left_axis"] != null) Vector3.TryParse(args["left_axis"].AsString(), out AtAxis); if (args["up_axis"] != null) Vector3.TryParse(args["up_axis"].AsString(), out AtAxis); if (args["changed_grid"] != null) ChangedGrid = args["changed_grid"].AsBoolean(); if (args["far"] != null) Far = (float)(args["far"].AsReal()); if (args["aspect"] != null) Aspect = (float)args["aspect"].AsReal(); if (args["throttles"] != null) Throttles = args["throttles"].AsBinary(); if (args["locomotion_state"] != null) UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState); if (args["head_rotation"] != null) Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation); if (args["body_rotation"] != null) Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation); if (args["control_flags"] != null) UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags); if (args["energy_level"] != null) EnergyLevel = (float)(args["energy_level"].AsReal()); if (args["god_level"] != null) Byte.TryParse(args["god_level"].AsString(), out GodLevel); if (args["always_run"] != null) AlwaysRun = args["always_run"].AsBoolean(); if (args["prey_agent"] != null) PreyAgent = args["prey_agent"].AsUUID(); if (args["agent_access"] != null) Byte.TryParse(args["agent_access"].AsString(), out AgentAccess); if (args["active_group_id"] != null) ActiveGroupID = args["active_group_id"].AsUUID(); if ((args["groups"] != null) && (args["groups"]).Type == OSDType.Array) { OSDArray groups = (OSDArray)(args["groups"]); Groups = new AgentGroupData[groups.Count]; int i = 0; foreach (OSD o in groups) { if (o.Type == OSDType.Map) { Groups[i++] = new AgentGroupData((OSDMap)o); } } } if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array) { OSDArray anims = (OSDArray)(args["animations"]); Anims = new Animation[anims.Count]; int i = 0; foreach (OSD o in anims) { if (o.Type == OSDType.Map) { Anims[i++] = new Animation((OSDMap)o); } } } //if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array) //{ // OSDArray textures = (OSDArray)(args["agent_textures"]); // AgentTextures = new UUID[textures.Count]; // int i = 0; // foreach (OSD o in textures) // AgentTextures[i++] = o.AsUUID(); //} Appearance = new AvatarAppearance(AgentID); // The code to unpack textures, visuals, wearables and attachments // should be removed; packed appearance contains the full appearance // This is retained for backward compatibility only if (args["texture_entry"] != null) { byte[] rawtextures = args["texture_entry"].AsBinary(); Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures,0,rawtextures.Length); Appearance.SetTextureEntries(textures); } if (args["visual_params"] != null) Appearance.SetVisualParams(args["visual_params"].AsBinary()); if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array) { OSDArray wears = (OSDArray)(args["wearables"]); for (int i = 0; i < wears.Count / 2; i++) { AvatarWearable awear = new AvatarWearable((OSDArray)wears[i]); Appearance.SetWearable(i,awear); } } if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array) { OSDArray attachs = (OSDArray)(args["attachments"]); foreach (OSD o in attachs) { if (o.Type == OSDType.Map) { // We know all of these must end up as attachments so we // append rather than replace to ensure multiple attachments // per point continues to work Appearance.AppendAttachment(new AvatarAttachment((OSDMap)o)); } } } // end of code to remove if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map) Appearance = new AvatarAppearance(AgentID,(OSDMap)args["packed_appearance"]); // DEBUG ON else m_log.WarnFormat("[CHILDAGENTDATAUPDATE] No packed appearance"); // DEBUG OFF if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array) { OSDArray controls = (OSDArray)(args["controllers"]); Controllers = new ControllerData[controls.Count]; int i = 0; foreach (OSD o in controls) { if (o.Type == OSDType.Map) { Controllers[i++] = new ControllerData((OSDMap)o); } } } if (args["callback_uri"] != null) CallbackURI = args["callback_uri"].AsString(); } public AgentData() { } public AgentData(Hashtable hash) { //UnpackUpdateMessage(hash); } public void Dump() { System.Console.WriteLine("------------ AgentData ------------"); System.Console.WriteLine("UUID: " + AgentID); System.Console.WriteLine("Region: " + RegionID); System.Console.WriteLine("Position: " + Position); } } public class CompleteAgentData : AgentData { public override OSDMap Pack() { return base.Pack(); } public override void Unpack(OSDMap map) { base.Unpack(map); } } }
#if !REAL_ID using System; using System.Collections.Generic; #pragma warning disable 660,661 namespace Svelto.ECS { public struct EGID:IEquatable<EGID>,IEqualityComparer<EGID>,IComparable<EGID> { readonly ulong _GID; public uint entityID => (uint) (_GID & 0xFFFFFFFF); public ExclusiveGroup.ExclusiveGroupStruct groupID => new ExclusiveGroup.ExclusiveGroupStruct((uint) (_GID >> 32)); public static bool operator ==(EGID obj1, EGID obj2) { return obj1._GID == obj2._GID; } public static bool operator !=(EGID obj1, EGID obj2) { return obj1._GID != obj2._GID; } public EGID(uint entityID, ExclusiveGroup.ExclusiveGroupStruct groupID) : this() { _GID = MAKE_GLOBAL_ID(entityID, groupID); } static ulong MAKE_GLOBAL_ID(uint entityId, uint groupId) { return (ulong)groupId << 32 | ((ulong)entityId & 0xFFFFFFFF); } public static explicit operator uint(EGID id) { return id.entityID; } //in the way it's used, ulong must be always the same for each id/group public static explicit operator ulong(EGID id) { return id._GID; } public bool Equals(EGID other) { return _GID == other._GID; } public bool Equals(EGID x, EGID y) { return x == y; } public int GetHashCode(EGID obj) { return _GID.GetHashCode(); } public int CompareTo(EGID other) { return _GID.CompareTo(other._GID); } internal EGID(uint entityID, uint groupID) : this() { _GID = MAKE_GLOBAL_ID(entityID, groupID); } } } #else using System; using System.Collections.Generic; using System.Runtime.CompilerServices; #pragma warning disable 660,661 namespace Svelto.ECS { public struct EGID:IEquatable<EGID>,IEqualityComparer<EGID>,IComparable<EGID> { readonly ulong _GID; const int idbits = 22; //one bit is reserved const int groupbits = 20; const int realidbits = 21; public EGID(uint entityID, ExclusiveGroup.ExclusiveGroupStruct groupID) : this() { DBC.ECS.Check.Require(entityID < bit21, "the entityID value is outside the range, max value: (2^22)-1"); DBC.ECS.Check.Require(groupID < bit20, "the groupID value is outside the range"); _GID = MAKE_GLOBAL_ID(entityID, groupID, 0, 1); } const uint bit21 = 0b0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0001_1111_1111_1111_1111_1111; const uint bit22 = 0b0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0011_1111_1111_1111_1111_1111; const uint bit20 = 0b0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_1111_1111_1111_1111_1111; public uint entityID { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (uint) (_GID & bit22); } } public ExclusiveGroup.ExclusiveGroupStruct groupID => new ExclusiveGroup.ExclusiveGroupStruct((uint) ((_GID >> idbits) & bit20)); // 1 21 20 1 21 // | | realid | groupid |R| entityID | static ulong MAKE_GLOBAL_ID(uint entityId, uint groupId, uint realId, byte hasID) { var makeGlobalId = (((ulong)realId & bit21) << (idbits+groupbits)) | (((ulong)groupId & bit20) << idbits) | ((ulong)entityId & bit22); return makeGlobalId | (ulong) (hasID << idbits + groupbits + realidbits); } public static explicit operator uint(EGID id) { return id.entityID; } public static bool operator ==(EGID obj1, EGID obj2) { throw new NotSupportedException(); } public static bool operator !=(EGID obj1, EGID obj2) { throw new NotSupportedException(); } public bool Equals(EGID other) { throw new NotSupportedException(); } public bool Equals(EGID x, EGID y) { throw new NotSupportedException(); } public int CompareTo(EGID other) { throw new NotSupportedException(); } //in the way it's used, ulong must be always the same for each id/group public static explicit operator ulong(EGID id) { throw new NotSupportedException(); } public int GetHashCode(EGID egid) { throw new NotSupportedException(); } internal EGID(ulong GID) : this() { _GID = GID; } internal EGID(uint entityID, uint groupID) : this() { _GID = MAKE_GLOBAL_ID(entityID, groupID, 0, 1); } internal static EGID UPDATE_REAL_ID_AND_GROUP(EGID egid, uint toGroupID, uint realID) { if (egid.hasID == 0) return new EGID(MAKE_GLOBAL_ID(SAFE_ID(realID), toGroupID, realID, 0)); return new EGID(MAKE_GLOBAL_ID(egid.entityID, toGroupID, realID, 1)); } internal static EGID UPDATE_REAL_ID(EGID egid, uint realID) { if (egid.hasID == 0) return new EGID(MAKE_GLOBAL_ID(SAFE_ID(realID), egid.groupID, realID, 0)); return new EGID(MAKE_GLOBAL_ID(egid.entityID, egid.groupID, realID, 1)); } internal static EGID CREATE_WITHOUT_ID(uint toGroupID, uint realID) { var _GID = MAKE_GLOBAL_ID(SAFE_ID(realID), toGroupID, realID, 0); return new EGID(_GID); } public byte hasID { get { return (byte) (_GID >> idbits + groupbits + realidbits); } } internal uint realID { get { return ((uint)(_GID >> idbits + groupbits)) & bit21; } } static uint SAFE_ID(uint u) { return u | (bit21 + 1); } } } #endif
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Utility.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Utility\Invoke-WebRequest command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class InvokeWebRequest : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public InvokeWebRequest() { this.DisplayName = "Invoke-WebRequest"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Utility\\Invoke-WebRequest"; } } // Arguments /// <summary> /// Provides access to the UseBasicParsing parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> UseBasicParsing { get; set; } /// <summary> /// Provides access to the Uri parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Uri> Uri { get; set; } /// <summary> /// Provides access to the WebSession parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<Microsoft.PowerShell.Commands.WebRequestSession> WebSession { get; set; } /// <summary> /// Provides access to the SessionVariable parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> SessionVariable { get; set; } /// <summary> /// Provides access to the Credential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> Credential { get; set; } /// <summary> /// Provides access to the UseDefaultCredentials parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> UseDefaultCredentials { get; set; } /// <summary> /// Provides access to the CertificateThumbprint parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> CertificateThumbprint { get; set; } /// <summary> /// Provides access to the Certificate parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Security.Cryptography.X509Certificates.X509Certificate> Certificate { get; set; } /// <summary> /// Provides access to the UserAgent parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> UserAgent { get; set; } /// <summary> /// Provides access to the DisableKeepAlive parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> DisableKeepAlive { get; set; } /// <summary> /// Provides access to the TimeoutSec parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> TimeoutSec { get; set; } /// <summary> /// Provides access to the Headers parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Collections.IDictionary> Headers { get; set; } /// <summary> /// Provides access to the MaximumRedirection parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> MaximumRedirection { get; set; } /// <summary> /// Provides access to the Method parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<Microsoft.PowerShell.Commands.WebRequestMethod> Method { get; set; } /// <summary> /// Provides access to the Proxy parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Uri> Proxy { get; set; } /// <summary> /// Provides access to the ProxyCredential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> ProxyCredential { get; set; } /// <summary> /// Provides access to the ProxyUseDefaultCredentials parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> ProxyUseDefaultCredentials { get; set; } /// <summary> /// Provides access to the Body parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object> Body { get; set; } /// <summary> /// Provides access to the ContentType parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> ContentType { get; set; } /// <summary> /// Provides access to the TransferEncoding parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> TransferEncoding { get; set; } /// <summary> /// Provides access to the InFile parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> InFile { get; set; } /// <summary> /// Provides access to the OutFile parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> OutFile { get; set; } /// <summary> /// Provides access to the PassThru parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> PassThru { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(UseBasicParsing.Expression != null) { targetCommand.AddParameter("UseBasicParsing", UseBasicParsing.Get(context)); } if(Uri.Expression != null) { targetCommand.AddParameter("Uri", Uri.Get(context)); } if(WebSession.Expression != null) { targetCommand.AddParameter("WebSession", WebSession.Get(context)); } if(SessionVariable.Expression != null) { targetCommand.AddParameter("SessionVariable", SessionVariable.Get(context)); } if(Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if(UseDefaultCredentials.Expression != null) { targetCommand.AddParameter("UseDefaultCredentials", UseDefaultCredentials.Get(context)); } if(CertificateThumbprint.Expression != null) { targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context)); } if(Certificate.Expression != null) { targetCommand.AddParameter("Certificate", Certificate.Get(context)); } if(UserAgent.Expression != null) { targetCommand.AddParameter("UserAgent", UserAgent.Get(context)); } if(DisableKeepAlive.Expression != null) { targetCommand.AddParameter("DisableKeepAlive", DisableKeepAlive.Get(context)); } if(TimeoutSec.Expression != null) { targetCommand.AddParameter("TimeoutSec", TimeoutSec.Get(context)); } if(Headers.Expression != null) { targetCommand.AddParameter("Headers", Headers.Get(context)); } if(MaximumRedirection.Expression != null) { targetCommand.AddParameter("MaximumRedirection", MaximumRedirection.Get(context)); } if(Method.Expression != null) { targetCommand.AddParameter("Method", Method.Get(context)); } if(Proxy.Expression != null) { targetCommand.AddParameter("Proxy", Proxy.Get(context)); } if(ProxyCredential.Expression != null) { targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context)); } if(ProxyUseDefaultCredentials.Expression != null) { targetCommand.AddParameter("ProxyUseDefaultCredentials", ProxyUseDefaultCredentials.Get(context)); } if(Body.Expression != null) { targetCommand.AddParameter("Body", Body.Get(context)); } if(ContentType.Expression != null) { targetCommand.AddParameter("ContentType", ContentType.Get(context)); } if(TransferEncoding.Expression != null) { targetCommand.AddParameter("TransferEncoding", TransferEncoding.Get(context)); } if(InFile.Expression != null) { targetCommand.AddParameter("InFile", InFile.Get(context)); } if(OutFile.Expression != null) { targetCommand.AddParameter("OutFile", OutFile.Get(context)); } if(PassThru.Expression != null) { targetCommand.AddParameter("PassThru", PassThru.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/rpc/checkout_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.RPC { /// <summary>Holder for reflection information generated from booking/rpc/checkout_svc.proto</summary> public static partial class CheckoutSvcReflection { #region Descriptor /// <summary>File descriptor for booking/rpc/checkout_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CheckoutSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5ib29raW5nL3JwYy9jaGVja291dF9zdmMucHJvdG8SF2hvbG1zLnR5cGVz", "LmJvb2tpbmcucnBjGi5ib29raW5nL2luZGljYXRvcnMvcmVzZXJ2YXRpb25f", "aW5kaWNhdG9yLnByb3RvGjNib29raW5nL2NoZWNrb3V0L2NoZWNrb3V0X2Nh", "bmRpZGF0ZV92aWFiaWxpdHkucHJvdG8iYQobQ2hlY2tvdXRTdmNDaGVja091", "dFJlc3BvbnNlEkIKBlJlc3VsdBgBIAEoDjIyLmhvbG1zLnR5cGVzLmJvb2tp", "bmcucnBjLkNoZWNrb3V0U3ZjQ2hlY2tPdXRSZXN1bHQijQEKMUNoZWNrb3V0", "U3ZjQW1lbmRGb3JFYXJseUltbWVkaWF0ZUNoZWNrb3V0UmVzcG9uc2USWAoG", "UmVzdWx0GAEgASgOMkguaG9sbXMudHlwZXMuYm9va2luZy5ycGMuQ2hlY2tv", "dXRTdmNBbWVuZEZvckVhcmx5SW1tZWRpYXRlQ2hlY2tvdXRSZXN1bHQiWQoX", "Q2hlY2tvdXRVbmRvU3ZjUmVzcG9uc2USPgoGUmVzdWx0GAEgASgOMi4uaG9s", "bXMudHlwZXMuYm9va2luZy5ycGMuQ2hlY2tvdXRVbmRvU3ZjUmVzdWx0KtIB", "ChlDaGVja291dFN2Y0NoZWNrT3V0UmVzdWx0EiUKIUNIRUNLT1VUX1NWQ19D", "SEVDS19PVVRfU1VDQ0VTU0ZVTBAAEikKJUNIRUNLT1VUX1NWQ19DSEVDS19P", "VVRfTk9UX0NIRUNLRURfSU4QARI3CjNDSEVDS09VVF9TVkNfQ0hFQ0tfT1VU", "X0lOQVBQUk9QUklBVEVfREVQQVJUVVJFX0RBVEUQAhIqCiZDSEVDS09VVF9T", "VkNfQ0hFQ0tfT1VUX1VOS05PV05fRkFJTFVSRRADKq4BCi9DaGVja291dFN2", "Y0FtZW5kRm9yRWFybHlJbW1lZGlhdGVDaGVja291dFJlc3VsdBI+CjpDSEVD", "S09VVF9TVkNfQU1FTkRfRk9SX0VBUkxZX0lNTUVESUFURV9DSEVDS09VVF9T", "VUNDRVNTRlVMEAASOwo3Q0hFQ0tPVVRfU1ZDX0FNRU5EX0ZPUl9FQVJMWV9J", "TU1FRElBVEVfQ0hFQ0tPVVRfRkFJTFVSRRABKs8BChVDaGVja291dFVuZG9T", "dmNSZXN1bHQSIAocQ0hFQ0tPVVRfU1ZDX1VORE9fU1VDQ0VTU0ZVTBAAEiAK", "HENIRUNLT1VUX1NWQ19OT1RfQ0hFQ0tFRF9PVVQQARIoCiRDSEVDS09VVF9T", "VkNfSU5BUFBST1BSSUFURV9VTkRPX0RBVEUQAhIgChxDSEVDS09VVF9TVkNf", "VU5LTk9XTl9GQUlMVVJFEAMSJgoiQ0hFQ0tPVVRfU1ZDX1JPT01fQUxSRUFE", "WV9PQ0NVUElFRBAEMsAECgtDaGVja291dFN2YxKPAQodR2V0Q2hlY2tvdXRD", "YW5kaWRhdGVWaWFiaWxpdHkSNC5ob2xtcy50eXBlcy5ib29raW5nLmluZGlj", "YXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3IaOC5ob2xtcy50eXBlcy5ib29r", "aW5nLmNoZWNrb3V0LkNoZWNrb3V0Q2FuZGlkYXRlVmlhYmlsaXR5EoEBChND", "aGVja091dFJlc2VydmF0aW9uEjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRp", "Y2F0b3JzLlJlc2VydmF0aW9uSW5kaWNhdG9yGjQuaG9sbXMudHlwZXMuYm9v", "a2luZy5ycGMuQ2hlY2tvdXRTdmNDaGVja091dFJlc3BvbnNlEqIBCh5BbWVu", "ZEZvckVhcmx5SW1tZWRpYXRlQ2hlY2tvdXQSNC5ob2xtcy50eXBlcy5ib29r", "aW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3IaSi5ob2xtcy50", "eXBlcy5ib29raW5nLnJwYy5DaGVja291dFN2Y0FtZW5kRm9yRWFybHlJbW1l", "ZGlhdGVDaGVja291dFJlc3BvbnNlEnYKDFVuZG9DaGVja291dBI0LmhvbG1z", "LnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRv", "chowLmhvbG1zLnR5cGVzLmJvb2tpbmcucnBjLkNoZWNrb3V0VW5kb1N2Y1Jl", "c3BvbnNlQhqqAhdIT0xNUy5UeXBlcy5Cb29raW5nLlJQQ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Checkout.CheckoutCandidateViabilityReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResult), typeof(global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResult), typeof(global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResult), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResponse), global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResponse.Parser, new[]{ "Result" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResponse), global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResponse.Parser, new[]{ "Result" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResponse), global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResponse.Parser, new[]{ "Result" }, null, null, null) })); } #endregion } #region Enums public enum CheckoutSvcCheckOutResult { [pbr::OriginalName("CHECKOUT_SVC_CHECK_OUT_SUCCESSFUL")] CheckoutSvcCheckOutSuccessful = 0, [pbr::OriginalName("CHECKOUT_SVC_CHECK_OUT_NOT_CHECKED_IN")] CheckoutSvcCheckOutNotCheckedIn = 1, [pbr::OriginalName("CHECKOUT_SVC_CHECK_OUT_INAPPROPRIATE_DEPARTURE_DATE")] CheckoutSvcCheckOutInappropriateDepartureDate = 2, [pbr::OriginalName("CHECKOUT_SVC_CHECK_OUT_UNKNOWN_FAILURE")] CheckoutSvcCheckOutUnknownFailure = 3, } public enum CheckoutSvcAmendForEarlyImmediateCheckoutResult { [pbr::OriginalName("CHECKOUT_SVC_AMEND_FOR_EARLY_IMMEDIATE_CHECKOUT_SUCCESSFUL")] CheckoutSvcAmendForEarlyImmediateCheckoutSuccessful = 0, [pbr::OriginalName("CHECKOUT_SVC_AMEND_FOR_EARLY_IMMEDIATE_CHECKOUT_FAILURE")] CheckoutSvcAmendForEarlyImmediateCheckoutFailure = 1, } public enum CheckoutUndoSvcResult { [pbr::OriginalName("CHECKOUT_SVC_UNDO_SUCCESSFUL")] CheckoutSvcUndoSuccessful = 0, [pbr::OriginalName("CHECKOUT_SVC_NOT_CHECKED_OUT")] CheckoutSvcNotCheckedOut = 1, [pbr::OriginalName("CHECKOUT_SVC_INAPPROPRIATE_UNDO_DATE")] CheckoutSvcInappropriateUndoDate = 2, [pbr::OriginalName("CHECKOUT_SVC_UNKNOWN_FAILURE")] CheckoutSvcUnknownFailure = 3, [pbr::OriginalName("CHECKOUT_SVC_ROOM_ALREADY_OCCUPIED")] CheckoutSvcRoomAlreadyOccupied = 4, } #endregion #region Messages public sealed partial class CheckoutSvcCheckOutResponse : pb::IMessage<CheckoutSvcCheckOutResponse> { private static readonly pb::MessageParser<CheckoutSvcCheckOutResponse> _parser = new pb::MessageParser<CheckoutSvcCheckOutResponse>(() => new CheckoutSvcCheckOutResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckoutSvcCheckOutResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.CheckoutSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcCheckOutResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcCheckOutResponse(CheckoutSvcCheckOutResponse other) : this() { result_ = other.result_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcCheckOutResponse Clone() { return new CheckoutSvcCheckOutResponse(this); } /// <summary>Field number for the "Result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResult Result { get { return result_; } set { result_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckoutSvcCheckOutResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckoutSvcCheckOutResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckoutSvcCheckOutResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Booking.RPC.CheckoutSvcCheckOutResult) input.ReadEnum(); break; } } } } } public sealed partial class CheckoutSvcAmendForEarlyImmediateCheckoutResponse : pb::IMessage<CheckoutSvcAmendForEarlyImmediateCheckoutResponse> { private static readonly pb::MessageParser<CheckoutSvcAmendForEarlyImmediateCheckoutResponse> _parser = new pb::MessageParser<CheckoutSvcAmendForEarlyImmediateCheckoutResponse>(() => new CheckoutSvcAmendForEarlyImmediateCheckoutResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckoutSvcAmendForEarlyImmediateCheckoutResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.CheckoutSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcAmendForEarlyImmediateCheckoutResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcAmendForEarlyImmediateCheckoutResponse(CheckoutSvcAmendForEarlyImmediateCheckoutResponse other) : this() { result_ = other.result_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutSvcAmendForEarlyImmediateCheckoutResponse Clone() { return new CheckoutSvcAmendForEarlyImmediateCheckoutResponse(this); } /// <summary>Field number for the "Result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResult Result { get { return result_; } set { result_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckoutSvcAmendForEarlyImmediateCheckoutResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckoutSvcAmendForEarlyImmediateCheckoutResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckoutSvcAmendForEarlyImmediateCheckoutResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Booking.RPC.CheckoutSvcAmendForEarlyImmediateCheckoutResult) input.ReadEnum(); break; } } } } } public sealed partial class CheckoutUndoSvcResponse : pb::IMessage<CheckoutUndoSvcResponse> { private static readonly pb::MessageParser<CheckoutUndoSvcResponse> _parser = new pb::MessageParser<CheckoutUndoSvcResponse>(() => new CheckoutUndoSvcResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckoutUndoSvcResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.CheckoutSvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutUndoSvcResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutUndoSvcResponse(CheckoutUndoSvcResponse other) : this() { result_ = other.result_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckoutUndoSvcResponse Clone() { return new CheckoutUndoSvcResponse(this); } /// <summary>Field number for the "Result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResult Result { get { return result_; } set { result_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckoutUndoSvcResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckoutUndoSvcResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckoutUndoSvcResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Booking.RPC.CheckoutUndoSvcResult) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; namespace System.Security.Principal { public sealed class NTAccount : IdentityReference { #region Private members private readonly string _name; // // Limit for nt account names for users is 20 while that for groups is 256 // internal const int MaximumAccountNameLength = 256; // // Limit for dns domain names is 255 // internal const int MaximumDomainNameLength = 255; #endregion #region Constructors public NTAccount(string domainName, string accountName) { if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } if (accountName.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, nameof(accountName)); } if (accountName.Length > MaximumAccountNameLength) { throw new ArgumentException(SR.IdentityReference_AccountNameTooLong, nameof(accountName)); } if (domainName != null && domainName.Length > MaximumDomainNameLength) { throw new ArgumentException(SR.IdentityReference_DomainNameTooLong, nameof(domainName)); } Contract.EndContractBlock(); if (domainName == null || domainName.Length == 0) { _name = accountName; } else { _name = domainName + "\\" + accountName; } } public NTAccount(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, nameof(name)); } if (name.Length > (MaximumDomainNameLength + 1 /* '\' */ + MaximumAccountNameLength)) { throw new ArgumentException(SR.IdentityReference_AccountNameTooLong, nameof(name)); } Contract.EndContractBlock(); _name = name; } #endregion #region Inherited properties and methods public override string Value { get { return ToString(); } } public override bool IsValidTargetType(Type targetType) { if (targetType == typeof(SecurityIdentifier)) { return true; } else if (targetType == typeof(NTAccount)) { return true; } else { return false; } } public override IdentityReference Translate(Type targetType) { if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } Contract.EndContractBlock(); if (targetType == typeof(NTAccount)) { return this; // assumes that NTAccount objects are immutable } else if (targetType == typeof(SecurityIdentifier)) { IdentityReferenceCollection irSource = new IdentityReferenceCollection(1); irSource.Add(this); IdentityReferenceCollection irTarget; irTarget = NTAccount.Translate(irSource, targetType, true); return irTarget[0]; } else { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } } public override bool Equals(object o) { return (this == o as NTAccount); // invokes operator== } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(_name); } public override string ToString() { return _name; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, bool forceSuccess) { bool SomeFailed = false; IdentityReferenceCollection Result; Result = Translate(sourceAccounts, targetType, out SomeFailed); if (forceSuccess && SomeFailed) { IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection(); foreach (IdentityReference id in Result) { if (id.GetType() != targetType) { UnmappedIdentities.Add(id); } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities); } return Result; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, out bool someFailed) { if (sourceAccounts == null) { throw new ArgumentNullException(nameof(sourceAccounts)); } Contract.EndContractBlock(); if (targetType == typeof(SecurityIdentifier)) { return TranslateToSids(sourceAccounts, out someFailed); } throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } #endregion #region Operators public static bool operator ==(NTAccount left, NTAccount right) { object l = left; object r = right; if (l == r) { return true; } else if (l == null || r == null) { return false; } else { return (left.ToString().Equals(right.ToString(), StringComparison.OrdinalIgnoreCase)); } } public static bool operator !=(NTAccount left, NTAccount right) { return !(left == right); // invoke operator== } #endregion #region Private methods private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed) { if (sourceAccounts == null) { throw new ArgumentNullException(nameof(sourceAccounts)); } if (sourceAccounts.Count == 0) { throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceAccounts)); } Contract.EndContractBlock(); SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle SidsPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Construct an array of unicode strings // Interop.UNICODE_STRING[] Names = new Interop.UNICODE_STRING[sourceAccounts.Count]; int currentName = 0; foreach (IdentityReference id in sourceAccounts) { NTAccount nta = id as NTAccount; if (nta == null) { throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceAccounts)); } Names[currentName].Buffer = nta.ToString(); if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue) { // this should never happen since we are already validating account name length in constructor and // it is less than this limit Debug.Assert(false, "NTAccount::TranslateToSids - source account name is too long."); throw new InvalidOperationException(); } Names[currentName].Length = (ushort)(Names[currentName].Buffer.Length * 2); Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2); currentName++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES); // // Now perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Interop.mincore.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY || ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES) { throw new OutOfMemoryException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { someFailed = true; } else if (ReturnCode != 0) { int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode)); if (win32ErrorCode != Interop.mincore.Errors.ERROR_TRUSTED_RELATIONSHIP_FAILURE) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode)); } throw new Win32Exception(win32ErrorCode); } // // Interpret the results and generate SID objects // IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count); if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_SID2>()); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count]; SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length); for (int i = 0; i < sourceAccounts.Count; i++) { Interop.LSA_TRANSLATED_SID2 Lts = translatedSids[i]; // // Only some names are recognized as NTAccount objects // switch ((SidNameUse)Lts.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: Result.Add(new SecurityIdentifier(Lts.Sid, true)); break; default: someFailed = true; Result.Add(sourceAccounts[i]); break; } } } else { for (int i = 0; i < sourceAccounts.Count; i++) { Result.Add(sourceAccounts[i]); } } return Result; } finally { LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); SidsPtr.Dispose(); } } #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// OrderChannelPartner /// </summary> [DataContract] public partial class OrderChannelPartner : IEquatable<OrderChannelPartner>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OrderChannelPartner" /> class. /// </summary> /// <param name="autoApprovePurchaseOrder">If true, any purchase order submitted is automatically approved.</param> /// <param name="channelPartnerCode">The code of the channel partner.</param> /// <param name="channelPartnerData">Additional data provided by the channel partner, read-only.</param> /// <param name="channelPartnerOid">Channel partner object identifier, read-only and available on existing channel orders only..</param> /// <param name="channelPartnerOrderId">The order ID assigned by the channel partner for this order..</param> /// <param name="ignoreInvalidShippingMethod">Set to true to ignore invalid shipping method being specified. Only applicable on inserting orders..</param> /// <param name="noRealtimePaymentProcessing">Indicates this order should be placed in Account Receivable for later payment processing.</param> /// <param name="skipPaymentProcessing">Indicates this order was already paid for via a channel purchase and no payment collection should be attempted.</param> /// <param name="storeCompleted">Instructs UltraCart to skip shipping department and mark this order as fully complete. This flag defaults to true. Set this flag to false to shipped product for this order..</param> /// <param name="storeIfPaymentDeclines">If true, any failed payment will place the order in Accounts Receivable rather than rejecting it..</param> /// <param name="treatWarningsAsErrors">Any warnings are raised as errors and halt the import of the order.</param> public OrderChannelPartner(bool? autoApprovePurchaseOrder = default(bool?), string channelPartnerCode = default(string), string channelPartnerData = default(string), int? channelPartnerOid = default(int?), string channelPartnerOrderId = default(string), bool? ignoreInvalidShippingMethod = default(bool?), bool? noRealtimePaymentProcessing = default(bool?), bool? skipPaymentProcessing = default(bool?), bool? storeCompleted = default(bool?), bool? storeIfPaymentDeclines = default(bool?), bool? treatWarningsAsErrors = default(bool?)) { this.AutoApprovePurchaseOrder = autoApprovePurchaseOrder; this.ChannelPartnerCode = channelPartnerCode; this.ChannelPartnerData = channelPartnerData; this.ChannelPartnerOid = channelPartnerOid; this.ChannelPartnerOrderId = channelPartnerOrderId; this.IgnoreInvalidShippingMethod = ignoreInvalidShippingMethod; this.NoRealtimePaymentProcessing = noRealtimePaymentProcessing; this.SkipPaymentProcessing = skipPaymentProcessing; this.StoreCompleted = storeCompleted; this.StoreIfPaymentDeclines = storeIfPaymentDeclines; this.TreatWarningsAsErrors = treatWarningsAsErrors; } /// <summary> /// If true, any purchase order submitted is automatically approved /// </summary> /// <value>If true, any purchase order submitted is automatically approved</value> [DataMember(Name="auto_approve_purchase_order", EmitDefaultValue=false)] public bool? AutoApprovePurchaseOrder { get; set; } /// <summary> /// The code of the channel partner /// </summary> /// <value>The code of the channel partner</value> [DataMember(Name="channel_partner_code", EmitDefaultValue=false)] public string ChannelPartnerCode { get; set; } /// <summary> /// Additional data provided by the channel partner, read-only /// </summary> /// <value>Additional data provided by the channel partner, read-only</value> [DataMember(Name="channel_partner_data", EmitDefaultValue=false)] public string ChannelPartnerData { get; set; } /// <summary> /// Channel partner object identifier, read-only and available on existing channel orders only. /// </summary> /// <value>Channel partner object identifier, read-only and available on existing channel orders only.</value> [DataMember(Name="channel_partner_oid", EmitDefaultValue=false)] public int? ChannelPartnerOid { get; set; } /// <summary> /// The order ID assigned by the channel partner for this order. /// </summary> /// <value>The order ID assigned by the channel partner for this order.</value> [DataMember(Name="channel_partner_order_id", EmitDefaultValue=false)] public string ChannelPartnerOrderId { get; set; } /// <summary> /// Set to true to ignore invalid shipping method being specified. Only applicable on inserting orders. /// </summary> /// <value>Set to true to ignore invalid shipping method being specified. Only applicable on inserting orders.</value> [DataMember(Name="ignore_invalid_shipping_method", EmitDefaultValue=false)] public bool? IgnoreInvalidShippingMethod { get; set; } /// <summary> /// Indicates this order should be placed in Account Receivable for later payment processing /// </summary> /// <value>Indicates this order should be placed in Account Receivable for later payment processing</value> [DataMember(Name="no_realtime_payment_processing", EmitDefaultValue=false)] public bool? NoRealtimePaymentProcessing { get; set; } /// <summary> /// Indicates this order was already paid for via a channel purchase and no payment collection should be attempted /// </summary> /// <value>Indicates this order was already paid for via a channel purchase and no payment collection should be attempted</value> [DataMember(Name="skip_payment_processing", EmitDefaultValue=false)] public bool? SkipPaymentProcessing { get; set; } /// <summary> /// Instructs UltraCart to skip shipping department and mark this order as fully complete. This flag defaults to true. Set this flag to false to shipped product for this order. /// </summary> /// <value>Instructs UltraCart to skip shipping department and mark this order as fully complete. This flag defaults to true. Set this flag to false to shipped product for this order.</value> [DataMember(Name="store_completed", EmitDefaultValue=false)] public bool? StoreCompleted { get; set; } /// <summary> /// If true, any failed payment will place the order in Accounts Receivable rather than rejecting it. /// </summary> /// <value>If true, any failed payment will place the order in Accounts Receivable rather than rejecting it.</value> [DataMember(Name="store_if_payment_declines", EmitDefaultValue=false)] public bool? StoreIfPaymentDeclines { get; set; } /// <summary> /// Any warnings are raised as errors and halt the import of the order /// </summary> /// <value>Any warnings are raised as errors and halt the import of the order</value> [DataMember(Name="treat_warnings_as_errors", EmitDefaultValue=false)] public bool? TreatWarningsAsErrors { 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 OrderChannelPartner {\n"); sb.Append(" AutoApprovePurchaseOrder: ").Append(AutoApprovePurchaseOrder).Append("\n"); sb.Append(" ChannelPartnerCode: ").Append(ChannelPartnerCode).Append("\n"); sb.Append(" ChannelPartnerData: ").Append(ChannelPartnerData).Append("\n"); sb.Append(" ChannelPartnerOid: ").Append(ChannelPartnerOid).Append("\n"); sb.Append(" ChannelPartnerOrderId: ").Append(ChannelPartnerOrderId).Append("\n"); sb.Append(" IgnoreInvalidShippingMethod: ").Append(IgnoreInvalidShippingMethod).Append("\n"); sb.Append(" NoRealtimePaymentProcessing: ").Append(NoRealtimePaymentProcessing).Append("\n"); sb.Append(" SkipPaymentProcessing: ").Append(SkipPaymentProcessing).Append("\n"); sb.Append(" StoreCompleted: ").Append(StoreCompleted).Append("\n"); sb.Append(" StoreIfPaymentDeclines: ").Append(StoreIfPaymentDeclines).Append("\n"); sb.Append(" TreatWarningsAsErrors: ").Append(TreatWarningsAsErrors).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderChannelPartner); } /// <summary> /// Returns true if OrderChannelPartner instances are equal /// </summary> /// <param name="input">Instance of OrderChannelPartner to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderChannelPartner input) { if (input == null) return false; return ( this.AutoApprovePurchaseOrder == input.AutoApprovePurchaseOrder || (this.AutoApprovePurchaseOrder != null && this.AutoApprovePurchaseOrder.Equals(input.AutoApprovePurchaseOrder)) ) && ( this.ChannelPartnerCode == input.ChannelPartnerCode || (this.ChannelPartnerCode != null && this.ChannelPartnerCode.Equals(input.ChannelPartnerCode)) ) && ( this.ChannelPartnerData == input.ChannelPartnerData || (this.ChannelPartnerData != null && this.ChannelPartnerData.Equals(input.ChannelPartnerData)) ) && ( this.ChannelPartnerOid == input.ChannelPartnerOid || (this.ChannelPartnerOid != null && this.ChannelPartnerOid.Equals(input.ChannelPartnerOid)) ) && ( this.ChannelPartnerOrderId == input.ChannelPartnerOrderId || (this.ChannelPartnerOrderId != null && this.ChannelPartnerOrderId.Equals(input.ChannelPartnerOrderId)) ) && ( this.IgnoreInvalidShippingMethod == input.IgnoreInvalidShippingMethod || (this.IgnoreInvalidShippingMethod != null && this.IgnoreInvalidShippingMethod.Equals(input.IgnoreInvalidShippingMethod)) ) && ( this.NoRealtimePaymentProcessing == input.NoRealtimePaymentProcessing || (this.NoRealtimePaymentProcessing != null && this.NoRealtimePaymentProcessing.Equals(input.NoRealtimePaymentProcessing)) ) && ( this.SkipPaymentProcessing == input.SkipPaymentProcessing || (this.SkipPaymentProcessing != null && this.SkipPaymentProcessing.Equals(input.SkipPaymentProcessing)) ) && ( this.StoreCompleted == input.StoreCompleted || (this.StoreCompleted != null && this.StoreCompleted.Equals(input.StoreCompleted)) ) && ( this.StoreIfPaymentDeclines == input.StoreIfPaymentDeclines || (this.StoreIfPaymentDeclines != null && this.StoreIfPaymentDeclines.Equals(input.StoreIfPaymentDeclines)) ) && ( this.TreatWarningsAsErrors == input.TreatWarningsAsErrors || (this.TreatWarningsAsErrors != null && this.TreatWarningsAsErrors.Equals(input.TreatWarningsAsErrors)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AutoApprovePurchaseOrder != null) hashCode = hashCode * 59 + this.AutoApprovePurchaseOrder.GetHashCode(); if (this.ChannelPartnerCode != null) hashCode = hashCode * 59 + this.ChannelPartnerCode.GetHashCode(); if (this.ChannelPartnerData != null) hashCode = hashCode * 59 + this.ChannelPartnerData.GetHashCode(); if (this.ChannelPartnerOid != null) hashCode = hashCode * 59 + this.ChannelPartnerOid.GetHashCode(); if (this.ChannelPartnerOrderId != null) hashCode = hashCode * 59 + this.ChannelPartnerOrderId.GetHashCode(); if (this.IgnoreInvalidShippingMethod != null) hashCode = hashCode * 59 + this.IgnoreInvalidShippingMethod.GetHashCode(); if (this.NoRealtimePaymentProcessing != null) hashCode = hashCode * 59 + this.NoRealtimePaymentProcessing.GetHashCode(); if (this.SkipPaymentProcessing != null) hashCode = hashCode * 59 + this.SkipPaymentProcessing.GetHashCode(); if (this.StoreCompleted != null) hashCode = hashCode * 59 + this.StoreCompleted.GetHashCode(); if (this.StoreIfPaymentDeclines != null) hashCode = hashCode * 59 + this.StoreIfPaymentDeclines.GetHashCode(); if (this.TreatWarningsAsErrors != null) hashCode = hashCode * 59 + this.TreatWarningsAsErrors.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // ChannelPartnerOrderId (string) maxLength if(this.ChannelPartnerOrderId != null && this.ChannelPartnerOrderId.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ChannelPartnerOrderId, length must be less than 50.", new [] { "ChannelPartnerOrderId" }); } yield break; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Net.Http.Headers; using System.Numerics; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Vortice.DCommon; using Vortice.Direct2D1; using Xilium.CefGlue; namespace NetDimension.NanUI.Browser { internal sealed class WinFormiumRenderHandlerUsingHwnd : CefRenderHandler { ID2D1Factory _d2dFactory = null; ID2D1HwndRenderTarget _renderTarget = null; bool _isPopupShown = false; CefRectangle? _popupRect = null; private int _view_width; private int _view_height; private readonly Formium _owner; public WinFormiumRenderHandlerUsingHwnd(Formium owner) { _owner = owner; D2D1.D2D1CreateFactory(FactoryType.SingleThreaded, out _d2dFactory); } public void CreateDeviceResource() { if (_renderTarget == null) { var renderProps = new RenderTargetProperties() { Type = RenderTargetType.Hardware, Usage = RenderTargetUsage.None, PixelFormat = new PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), MinLevel = FeatureLevel.Default, DpiX = 96, DpiY = 96 }; var hwndRenderTargetProperties = new HwndRenderTargetProperties() { Hwnd = _owner.HostWindowHandle, PresentOptions = PresentOptions.RetainContents, PixelSize = new Vortice.Mathematics.Size(_owner.HostWindowInternal.ClientRectangle.Width, _owner.HostWindowInternal.ClientRectangle.Height) }; _renderTarget = _d2dFactory.CreateHwndRenderTarget(renderProps, hwndRenderTargetProperties); } } public void DiscardDeviceResources() { _renderTarget.Dispose(); _renderTarget = null; GC.Collect(); } protected override CefAccessibilityHandler GetAccessibilityHandler() { return null; } //Screen _lastScreen = null; protected override bool GetScreenInfo(CefBrowser browser, CefScreenInfo screenInfo) { var handle = _owner.HostWindowHandle; var screen = Screen.FromHandle(handle); screenInfo.DeviceScaleFactor = DpiHelper.GetScaleFactorForCurrentWindow(handle); GetViewRect(browser, out var rectView); screenInfo.Rectangle = rectView; screenInfo.AvailableRectangle = rectView; return true; } protected override void GetViewRect(CefBrowser browser, out CefRectangle rect) { var handle = _owner.HostWindowHandle; var scaleFactor = DpiHelper.GetScaleFactorForCurrentWindow(handle); var clientRect = new RECT(); rect = new CefRectangle(); User32.GetClientRect(handle, ref clientRect); rect.X = rect.Y = 0; if (User32.IsIconic(handle)||clientRect.Width ==0 || clientRect.Height == 0) { var placement = new WINDOWPLACEMENT(); User32.GetWindowPlacement(_owner.HostWindowHandle, ref placement); clientRect = placement.rcNormalPosition; rect.Width = (int)(clientRect.Width / scaleFactor); rect.Height = (int)(clientRect.Height / scaleFactor); } else { rect.Width = (int)(clientRect.Width / scaleFactor); rect.Height = (int)(clientRect.Height / scaleFactor); } if (clientRect.Width != _view_width || clientRect.Height != _view_height) { _view_width = clientRect.Width; _view_height = clientRect.Height; _renderTarget?.Resize(new Vortice.Mathematics.Size(_view_width, _view_height)); } } protected override bool GetRootScreenRect(CefBrowser browser, ref CefRectangle rect) { return false; } protected override bool GetScreenPoint(CefBrowser browser, int viewX, int viewY, ref int screenX, ref int screenY) { var scaleFactor = DpiHelper.GetScaleFactorForCurrentWindow(_owner.HostWindowHandle); var pt = new POINT((int)(viewX * scaleFactor), (int)(viewY * scaleFactor)); User32.ClientToScreen(_owner.HostWindowHandle, ref pt); screenX = pt.x; screenY = pt.y; return true; } protected override void OnAcceleratedPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr sharedHandle) { } protected override void OnCursorChange(CefBrowser browser, IntPtr cursorHandle, CefCursorType type, CefCursorInfo customCursorInfo) { _owner.InvokeIfRequired(() => _owner.HostWindowInternal.Cursor = new Cursor(cursorHandle)); } protected override void OnImeCompositionRangeChanged(CefBrowser browser, CefRange selectedRange, CefRectangle[] characterBounds) { } protected override void OnPopupShow(CefBrowser browser, bool show) { _isPopupShown = show; if (show == false) { _popupRect = null; if (_cachedPopupImage != null) { _cachedPopupImage.Dispose(); _cachedPopupImage = null; GC.Collect(); } } base.OnPopupShow(browser, show); } protected override void OnPopupSize(CefBrowser browser, CefRectangle rect) { _popupRect = rect; } ID2D1Bitmap _cachedPopupImage = null; protected override void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr buffer, int width, int height) { if (width <= 0 || height <= 0) { return; } CreateDeviceResource(); _renderTarget.BeginDraw(); if (type == CefPaintElementType.View) { var bmp = _renderTarget.CreateBitmap(new Vortice.Mathematics.Size(width, height), buffer, width * 4, new BitmapProperties(new PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied))); if (!_isPopupShown) { _renderTarget.Clear(Color.Transparent); } _renderTarget.DrawBitmap(bmp); bmp.Dispose(); } else if (type == CefPaintElementType.Popup) { var bmp = _renderTarget.CreateBitmap(new Vortice.Mathematics.Size(width, height), buffer, width * 4, new BitmapProperties(new PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied))); if (_cachedPopupImage != null) { _cachedPopupImage.Dispose(); _cachedPopupImage = null; GC.Collect(); } _cachedPopupImage = _renderTarget.CreateSharedBitmap(bmp, new BitmapProperties { PixelFormat = new PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied) }); bmp.Dispose(); } //var layer = _renderTarget.CreateLayer(); //var layerParameter = new LayerParameters //{ // ContentBounds = new Vortice.RawRectF(0, 0, width, height), // Opacity = 1 //}; //_renderTarget.PushLayer(ref layerParameter, layer); if (_cachedPopupImage != null && _isPopupShown && _popupRect.HasValue) { var scaleFactor = DpiHelper.GetScaleFactorForCurrentWindow(_owner.HostWindowHandle); var x = _popupRect.Value.X * scaleFactor; var y = _popupRect.Value.Y * scaleFactor; var popupWidth = _popupRect.Value.Width * scaleFactor; var popupHeight = _popupRect.Value.Height * scaleFactor; var right = x + popupWidth; var bottom = y + popupHeight; _renderTarget.DrawBitmap(_cachedPopupImage, new Vortice.RawRectF(x, y, right, bottom), 1f, BitmapInterpolationMode.Linear, new Vortice.RawRectF(0, 0, popupWidth, popupHeight)); } //_renderTarget.PopLayer(); //layer.Dispose(); if (_renderTarget.EndDraw().Failure) { DiscardDeviceResources(); } } protected override void OnScrollOffsetChanged(CefBrowser browser, double x, double y) { } protected override void OnTextSelectionChanged(CefBrowser browser, string selectedText, CefRange selectedRange) { base.OnTextSelectionChanged(browser, selectedText, selectedRange); } protected override void OnVirtualKeyboardRequested(CefBrowser browser, CefTextInputMode inputMode) { base.OnVirtualKeyboardRequested(browser, inputMode); } } }
// 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; /// <summary> /// Array.Sort (T[]) /// </summary> public class ArraySort6 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; string[] s2 = new string[]{"Allin", "Jack", "Mary", "Mike", "Peter", "Tom"}; Array.Sort<string>(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array"); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; i2[i] = value; } Array.Sort<int>(i1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array "); try { int length = TestLibrary.Generator.GetInt16(-55); char[] c1 = new char[length]; char[] c2 = new char[length]; for (int i = 0; i < length; i++) { char value = TestLibrary.Generator.GetChar(-55); c1[i] = value; c2[i] = value; } Array.Sort<char>(c1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (c2[i] > c2[j]) { char temp = c2[i]; c2[i] = c2[j]; c2[j] = temp; } } } for (int i = 0; i < length; i++) { if (c1[i] != c2[i]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort a string array including null reference "); try { string[] s1 = new string[6]{"Jack", "Mary", null, "Peter", "Tom", "Allin"}; string[] s2 = new string[]{null, "Allin", "Jack", "Mary", "Peter", "Tom"}; Array.Sort<string>(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Sort customized type array"); try { C[] c_array = new C[5]; C[] c_result = new C[5]; for (int i = 0; i < 5; i++) { int value = TestLibrary.Generator.GetInt32(-55); C c1 = new C(value); c_array.SetValue(c1, i); c_result.SetValue(c1, i); } //sort manually C temp; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { if (c_result[i].c > c_result[i + 1].c) { temp = c_result[i]; c_result[i] = c_result[i + 1]; c_result[i + 1] = temp; } } } Array.Sort<C>(c_array); for (int i = 0; i < 5; i++) { if (c_result[i].c != c_array[i].c) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is null "); try { string[] s1 = null; Array.Sort<string>(s1); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: One or more elements in array do not implement the IComparable interface"); try { A<int>[] i1 = new A<int>[5] { new A<int>(7), new A<int>(99), new A<int>(-23), new A<int>(0), new A<int>(345) }; Array.Sort<A<int>>(i1); TestLibrary.TestFramework.LogError("103", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArraySort6 test = new ArraySort6(); TestLibrary.TestFramework.BeginTestCase("ArraySort6"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class C : IComparable { protected int c_value; public C(int a) { this.c_value = a; } public int c { get { return c_value; } } #region IComparable Members public int CompareTo(object obj) { if (this.c_value <= ((C)obj).c) { return -1; } else { return 1; } } #endregion } class A<T> { protected T a_value; public A(T a) { this.a_value = a; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { internal enum NCFlags : int { InstanceTypeIsNCHead = 1, InstanceTypeIsWriteable = 4 } internal enum ApplicationPartitionType : int { Unknown = -1, ADApplicationPartition = 0, ADAMApplicationPartition = 1 } public class ApplicationPartition : ActiveDirectoryPartition { private bool _disposed = false; private ApplicationPartitionType _appType = (ApplicationPartitionType)(-1); private bool _committed = true; private DirectoryEntry _domainDNSEntry = null; private DirectoryEntry _crossRefEntry = null; private string _dnsName = null; private DirectoryServerCollection _cachedDirectoryServers = null; private bool _securityRefDomainModified = false; private string _securityRefDomain = null; #region constructors // Public Constructors public ApplicationPartition(DirectoryContext context, string distinguishedName) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, null, false); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, "domainDns"); } public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, objectClass); } // Internal Constructors internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.directoryEntryMgr = directoryEntryMgr; _appType = appType; _dnsName = dnsName; } internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, DirectoryEntryManager directoryEntryMgr) : this(context, distinguishedName, dnsName, GetApplicationPartitionType(context), directoryEntryMgr) { } #endregion constructors #region IDisposable // private Dispose method protected override void Dispose(bool disposing) { if (!_disposed) { try { // if there are any managed or unmanaged // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. if (_crossRefEntry != null) { _crossRefEntry.Dispose(); _crossRefEntry = null; } if (_domainDNSEntry != null) { _domainDNSEntry.Dispose(); _domainDNSEntry = null; } _disposed = true; } finally { base.Dispose(); } } } #endregion IDisposable #region public methods public static ApplicationPartition GetApplicationPartition(DirectoryContext context) { // validate the context if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ApplicationPartiton if (context.ContextType != DirectoryContextType.ApplicationPartition) { throw new ArgumentException(SR.TargetShouldBeAppNCDnsName, "context"); } // target must be ndnc dns name if (!context.isNdnc()) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } // work with copy of the context context = new DirectoryContext(context); // bind to the application partition head (this will verify credentials) string distinguishedName = Utils.GetDNFromDnsName(context.Name); DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry appNCHead = null; try { appNCHead = directoryEntryMgr.GetCachedDirectoryEntry(distinguishedName); // need to force the bind appNCHead.Bind(true); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new ApplicationPartition(context, distinguishedName, context.Name, ApplicationPartitionType.ADApplicationPartition, directoryEntryMgr); } public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName) { ApplicationPartition partition = null; DirectoryEntryManager directoryEntryMgr = null; DirectoryContext appNCContext = null; // check that the argument is not null if (context == null) throw new ArgumentNullException("context"); if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context"); } if (context.Name != null) { // the target should be a valid forest name, configset name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer())) { throw new ArgumentException(SR.NotADOrADAM, "context"); } } // check that the distingushed name of the application partition is not null or empty if (distinguishedName == null) throw new ArgumentNullException("distinguishedName"); if (distinguishedName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName"); if (!Utils.IsValidDNFormat(distinguishedName)) throw new ArgumentException(SR.InvalidDNFormat, "distinguishedName"); // work with copy of the context context = new DirectoryContext(context); // search in the partitions container of the forest for // crossRef objects that have their nCName set to the specified distinguishedName directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry partitionsEntry = null; try { partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } // build the filter StringBuilder str = new StringBuilder(15); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=crossRef)("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.804:="); str.Append((int)SystemFlag.SystemFlagNtdsNC); str.Append(")(!("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.803:="); str.Append((int)SystemFlag.SystemFlagNtdsDomain); str.Append("))("); str.Append(PropertyManager.NCName); str.Append("="); str.Append(Utils.GetEscapedFilterValue(distinguishedName)); str.Append("))"); string filter = str.ToString(); string[] propertiesToLoad = new string[2]; propertiesToLoad[0] = PropertyManager.DnsRoot; propertiesToLoad[1] = PropertyManager.NCName; ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/); SearchResult res = null; try { res = searcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { partitionsEntry.Dispose(); } if (res == null) { // the specified application partition could not be found in the given forest throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } string appNCDnsName = null; try { appNCDnsName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? (string)res.Properties[PropertyManager.DnsRoot][0] : null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // verify that if the target is a server, then this partition is a naming context on it ApplicationPartitionType appType = GetApplicationPartitionType(context); if (context.ContextType == DirectoryContextType.DirectoryServer) { bool hostsCurrentPartition = false; DistinguishedName appNCDN = new DistinguishedName(distinguishedName); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string namingContext in rootDSE.Properties[PropertyManager.NamingContexts]) { DistinguishedName dn = new DistinguishedName(namingContext); if (dn.Equals(appNCDN)) { hostsCurrentPartition = true; break; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } if (!hostsCurrentPartition) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } appNCContext = context; } else { // we need to find a server which hosts this application partition if (appType == ApplicationPartitionType.ADApplicationPartition) { int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, appNCDnsName, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindByName - domainControllerInfo.DomainControllerName.Length <= 2"); string serverName = domainControllerInfo.DomainControllerName.Substring(2); appNCContext = Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context); } else { // this will find an adam instance that hosts this partition and which is alive and responding. string adamInstName = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name; appNCContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context); } } partition = new ApplicationPartition(appNCContext, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), appNCDnsName, appType, directoryEntryMgr); return partition; } public DirectoryServer FindDirectoryServer() { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public DirectoryServer FindDirectoryServer(bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(null); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, null)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(siteName); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, siteName)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(null); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(siteName); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public void Delete() { CheckIfDisposed(); // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // Get the partitions container and delete the crossRef entry for this // application partition DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { GetCrossRefEntry(); partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { partitionsEntry.Dispose(); } } public void Save() { CheckIfDisposed(); if (!_committed) { bool createManually = false; if (_appType == ApplicationPartitionType.ADApplicationPartition) { try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072029)) { // inappropriate authentication (we might have fallen back to NTLM) createManually = true; } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // for ADAM we always create the crossRef manually before creating the domainDNS object createManually = true; } if (createManually) { // we need to first save the cross ref entry try { InitializeCrossRef(partitionName); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { // //delete the crossRef entry // DirectoryEntry partitionsEntry = _crossRefEntry.Parent; try { partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e2) { throw ExceptionHelper.GetExceptionFromCOMException(e2); } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // if the crossRef is created manually we need to refresh the cross ref entry to get the changes that were made // due to the creation of the partition try { _crossRefEntry.RefreshCache(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } // When we create a domainDNS object on DC1 (Naming Master = DC2), // then internally DC1 will contact DC2 to create the disabled crossRef object. // DC2 will force replicate the crossRef object to DC1. DC1 will then create // the domainDNS object and enable the crossRef on DC1 (not DC2). // Here we need to force replicate the enabling of the crossRef to the FSMO (DC2) // so that we can later add replicas (which need to modify an attribute on the crossRef // on DC2, the FSMO, and can only be done if the crossRef on DC2 is enabled) // get the ntdsa name of the server on which the partition is created DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string primaryServerNtdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); // get the DN of the crossRef entry that needs to be replicated to the fsmo role if (_appType == ApplicationPartitionType.ADApplicationPartition) { // for AD we may not have the crossRef entry yet GetCrossRefEntry(); } string crossRefDN = (string)PropertyManager.GetPropertyValue(context, _crossRefEntry, PropertyManager.DistinguishedName); // Now set the operational attribute "replicateSingleObject" on the Rootdse of the fsmo role // to <ntdsa name of the source>:<DN of the crossRef object which needs to be replicated> DirectoryContext fsmoContext = Utils.GetNewDirectoryContext(GetNamingRoleOwner(), DirectoryContextType.DirectoryServer, context); DirectoryEntry fsmoRootDSE = DirectoryEntryManager.GetDirectoryEntry(fsmoContext, WellKnownDN.RootDSE); try { fsmoRootDSE.Properties[PropertyManager.ReplicateSingleObject].Value = primaryServerNtdsaName + ":" + crossRefDN; fsmoRootDSE.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { fsmoRootDSE.Dispose(); } // the partition has been created _committed = true; // commit the replica locations information or security reference domain if applicable if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { if (_cachedDirectoryServers != null) { _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].AddRange(_cachedDirectoryServers.GetMultiValuedProperty()); } if (_securityRefDomainModified) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = _securityRefDomain; } try { _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // just save the crossRef entry for teh directory servers and the // security reference domain information if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { try { // we should already have the crossRef entries as some attribute on it has already // been modified Debug.Assert(_crossRefEntry != null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null."); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } // invalidate cached info _cachedDirectoryServers = null; _securityRefDomainModified = false; } public override DirectoryEntry GetDirectoryEntry() { CheckIfDisposed(); if (!_committed) { throw new InvalidOperationException(SR.CannotGetObject); } return DirectoryEntryManager.GetDirectoryEntry(context, Name); } #endregion public methods #region public properties public DirectoryServerCollection DirectoryServers { get { CheckIfDisposed(); if (_cachedDirectoryServers == null) { ReadOnlyDirectoryServerCollection servers = (_committed) ? FindAllDirectoryServers() : new ReadOnlyDirectoryServerCollection(); bool isADAM = (_appType == ApplicationPartitionType.ADAMApplicationPartition) ? true : false; // Get the cross ref entry if we don't already have it if (_committed) { GetCrossRefEntry(); } // // If the application partition is already committed at this point, we pass in the directory entry for teh crossRef, so any modifications // are made directly on the crossRef entry. If at this point we do not have a crossRefEntry, we pass in null, while saving, we get the information // from the collection and set it on the appropriate attribute on the crossRef directory entry. // // _cachedDirectoryServers = new DirectoryServerCollection(context, (_committed) ? _crossRefEntry : null, isADAM, servers); } return _cachedDirectoryServers; } } public string SecurityReferenceDomain { get { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); try { if (_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Count > 0) { return (string)_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value; } else { return null; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { return _securityRefDomain; } } set { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); // modify the security reference domain // this will get committed when the crossRefEntry is committed if (value == null) { if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSSDReferenceDomain)) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Clear(); _securityRefDomainModified = true; } } else { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = value; _securityRefDomainModified = true; } } else { if (!((_securityRefDomain == null) && (value == null))) { _securityRefDomain = value; _securityRefDomainModified = true; } } } } #endregion public properties #region private methods private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string objectClass, bool objectClassSpecified) { // validate context if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be DirectoryServer if ((context.Name == null) || (!context.isServer())) { throw new ArgumentException(SR.TargetShouldBeServer, "context"); } // check that the distinguished name is not null or empty if (distinguishedName == null) { throw new ArgumentNullException("distinguishedName"); } if (distinguishedName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName"); } // initialize private variables this.context = new DirectoryContext(context); this.directoryEntryMgr = new DirectoryEntryManager(this.context); // validate the distinguished name // Utils.GetDnsNameFromDN will throw an ArgumentException if the dn is not valid (cannot be syntactically converted to dns name) _dnsName = Utils.GetDnsNameFromDN(distinguishedName); this.partitionName = distinguishedName; // // if the partition being created is a one-level partition, we do not support it // Component[] components = Utils.GetDNComponents(distinguishedName); if (components.Length == 1) { throw new NotSupportedException(SR.OneLevelPartitionNotSupported); } // check if the object class can be specified _appType = GetApplicationPartitionType(this.context); if ((_appType == ApplicationPartitionType.ADApplicationPartition) && (objectClassSpecified)) { throw new InvalidOperationException(SR.NoObjectClassForADPartition); } else if (objectClassSpecified) { // ADAM case and objectClass is explicitly specified, so must be validated if (objectClass == null) { throw new ArgumentNullException("objectClass"); } if (objectClass.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "objectClass"); } } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // the target in the directory context could be the netbios name of the server, so we will get the dns name // (since application partition creation will fail if dns name is not specified) // string serverDnsName = null; try { DirectoryEntry rootDSEEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); serverDnsName = (string)PropertyManager.GetPropertyValue(this.context, rootDSEEntry, PropertyManager.DnsHostName); } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(this.context, e); } this.context = Utils.GetNewDirectoryContext(serverDnsName, DirectoryContextType.DirectoryServer, context); } } private void CreateApplicationPartition(string distinguishedName, string objectClass) { if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // AD // 1. Bind to the non-existent application partition using the fast bind and delegation option // 2. Get the Parent object and create a new "domainDNS" object under it // 3. Set the instanceType and the description for the application partitin object // DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind | AuthenticationTypes.Delegation; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.GetServerName() + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), PropertyManager.DomainDNS); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } else { // // ADAM // 1. Bind to the partitions container on the domain naming owner instance // 2. Create a disabled crossRef object for the new application partition // 3. Bind to the target hint and follow the same steps as for AD // try { InitializeCrossRef(distinguishedName); DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.Name + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), objectClass); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } private void InitializeCrossRef(string distinguishedName) { if (_crossRefEntry != null) // already initialized return; DirectoryEntry partitionsEntry = null; try { string namingFsmoName = GetNamingRoleOwner(); DirectoryContext roleOwnerContext = Utils.GetNewDirectoryContext(namingFsmoName, DirectoryContextType.DirectoryServer, context); partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(roleOwnerContext, WellKnownDN.PartitionsContainer); string uniqueName = "CN={" + Guid.NewGuid() + "}"; _crossRefEntry = partitionsEntry.Children.Add(uniqueName, "crossRef"); string dnsHostName = null; if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { // Bind to rootdse and get the server name DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string ntdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); dnsHostName = Utils.GetAdamHostNameAndPortsFromNTDSA(context, ntdsaName); } else { // for AD the name in the context will be the dns name of the server dnsHostName = context.Name; } // create disabled cross ref object _crossRefEntry.Properties[PropertyManager.DnsRoot].Value = dnsHostName; _crossRefEntry.Properties[PropertyManager.Enabled].Value = false; _crossRefEntry.Properties[PropertyManager.NCName].Value = distinguishedName; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (partitionsEntry != null) { partitionsEntry.Dispose(); } } } private static ApplicationPartitionType GetApplicationPartitionType(DirectoryContext context) { ApplicationPartitionType type = ApplicationPartitionType.Unknown; DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string supportedCapability in rootDSE.Properties[PropertyManager.SupportedCapabilities]) { if (String.Compare(supportedCapability, SupportedCapability.ADOid, StringComparison.OrdinalIgnoreCase) == 0) { type = ApplicationPartitionType.ADApplicationPartition; } if (String.Compare(supportedCapability, SupportedCapability.ADAMOid, StringComparison.OrdinalIgnoreCase) == 0) { type = ApplicationPartitionType.ADAMApplicationPartition; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } // should not happen if (type == ApplicationPartitionType.Unknown) { throw new ActiveDirectoryOperationException(SR.ApplicationPartitionTypeUnknown); } return type; } // we always get the crossEntry bound to the FSMO role // this is so that we do not encounter any replication delay related issues internal DirectoryEntry GetCrossRefEntry() { if (_crossRefEntry != null) { return _crossRefEntry; } DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { _crossRefEntry = Utils.GetCrossRefEntry(context, partitionsEntry, Name); } finally { partitionsEntry.Dispose(); } return _crossRefEntry; } internal string GetNamingRoleOwner() { string namingFsmo = null; DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { if (_appType == ApplicationPartitionType.ADApplicationPartition) { namingFsmo = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } else { namingFsmo = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } } finally { partitionsEntry.Dispose(); } return namingFsmo; } private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; LocatorOptions flag = 0; int errorCode = 0; DomainControllerInfo domainControllerInfo; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // set the force rediscovery flag if required if (forceRediscovery) { flag = LocatorOptions.ForceRediscovery; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, _dnsName, siteName, (long)flag | (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.ReplicaNotFound, typeof(DirectoryServer), null); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindDirectoryServerInternal - domainControllerInfo.DomainControllerName.Length <= 2"); string dcName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the domain controller passing on only the // credentials from the forest context DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); directoryServer = new DomainController(dcContext, dcName); return directoryServer; } private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ArrayList dcList = new ArrayList(); foreach (string dcName in Utils.GetReplicaList(context, Name, siteName, false /* isDefaultNC */, false /* isADAM */, false /* mustBeGC */)) { DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); dcList.Add(new DomainController(dcContext, dcName)); } return new ReadOnlyDirectoryServerCollection(dcList); } private ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } long flag = (long)PrivateLocatorFlags.OnlyLDAPNeeded; return new ReadOnlyDirectoryServerCollection(Locator.EnumerateDomainControllers(context, _dnsName, siteName, flag)); } #endregion private methods } }
// 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.Data.Tests.Common { public partial class DbDataReaderTest { [Fact] public void GetBooleanByColumnNameTest() { SkipRows(3); var expected = true; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetBoolean("boolean_col"); Assert.Equal(expected, actual); } [Fact] public void GetByteByColumnNameTest() { SkipRows(3); var expected = (byte)0x00; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetByte("byte_col"); Assert.Equal(expected, actual); } [Fact] public void GetBytesByColumnNameTest() { SkipRows(3); var expected = new byte[] { 0xAD, 0xBE }; // The row after rowsToSkip _dataReader.Read(); var actual = new byte[1024]; var length = _dataReader.GetBytes("binary_col", 1, actual, 0, 2); Assert.Equal(expected.Length, length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } [Fact] public void GetCharByColumnNameTest() { SkipRows(3); var expected = 'E'; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetChar("char_col"); Assert.Equal(expected, actual); } [Fact] public void GetCharsByColumnNameTest() { SkipRows(3); var expected = new char[] { 'N', 'E', 'T' }; // The row after rowsToSkip _dataReader.Read(); const int dataLength = 1024; var actual = new char[dataLength]; var length = _dataReader.GetChars("text_col", 1, actual, 0, dataLength); Assert.Equal(expected.Length, length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } [Fact] public void GetDateTimeByColumnNameTest() { SkipRows(3); var expected = new DateTime(2016, 6, 27); // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetDateTime("datetime_col"); Assert.Equal(expected, actual); } [Fact] public void GetDecimalByColumnNameTest() { SkipRows(3); var expected = 810.72m; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetDecimal("decimal_col"); Assert.Equal(expected, actual); } [Fact] public void GetDoubleByColumnNameTest() { SkipRows(3); var expected = Math.PI; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetDouble("double_col"); Assert.Equal(expected, actual); } [Fact] public void GetFieldValueByColumnNameTest() { SkipRows(3); var expected = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetFieldValue<byte[]>("binary_col"); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } [Fact] public void GetFloatByColumnNameTest() { SkipRows(3); var expected = 776.90f; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetFloat("float_col"); Assert.Equal(expected, actual); } [Fact] public void GetGuidByColumnNameTest() { SkipRows(3); var expected = Guid.Parse("893e4fe8-299a-465a-a600-3cd4ad91629a"); // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetGuid("guid_col"); Assert.Equal(expected, actual); } [Fact] public void GetInt16ByColumnNameTest() { SkipRows(3); short expected = 12345; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetInt16("short_col"); Assert.Equal(expected, actual); } [Fact] public void GetInt32ByColumnNameTest() { SkipRows(3); var expected = 1234567890; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetInt32("int_col"); Assert.Equal(expected, actual); } [Fact] public void GetInt64ByColumnNameTest() { SkipRows(3); var expected = 1234567890123456789; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetInt64("long_col"); Assert.Equal(expected, actual); } [Fact] public void GetStreamByColumnNameTest() { SkipRows(3); var expected = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; // The row after rowsToSkip _dataReader.Read(); var stream = _dataReader.GetStream("binary_col"); Assert.NotNull(stream); var actual = new byte[1024]; var readLength = stream.Read(actual, 0, actual.Length); Assert.Equal(expected.Length, readLength); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } [Fact] public void GetStringByColumnNameTest() { SkipRows(3); var expected = ".NET"; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetString("text_col"); Assert.Equal(expected, actual); } [Fact] public void GetTextReaderByColumnNameTest() { SkipRows(3); var expected = ".NET"; // The row after rowsToSkip _dataReader.Read(); var textReader = _dataReader.GetTextReader("text_col"); Assert.NotNull(textReader); var actual = textReader.ReadToEnd(); Assert.Equal(expected, actual); } [Fact] public void GetValueByColumnNameTest() { SkipRows(3); var expected = ".NET"; // The row after rowsToSkip _dataReader.Read(); var actual = _dataReader.GetValue("text_col") as string; Assert.NotNull(actual); Assert.Equal(expected, actual); } [Fact] public void IsDBNullByColumnNameTest() { SkipRows(3); // The row after rowsToSkip _dataReader.Read(); Assert.False(_dataReader.IsDBNull("text_col")); Assert.True(_dataReader.IsDBNull("dbnull_col")); } private void SkipRows(int rowsToSkip) { var i = 0; do { _dataReader.Read(); } while (++i < rowsToSkip); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using Raven.Client.Documents.Session; using System.Threading; using Raven.Client.Documents; using System.Linq.Expressions; using Raven.Client.Documents.Operations; namespace SPR.Blog.Models { public class RavenDbBlogDataStore : IBlogDataStore { private readonly DocumentStore _documentStore; private readonly Lazy<IAsyncDocumentSession> _currentAsyncSession; private readonly Lazy<IDocumentSession> _currentSyncSession; private DocumentStore DocumentStore => _documentStore; private IAsyncDocumentSession CurrentAsyncSession => _currentAsyncSession.Value; private IDocumentSession CurrentSyncSession => _currentSyncSession.Value; public IQueryable<Post> Posts => CurrentSyncSession.Query<Post>(); public RavenDbBlogDataStore(DocumentStore documentStore) { _documentStore = documentStore; _currentSyncSession = new Lazy<IDocumentSession>(() => _documentStore.OpenSession()); _currentAsyncSession = new Lazy<IAsyncDocumentSession>(() => _documentStore.OpenAsyncSession()); } public async Task<IEnumerable<Post>> GetPostsAsync(int pageNumber = 1, int countByPage = 20, Expression<Func<Post, bool>> filter = null, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); IQueryable<Post> source; if (filter == null) source = Posts; else source = Queryable.Where(Posts, filter); return await Task.FromResult(source.Skip(countByPage * (pageNumber - 1)) .Take(countByPage) .ToList()); } public Task<Post> GetPostAsync(string postId, bool includeComments = true, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (postId == null) throw new ArgumentNullException(nameof(postId)); Post dbPost = null; if (includeComments) dbPost = CurrentSyncSession.Load<Post>(postId); else dbPost = Posts.Select(p => new Post { Id = p.Id, Body = p.Body, Excerpt = p.Excerpt, LastModified = p.LastModified, PubDate = p.PubDate, Slug = p.Slug, Status = p.Status, Title = p.Title }).FirstOrDefault(p => p.Id == postId); dbPost.Attachments = CurrentSyncSession.Advanced.GetAttachmentNames(dbPost).ToList(); return Task.FromResult(dbPost); } public async Task<Post> CreatePostAsync(Post post, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (post == null) throw new ArgumentNullException(nameof(post)); await CurrentAsyncSession.StoreAsync(post, cancellationToken); await CurrentAsyncSession.SaveChangesAsync(cancellationToken); return post; } public async Task<Post> UpdatePostAsync(Post post, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (post == null) throw new ArgumentNullException(nameof(post)); var dbPost = await CurrentAsyncSession.LoadAsync<Post>(post.Id, cancellationToken); CurrentAsyncSession.Advanced.Evict(dbPost); await CurrentAsyncSession.StoreAsync(post, dbPost.Id, cancellationToken); await CurrentAsyncSession.SaveChangesAsync(cancellationToken); return post; } public async Task DeletePostAsync(string postId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (postId == null) throw new ArgumentNullException(nameof(postId)); CurrentAsyncSession.Delete(postId); await CurrentAsyncSession.SaveChangesAsync(cancellationToken); } public async Task<IEnumerable<Comment>> GetCommentsAsync(string postId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (postId == null) throw new ArgumentNullException(nameof(postId)); var dbPost = await CurrentAsyncSession.LoadAsync<Post>(postId, cancellationToken); return dbPost.Comments; } public Task<Comment> GetCommentAsync(string commentId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (commentId == null) throw new ArgumentNullException(nameof(commentId)); var parentPost = Posts.FirstOrDefault(post => post.Comments.Any(comment => comment.UniqueId == commentId)); return Task.FromResult(parentPost.Comments.First(comment => comment.UniqueId == commentId)); } public async Task<Comment> CreateCommentAsync(string postId, Comment comment, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (postId == null) throw new ArgumentNullException(nameof(postId)); if (comment == null) throw new ArgumentNullException(nameof(comment)); var dbPost = await CurrentAsyncSession.LoadAsync<Post>(postId, cancellationToken); dbPost.Comments.Add(comment); await CurrentAsyncSession.StoreAsync(dbPost, CurrentAsyncSession.Advanced.GetChangeVectorFor(dbPost), cancellationToken); await CurrentAsyncSession.SaveChangesAsync(cancellationToken); return comment; } public async Task<Comment> UpdateCommentAsync(Comment comment, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (comment == null) throw new ArgumentNullException(nameof(comment)); var dbPost = await CurrentAsyncSession.LoadAsync<Post>(comment.PostId, cancellationToken); for (int i = dbPost.Comments.Count; i >= 0; i--) { if (dbPost.Comments[i].UniqueId == comment.UniqueId) { dbPost.Comments[i] = comment; break; } } await CurrentAsyncSession.SaveChangesAsync(cancellationToken); return comment; } public async Task DeleteCommentAsync(string commentId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (commentId == null) throw new ArgumentNullException(nameof(commentId)); var parentPost = Posts.FirstOrDefault(post => post.Comments.Any(comment => comment.UniqueId == commentId)); for (int i = parentPost.Comments.Count; i >= 0; i--) { if (parentPost.Comments[i].UniqueId == commentId) { parentPost.Comments.RemoveAt(i); break; } } await CurrentAsyncSession.SaveChangesAsync(cancellationToken); } public async Task AddAttachedFile(string documentId, List<IFormFile> files, CancellationToken cancellationToken = default(CancellationToken)) { var fs = files.Where(f => f.Length > 0).Select(f => new { f.FileName, f.ContentType, Stream = f.OpenReadStream() }); try { foreach (var file in fs) CurrentAsyncSession.Advanced.StoreAttachment(documentId, file.FileName, file.Stream, file.ContentType); await CurrentAsyncSession.SaveChangesAsync(); } finally { foreach (var f in fs) f.Stream.Dispose(); } } public async Task<(string Name, long Size, string ContentType, Stream Stream)> GetAttachedFile(string documentId, string fileName) { var attachment = await CurrentAsyncSession.Advanced.GetAttachmentAsync(documentId, fileName); return (attachment.Details.Name, attachment.Details.Size, attachment.Details.ContentType, attachment.Stream); } } }
// 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.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class AcceptAsync { private readonly ITestOutputHelper _log; public AcceptAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnAcceptCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } public void OnConnectCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnConnectCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void AcceptAsync_IpV4_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv6", "true")] public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task AcceptAsync_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); servers[i] = listener.AcceptAsync(); } foreach (Socket client in clients) { client.Connect(listener.LocalEndPoint); } await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task AcceptAsync_ConcurrentAcceptsAfterConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var clientConnects = new Task[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientConnects[i] = clients[i].ConnectAsync(listener.LocalEndPoint); } for (int i = 0; i < numberAccepts; i++) { servers[i] = listener.AcceptAsync(); } await Task.WhenAll(clientConnects); Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status)); await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent accepted = new AutoResetEvent(false); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx const int acceptBufferDataSize = 256; const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize; byte[] sendBuffer = new byte[acceptBufferDataSize]; new Random().NextBytes(sendBuffer); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = accepted; acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize); Assert.True(server.AcceptAsync(acceptArgs)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(IPAddress.Loopback, port); client.Send(sendBuffer); client.Shutdown(SocketShutdown.Both); } Assert.True( accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in alotted time"); Assert.Equal( SocketError.Success, acceptArgs.SocketError); Assert.Equal( acceptBufferDataSize, acceptArgs.BytesTransferred); Assert.Equal( new ArraySegment<byte>(sendBuffer), new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithTooSmallReceiveBuffer_Failure() { using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); AssertExtensions.Throws<ArgumentException>(null, () => server.AcceptAsync(acceptArgs)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void AcceptAsync_WithTargetSocket_Success() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(server); client.Connect(IPAddress.Loopback, port); Assert.Same(server, acceptTask.Result); } } [ActiveIssue(17209, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public void AcceptAsync_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); var are = new AutoResetEvent(false); saea.Completed += delegate { are.Set(); }; saea.AcceptSocket = server; using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(listener.AcceptAsync(saea)); client.Connect(IPAddress.Loopback, port); are.WaitOne(); Assert.Same(server, saea.AcceptSocket); Assert.True(server.Connected); } server.Disconnect(reuseSocket); Assert.False(server.Connected); if (reuseSocket) { using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(listener.AcceptAsync(saea)); client.Connect(IPAddress.Loopback, port); are.WaitOne(); Assert.Same(server, saea.AcceptSocket); Assert.True(server.Connected); } } else { if (listener.AcceptAsync(saea)) { are.WaitOne(); } Assert.Equal(SocketError.InvalidArgument, saea.SocketError); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void AcceptAsync_WithAlreadyBoundTargetSocket_Failed() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); server.BindToAnonymousPort(IPAddress.Loopback); Assert.Throws<InvalidOperationException>(() => { listener.AcceptAsync(server); }); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class AssetServicesConnector : IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private IImprovedAssetCache m_Cache = null; public AssetServicesConnector() { } public AssetServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public AssetServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); throw new Exception("Asset connector init error"); } string serviceURI = assetConfig.GetString("AssetServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService"); throw new Exception("Asset connector init error"); } m_ServerURI = serviceURI; MainConsole.Instance.Commands.AddCommand("asset", false, "dump asset", "dump asset <id> <file>", "dump one cached asset", HandleDumpAsset); } protected void SetCache(IImprovedAssetCache cache) { m_Cache = cache; } public AssetBase Get(string id) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0); if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Metadata; } string uri = m_ServerURI + "/assets/" + id + "/metadata"; AssetMetadata asset = SynchronousRestObjectRequester. MakeRequest<int, AssetMetadata>("GET", uri, 0); return asset; } public byte[] GetData(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Data; } RestClient rc = new RestClient(m_ServerURI); rc.AddResourcePath("assets"); rc.AddResourcePath(id); rc.AddResourcePath("data"); rc.RequestMethod = "GET"; Stream s = rc.Request(); if (s == null) return null; if (s.Length > 0) { byte[] ret = new byte[s.Length]; s.Read(ret, 0, (int)s.Length); return ret; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { bool result = false; AsynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0, delegate(AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(id, sender, a); result = true; }); return result; } else { //Util.FireAndForget(delegate { handler(id, sender, asset); }); handler(id, sender, asset); } return true; } public string Store(AssetBase asset) { if (asset.Temporary || asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string uri = m_ServerURI + "/assets/"; string newID = string.Empty; try { newID = SynchronousRestObjectRequester. MakeRequest<AssetBase, string>("POST", uri, asset); } catch (Exception e) { m_log.WarnFormat("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1}", asset.ID, e.Message); } if (newID != String.Empty) { // Placing this here, so that this work with old asset servers that don't send any reply back // SynchronousRestObjectRequester returns somethins that is not an empty string if (newID != null) asset.ID = newID; if (m_Cache != null) m_Cache.Cache(asset); } return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AssetMetadata metadata = GetMetadata(id); if (metadata == null) return false; asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString()); asset.Metadata = metadata; } asset.Data = data; string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<AssetBase, bool>("POST", uri, asset)) { if (m_Cache != null) m_Cache.Cache(asset); return true; } return false; } public bool Delete(string id) { string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<int, bool>("DELETE", uri, 0)) { if (m_Cache != null) m_Cache.Expire(id); return true; } return false; } private void HandleDumpAsset(string module, string[] args) { if (args.Length != 4) { MainConsole.Instance.Output("Syntax: dump asset <id> <file>"); return; } UUID assetID; if (!UUID.TryParse(args[2], out assetID)) { MainConsole.Instance.Output("Invalid asset ID"); return; } if (m_Cache == null) { MainConsole.Instance.Output("Instance uses no cache"); return; } AssetBase asset = m_Cache.Get(assetID.ToString()); if (asset == null) { MainConsole.Instance.Output("Asset not found in cache"); return; } string fileName = args[3]; FileStream fs = File.Create(fileName); fs.Write(asset.Data, 0, asset.Data.Length); fs.Close(); } } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Microsoft.Kinect.Face { // // Microsoft.Kinect.Face.HighDefinitionFaceFrameSource // public sealed partial class HighDefinitionFaceFrameSource : Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal HighDefinitionFaceFrameSource(RootSystem.IntPtr pNative) { _pNative = pNative; Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_AddRefObject(ref _pNative); } ~HighDefinitionFaceFrameSource() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_AddRefObject(ref RootSystem.IntPtr pNative); public void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<HighDefinitionFaceFrameSource>(_pNative); Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern Microsoft.Kinect.Face.FaceAlignmentQuality Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_TrackingQuality(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_TrackingQuality(RootSystem.IntPtr pNative, Microsoft.Kinect.Face.FaceAlignmentQuality trackingQuality); public Microsoft.Kinect.Face.FaceAlignmentQuality TrackingQuality { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } return Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_TrackingQuality(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_TrackingQuality(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern ulong Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_TrackingId(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_TrackingId(RootSystem.IntPtr pNative, ulong trackingId); public ulong TrackingId { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } return Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_TrackingId(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_TrackingId(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsOnline(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_IsOnline(RootSystem.IntPtr pNative, bool isOnline); public bool IsOnline { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } return Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsOnline(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_IsOnline(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_FaceModel(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_FaceModel(RootSystem.IntPtr pNative, RootSystem.IntPtr faceModel); public Microsoft.Kinect.Face.FaceModel FaceModel { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_FaceModel(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceModel>(objectPointer, n => new Microsoft.Kinect.Face.FaceModel(n)); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_put_FaceModel(_pNative, ((Helper.INativeWrapper)value).nativePtr); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsActive(RootSystem.IntPtr pNative); public bool IsActive { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } return Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsActive(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsTrackingIdValid(RootSystem.IntPtr pNative); public bool IsTrackingIdValid { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } return Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_IsTrackingIdValid(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_KinectSensor(RootSystem.IntPtr pNative); public Windows.Kinect.KinectSensor KinectSensor { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_get_KinectSensor(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.KinectSensor>(objectPointer, n => new Windows.Kinect.KinectSensor(n)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.TrackingIdLostEventArgs>>> Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.TrackingIdLostEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate))] private static void Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Microsoft.Kinect.Face.TrackingIdLostEventArgs>> callbackList = null; Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<HighDefinitionFaceFrameSource>(pNative); var args = new Microsoft.Kinect.Face.TrackingIdLostEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_TrackingIdLost(RootSystem.IntPtr pNative, _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Microsoft.Kinect.Face.TrackingIdLostEventArgs> TrackingIdLost { add { Helper.EventPump.EnsureInitialized(); Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate(Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handler); _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_TrackingIdLost(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_TrackingIdLost(_pNative, Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handler, true); _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handle.Free(); } } } } 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<HighDefinitionFaceFrameSource>(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("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_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); Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_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) { Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_OpenReader(RootSystem.IntPtr pNative); public Microsoft.Kinect.Face.HighDefinitionFaceFrameReader OpenReader() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_OpenReader(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.HighDefinitionFaceFrameReader>(objectPointer, n => new Microsoft.Kinect.Face.HighDefinitionFaceFrameReader(n)); } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_OpenModelBuilder(RootSystem.IntPtr pNative, Microsoft.Kinect.Face.FaceModelBuilderAttributes enabledAttributes); public Microsoft.Kinect.Face.FaceModelBuilder OpenModelBuilder(Microsoft.Kinect.Face.FaceModelBuilderAttributes enabledAttributes) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("HighDefinitionFaceFrameSource"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_OpenModelBuilder(_pNative, enabledAttributes); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceModelBuilder>(objectPointer, n => new Microsoft.Kinect.Face.FaceModelBuilder(n)); } private void __EventCleanup() { { Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_TrackingIdLost(_pNative, Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handler, true); } _Microsoft_Kinect_Face_TrackingIdLostEventArgs_Delegate_Handle.Free(); } } } { 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) { Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Diagnostics; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using FarseerPhysics.Dynamics.Contacts; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics { [Flags] public enum Category { None = 0, All = int.MaxValue, Cat1 = 1, Cat2 = 2, Cat3 = 4, Cat4 = 8, Cat5 = 16, Cat6 = 32, Cat7 = 64, Cat8 = 128, Cat9 = 256, Cat10 = 512, Cat11 = 1024, Cat12 = 2048, Cat13 = 4096, Cat14 = 8192, Cat15 = 16384, Cat16 = 32768, Cat17 = 65536, Cat18 = 131072, Cat19 = 262144, Cat20 = 524288, Cat21 = 1048576, Cat22 = 2097152, Cat23 = 4194304, Cat24 = 8388608, Cat25 = 16777216, Cat26 = 33554432, Cat27 = 67108864, Cat28 = 134217728, Cat29 = 268435456, Cat30 = 536870912, Cat31 = 1073741824 } /// <summary> /// This proxy is used internally to connect fixtures to the broad-phase. /// </summary> public struct FixtureProxy { public AABB AABB; public int ChildIndex; public Fixture Fixture; public int ProxyId; } /// <summary> /// A fixture is used to attach a Shape to a body for collision detection. A fixture /// inherits its transform from its parent. Fixtures hold additional non-geometric data /// such as friction, collision filters, etc. /// Fixtures are created via Body.CreateFixture. /// Warning: You cannot reuse fixtures. /// </summary> public class Fixture : IDisposable { private static int _fixtureIdCounter; /// <summary> /// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force. /// </summary> public AfterCollisionEventHandler AfterCollision; /// <summary> /// Fires when two fixtures are close to each other. /// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs. /// </summary> public BeforeCollisionEventHandler BeforeCollision; /// <summary> /// Fires when two shapes collide and a contact is created between them. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to. /// </summary> public OnCollisionEventHandler OnCollision; /// <summary> /// Fires when two shapes separate and a contact is removed between them. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to. /// </summary> public OnSeparationEventHandler OnSeparation; public FixtureProxy[] Proxies; public int ProxyCount; internal Category _collidesWith; internal Category _collisionCategories; internal short _collisionGroup; internal Dictionary<int, bool> _collisionIgnores; private float _friction; private float _restitution; internal Fixture() { } public Fixture(Body body, Shape shape) : this(body, shape, null) { } public Fixture(Body body, Shape shape, object userData) { if (Settings.UseFPECollisionCategories) _collisionCategories = Category.All; else _collisionCategories = Category.Cat1; _collidesWith = Category.All; _collisionGroup = 0; //Fixture defaults Friction = 0.2f; Restitution = 0; IsSensor = false; Body = body; UserData = userData; #pragma warning disable 162 if (Settings.ConserveMemory) Shape = shape; else Shape = shape.Clone(); #pragma warning restore 162 RegisterFixture(); } /// <summary> /// Defaults to 0 /// /// If Settings.UseFPECollisionCategories is set to false: /// Collision groups allow a certain group of objects to never collide (negative) /// or always collide (positive). Zero means no collision group. Non-zero group /// filtering always wins against the mask bits. /// /// If Settings.UseFPECollisionCategories is set to true: /// If 2 fixtures are in the same collision group, they will not collide. /// </summary> public short CollisionGroup { set { if (_collisionGroup == value) return; _collisionGroup = value; Refilter(); } get { return _collisionGroup; } } /// <summary> /// Defaults to Category.All /// /// The collision mask bits. This states the categories that this /// fixture would accept for collision. /// Use Settings.UseFPECollisionCategories to change the behavior. /// </summary> public Category CollidesWith { get { return _collidesWith; } set { if (_collidesWith == value) return; _collidesWith = value; Refilter(); } } /// <summary> /// The collision categories this fixture is a part of. /// /// If Settings.UseFPECollisionCategories is set to false: /// Defaults to Category.Cat1 /// /// If Settings.UseFPECollisionCategories is set to true: /// Defaults to Category.All /// </summary> public Category CollisionCategories { get { return _collisionCategories; } set { if (_collisionCategories == value) return; _collisionCategories = value; Refilter(); } } /// <summary> /// Get the type of the child Shape. You can use this to down cast to the concrete Shape. /// </summary> /// <value>The type of the shape.</value> public ShapeType ShapeType { get { return Shape.ShapeType; } } /// <summary> /// Get the child Shape. You can modify the child Shape, however you should not change the /// number of vertices because this will crash some collision caching mechanisms. /// </summary> /// <value>The shape.</value> public Shape Shape { get; internal set; } /// <summary> /// Gets or sets a value indicating whether this fixture is a sensor. /// </summary> /// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value> public bool IsSensor { get; set; } /// <summary> /// Get the parent body of this fixture. This is null if the fixture is not attached. /// </summary> /// <value>The body.</value> public Body Body { get; internal set; } /// <summary> /// Set the user data. Use this to store your application specific data. /// </summary> /// <value>The user data.</value> public object UserData { get; set; } /// <summary> /// Get or set the coefficient of friction. /// </summary> /// <value>The friction.</value> public float Friction { get { return _friction; } set { Debug.Assert(!float.IsNaN(value)); _friction = value; } } /// <summary> /// Get or set the coefficient of restitution. /// </summary> /// <value>The restitution.</value> public float Restitution { get { return _restitution; } set { Debug.Assert(!float.IsNaN(value)); _restitution = value; } } /// <summary> /// Gets a unique ID for this fixture. /// </summary> /// <value>The fixture id.</value> public int FixtureId { get; private set; } #region IDisposable Members public bool IsDisposed { get; set; } public void Dispose() { if (!IsDisposed) { Body.DestroyFixture(this); IsDisposed = true; GC.SuppressFinalize(this); } } #endregion /// <summary> /// Restores collisions between this fixture and the provided fixture. /// </summary> /// <param name="fixture">The fixture.</param> public void RestoreCollisionWith(Fixture fixture) { if (_collisionIgnores == null) return; if (_collisionIgnores.ContainsKey(fixture.FixtureId)) { _collisionIgnores[fixture.FixtureId] = false; Refilter(); } } /// <summary> /// Ignores collisions between this fixture and the provided fixture. /// </summary> /// <param name="fixture">The fixture.</param> public void IgnoreCollisionWith(Fixture fixture) { if (_collisionIgnores == null) _collisionIgnores = new Dictionary<int, bool>(); if (_collisionIgnores.ContainsKey(fixture.FixtureId)) _collisionIgnores[fixture.FixtureId] = true; else _collisionIgnores.Add(fixture.FixtureId, true); Refilter(); } /// <summary> /// Determines whether collisions are ignored between this fixture and the provided fixture. /// </summary> /// <param name="fixture">The fixture.</param> /// <returns> /// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>. /// </returns> public bool IsFixtureIgnored(Fixture fixture) { if (_collisionIgnores == null) return false; if (_collisionIgnores.ContainsKey(fixture.FixtureId)) return _collisionIgnores[fixture.FixtureId]; return false; } /// <summary> /// Contacts are persistant and will keep being persistant unless they are /// flagged for filtering. /// This methods flags all contacts associated with the body for filtering. /// </summary> internal void Refilter() { // Flag associated contacts for filtering. ContactEdge edge = Body.ContactList; while (edge != null) { Contact contact = edge.Contact; Fixture fixtureA = contact.FixtureA; Fixture fixtureB = contact.FixtureB; if (fixtureA == this || fixtureB == this) { contact.FlagForFiltering(); } edge = edge.Next; } World world = Body.World; if (world == null) { return; } // Touch each proxy so that new pairs may be created IBroadPhase broadPhase = world.ContactManager.BroadPhase; for (int i = 0; i < ProxyCount; ++i) { broadPhase.TouchProxy(Proxies[i].ProxyId); } } private void RegisterFixture() { // Reserve proxy space Proxies = new FixtureProxy[Shape.ChildCount]; ProxyCount = 0; FixtureId = _fixtureIdCounter++; if ((Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled) { IBroadPhase broadPhase = Body.World.ContactManager.BroadPhase; CreateProxies(broadPhase, ref Body.Xf); } Body.FixtureList.Add(this); // Adjust mass properties if needed. if (Shape._density > 0.0f) { Body.ResetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. Body.World.Flags |= WorldFlags.NewFixture; if (Body.World.FixtureAdded != null) { Body.World.FixtureAdded(this); } } /// <summary> /// Test a point for containment in this fixture. /// </summary> /// <param name="point">A point in world coordinates.</param> /// <returns></returns> public bool TestPoint(ref Vector2 point) { return Shape.TestPoint(ref Body.Xf, ref point); } /// <summary> /// Cast a ray against this Shape. /// </summary> /// <param name="output">The ray-cast results.</param> /// <param name="input">The ray-cast input parameters.</param> /// <param name="childIndex">Index of the child.</param> /// <returns></returns> public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex) { return Shape.RayCast(out output, ref input, ref Body.Xf, childIndex); } /// <summary> /// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// If you need a more accurate AABB, compute it using the Shape and /// the body transform. /// </summary> /// <param name="aabb">The aabb.</param> /// <param name="childIndex">Index of the child.</param> public void GetAABB(out AABB aabb, int childIndex) { Debug.Assert(0 <= childIndex && childIndex < ProxyCount); aabb = Proxies[childIndex].AABB; } public Fixture Clone(Body body) { Fixture fixture = new Fixture(); fixture.Body = body; #pragma warning disable 162 if (Settings.ConserveMemory) fixture.Shape = Shape; else fixture.Shape = Shape.Clone(); #pragma warning restore 162 fixture.UserData = UserData; fixture.Restitution = Restitution; fixture.Friction = Friction; fixture.IsSensor = IsSensor; fixture._collisionGroup = CollisionGroup; fixture._collisionCategories = CollisionCategories; fixture._collidesWith = CollidesWith; if (_collisionIgnores != null) { fixture._collisionIgnores = new Dictionary<int, bool>(); foreach (KeyValuePair<int, bool> pair in _collisionIgnores) { fixture._collisionIgnores.Add(pair.Key, pair.Value); } } fixture.RegisterFixture(); return fixture; } public Fixture DeepClone() { Fixture fix = Clone(Body.Clone()); return fix; } internal void Destroy() { // The proxies must be destroyed before calling this. Debug.Assert(ProxyCount == 0); // Free the proxy array. Proxies = null; Shape = null; BeforeCollision = null; OnCollision = null; OnSeparation = null; AfterCollision = null; if (Body.World.FixtureRemoved != null) { Body.World.FixtureRemoved(this); } Body.World.FixtureAdded = null; Body.World.FixtureRemoved = null; OnSeparation = null; OnCollision = null; } // These support body activation/deactivation. internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf) { Debug.Assert(ProxyCount == 0); // Create proxies in the broad-phase. ProxyCount = Shape.ChildCount; for (int i = 0; i < ProxyCount; ++i) { FixtureProxy proxy = new FixtureProxy(); Shape.ComputeAABB(out proxy.AABB, ref xf, i); proxy.Fixture = this; proxy.ChildIndex = i; proxy.ProxyId = broadPhase.AddProxy(ref proxy); Proxies[i] = proxy; } } internal void DestroyProxies(IBroadPhase broadPhase) { // Destroy proxies in the broad-phase. for (int i = 0; i < ProxyCount; ++i) { broadPhase.RemoveProxy(Proxies[i].ProxyId); Proxies[i].ProxyId = -1; } ProxyCount = 0; } internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2) { if (ProxyCount == 0) { return; } for (int i = 0; i < ProxyCount; ++i) { FixtureProxy proxy = Proxies[i]; // Compute an AABB that covers the swept Shape (may miss some rotation effect). AABB aabb1, aabb2; Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex); Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex); proxy.AABB.Combine(ref aabb1, ref aabb2); Vector2 displacement = transform2.Position - transform1.Position; broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement); } } internal bool CompareTo(Fixture fixture) { return ( CollidesWith == fixture.CollidesWith && CollisionCategories == fixture.CollisionCategories && CollisionGroup == fixture.CollisionGroup && Friction == fixture.Friction && IsSensor == fixture.IsSensor && Restitution == fixture.Restitution && Shape.CompareTo(fixture.Shape) && UserData == fixture.UserData); } } }
// 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.Globalization; // Ported to CoreCLR from Co7531TryParse_all.cs // Tests Decimal.TryParse(String), Decimal.TryParse(String, NumberStyles, IFormatProvider, ref Decimal) // 2003/04/01 KatyK // 2007/07/12 adapted by MarielY public class Co7531TryParse { static bool verbose = false; public static int Main() { bool passed = true; try { // Make the test culture independent TestLibrary.Utilities.CurrentCulture = CultureInfo.InvariantCulture; // Set up NFIs to use NumberFormatInfo goodNFI = new NumberFormatInfo(); NumberFormatInfo corruptNFI = new NumberFormatInfo(); // DecimalSeparator == GroupSeparator corruptNFI.NumberDecimalSeparator = "."; corruptNFI.NumberGroupSeparator = "."; corruptNFI.CurrencyDecimalSeparator = "."; corruptNFI.CurrencyGroupSeparator = "."; corruptNFI.CurrencySymbol = "$"; NumberFormatInfo swappedNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator swapped swappedNFI.NumberDecimalSeparator = "."; swappedNFI.NumberGroupSeparator = ","; swappedNFI.CurrencyDecimalSeparator = ","; swappedNFI.CurrencyGroupSeparator = "."; swappedNFI.CurrencySymbol = "$"; NumberFormatInfo distinctNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator distinct distinctNFI.NumberDecimalSeparator = "."; distinctNFI.NumberGroupSeparator = ","; distinctNFI.CurrencyDecimalSeparator = ":"; distinctNFI.CurrencyGroupSeparator = ";"; distinctNFI.CurrencySymbol = "$"; NumberFormatInfo customNFI = new NumberFormatInfo(); customNFI.NegativeSign = "^"; NumberFormatInfo ambigNFI = new NumberFormatInfo(); ambigNFI.NegativeSign = "^"; ambigNFI.CurrencySymbol = "^"; CultureInfo invariantCulture = CultureInfo.InvariantCulture; CultureInfo germanCulture = new CultureInfo("de-DE"); CultureInfo japaneseCulture; try { japaneseCulture = new CultureInfo("ja-JP"); } catch (CultureNotFoundException) { TestLibrary.TestFramework.LogInformation("East Asian Languages are not installed. Skipping Japanese culture test(s)."); japaneseCulture = null; } // Parse tests included for comparison/regression passed &= VerifyDecimalParse("5", 5); passed &= VerifyDecimalParse("5 ", 5); passed &= VerifyDecimalParse("5\0", 5); passed &= VerifyDecimalParse("-5", -5); passed &= VerifyDecimalParse("893382737", 893382737); passed &= VerifyDecimalParse("-893382737", -893382737); passed &= VerifyDecimalParse("1234567891", 1234567891); passed &= VerifyDecimalParse("-1234567891", -1234567891); passed &= VerifyDecimalParse("123456789123456789", 123456789123456789); passed &= VerifyDecimalParse("-123456789123456789", -123456789123456789); passed &= VerifyDecimalParse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyDecimalParse("5 \0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyDecimalParse("5\0\0\0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5); passed &= VerifyDecimalParse("-5", NumberStyles.Integer, CultureInfo.InvariantCulture, -5); passed &= VerifyDecimalParse("5", NumberStyles.Integer, goodNFI, 5); passed &= VerifyDecimalParse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5.0m); passed &= VerifyDecimalParse("5.3", NumberStyles.AllowDecimalPoint, goodNFI, 5.3m); passed &= VerifyDecimalParse("123456789123456789123", 123456789123456789123m); passed &= VerifyDecimalParse("-123456789123456789123", -123456789123456789123m); passed &= VerifyDecimalParse("18446744073709551615", 18446744073709551615); passed &= VerifyDecimalParse("79228162514264337593543950335", 79228162514264337593543950335m); passed &= VerifyDecimalParse("-79228162514264337593543950335", -79228162514264337593543950335m); passed &= VerifyDecimalParse("5.555555555", 5.555555555m); passed &= VerifyDecimalParse("1.000000", 1.000000m); passed &= VerifyDecimalParse("123", NumberStyles.Integer, germanCulture, 123); passed &= VerifyDecimalParse("123", NumberStyles.Integer, japaneseCulture, 123); passed &= VerifyDecimalParse("123.456", NumberStyles.Any, germanCulture, 123456); passed &= VerifyDecimalParse("123,456", NumberStyles.Any, japaneseCulture, 123456); passed &= VerifyDecimalParse("123,456", NumberStyles.AllowDecimalPoint, germanCulture, 123.456m); passed &= VerifyDecimalParse("123.456", NumberStyles.AllowDecimalPoint, japaneseCulture, 123.456m); passed &= VerifyDecimalParse("5,23 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5.23m); // currency passed &= VerifyDecimalParse("5.23 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 523); // currency // passed &= VerifyDecimalParse("5", NumberStyles.Integer, corruptNFI, 5); passed &= VerifyDecimalParse("5", NumberStyles.Number, corruptNFI, 5); passed &= VerifyDecimalParse("5.3", NumberStyles.Number, corruptNFI, 5.3m); passed &= VerifyDecimalParseException("5,3", NumberStyles.Number, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5.2.3", NumberStyles.Number, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParse("$5.3", NumberStyles.Currency, corruptNFI, 5.3m); passed &= VerifyDecimalParseException("$5,3", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("$5.2.3", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5.3", NumberStyles.Currency, corruptNFI, 5.3m); passed &= VerifyDecimalParseException("5,3", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5.2.3", NumberStyles.Currency, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5.3", NumberStyles.Any, corruptNFI, 5.3m); passed &= VerifyDecimalParseException("5,3", NumberStyles.Any, corruptNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5.2.3", NumberStyles.Any, corruptNFI, typeof(FormatException)); // passed &= VerifyDecimalParse("5", NumberStyles.Integer, swappedNFI, 5); passed &= VerifyDecimalParseException("1,234", NumberStyles.Integer, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5", NumberStyles.Number, swappedNFI, 5); passed &= VerifyDecimalParse("5.0", NumberStyles.Number, swappedNFI, 5.0m); passed &= VerifyDecimalParse("1,234", NumberStyles.Number, swappedNFI, 1234); passed &= VerifyDecimalParse("1,234.0", NumberStyles.Number, swappedNFI, 1234.0m); passed &= VerifyDecimalParseException("5.000.000", NumberStyles.Number, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5.000,00", NumberStyles.Number, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5.000", NumberStyles.Currency, swappedNFI, 5); //??? passed &= VerifyDecimalParseException("5.000,00", NumberStyles.Currency, swappedNFI, typeof(FormatException)); //??? passed &= VerifyDecimalParse("$5.000", NumberStyles.Currency, swappedNFI, 5000); passed &= VerifyDecimalParse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000); passed &= VerifyDecimalParse("5.000", NumberStyles.Any, swappedNFI, 5); //? passed &= VerifyDecimalParseException("5.000,00", NumberStyles.Any, swappedNFI, typeof(FormatException)); //? passed &= VerifyDecimalParse("$5.000", NumberStyles.Any, swappedNFI, 5000); passed &= VerifyDecimalParse("$5.000,00", NumberStyles.Any, swappedNFI, 5000); passed &= VerifyDecimalParse("5,0", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyDecimalParse("$5,0", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyDecimalParse("5,000", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyDecimalParse("$5,000", NumberStyles.Currency, swappedNFI, 5); passed &= VerifyDecimalParseException("5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("$5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5,000", NumberStyles.Any, swappedNFI, 5); passed &= VerifyDecimalParse("$5,000", NumberStyles.Any, swappedNFI, 5); passed &= VerifyDecimalParseException("5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("$5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException)); // passed &= VerifyDecimalParse("5.0", NumberStyles.Number, distinctNFI, 5); passed &= VerifyDecimalParse("1,234.0", NumberStyles.Number, distinctNFI, 1234); passed &= VerifyDecimalParse("5.0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyDecimalParse("1,234.0", NumberStyles.Currency, distinctNFI, 1234); passed &= VerifyDecimalParse("5.0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyDecimalParse("1,234.0", NumberStyles.Any, distinctNFI, 1234); passed &= VerifyDecimalParseException("$5.0", NumberStyles.Currency, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("$5.0", NumberStyles.Any, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5:0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("5;0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParseException("$5:0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParse("5:0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyDecimalParse("5:000", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyDecimalParse("5;000", NumberStyles.Currency, distinctNFI, 5000); passed &= VerifyDecimalParse("$5:0", NumberStyles.Currency, distinctNFI, 5); passed &= VerifyDecimalParse("$5;0", NumberStyles.Currency, distinctNFI, 50); passed &= VerifyDecimalParse("5:0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyDecimalParse("5;0", NumberStyles.Any, distinctNFI, 50); passed &= VerifyDecimalParse("$5:0", NumberStyles.Any, distinctNFI, 5); passed &= VerifyDecimalParse("$5;0", NumberStyles.Any, distinctNFI, 50); passed &= VerifyDecimalParseException("123,456;789.0", NumberStyles.Number, distinctNFI, typeof(FormatException)); passed &= VerifyDecimalParse("123,456;789.0", NumberStyles.Currency, distinctNFI, 123456789); passed &= VerifyDecimalParse("123,456;789.0", NumberStyles.Any, distinctNFI, 123456789); passed &= VerifyDecimalParseException("$123,456;789.0", NumberStyles.Any, distinctNFI, typeof(FormatException)); // passed &= VerifyDecimalParseException("79228162514264337593543950336", typeof(OverflowException)); passed &= VerifyDecimalParseException("-79228162514264337593543950336", typeof(OverflowException)); passed &= VerifyDecimalParseException("Garbage", typeof(FormatException)); passed &= VerifyDecimalParseException("5\0Garbage", typeof(FormatException)); passed &= VerifyDecimalParseException(null, typeof(ArgumentNullException)); passed &= VerifyDecimalParseException("FF", NumberStyles.HexNumber, goodNFI, typeof(ArgumentException)); passed &= VerifyDecimalParseException("4", (NumberStyles)(-1), typeof(ArgumentException)); passed &= VerifyDecimalParseException("4", (NumberStyles)0x10000, typeof(ArgumentException)); passed &= VerifyDecimalParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyDecimalParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyDecimalParseException("123,000,000,000,000,000,000", NumberStyles.Any, germanCulture, typeof(FormatException)); passed &= VerifyDecimalParseException("123.000.000.000.000.000.000", NumberStyles.Any, japaneseCulture, typeof(FormatException)); passed &= VerifyDecimalParseException("5,00 \u20AC", NumberStyles.Integer, germanCulture, typeof(FormatException)); // currency // Underflow cases - see VSWhidbey #576556 Decimal zeroScale28 = new Decimal(0, 0, 0, false, 28); Decimal zeroScale27 = new Decimal(0, 0, 0, false, 27); passed &= VerifyExactDecimalParse("0E-27", NumberStyles.AllowExponent, zeroScale27); passed &= VerifyExactDecimalParse("0E-28", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0E-29", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0E-30", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0E-31", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0E-50", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0E-100", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("0.000000000000000000000000000", zeroScale27); passed &= VerifyExactDecimalParse("0.0000000000000000000000000000", zeroScale28); //28 passed &= VerifyExactDecimalParse("0.00000000000000000000000000000", zeroScale28); //29 passed &= VerifyExactDecimalParse("0.000000000000000000000000000000", zeroScale28); //30 passed &= VerifyExactDecimalParse("0.0000000000000000000000000000000", zeroScale28); //31 passed &= VerifyExactDecimalParse("0.0", new Decimal(0, 0, 0, false, 1)); passed &= VerifyExactDecimalParse("0E-15", NumberStyles.AllowExponent, new Decimal(0, 0, 0, false, 15)); passed &= VerifyExactDecimalParse("0", Decimal.Zero); Decimal oneScale27 = new Decimal(1, 0, 0, false, 27); Decimal oneScale28 = new Decimal(1, 0, 0, false, 28); passed &= VerifyExactDecimalParse("1E-27", NumberStyles.AllowExponent, oneScale27); passed &= VerifyExactDecimalParse("1E-28", NumberStyles.AllowExponent, oneScale28); passed &= VerifyExactDecimalParse("1E-29", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("1E-30", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("1E-31", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("1E-50", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("1E-100", NumberStyles.AllowExponent, zeroScale28); passed &= VerifyExactDecimalParse("1E-27", NumberStyles.AllowExponent, invariantCulture, oneScale27); passed &= VerifyExactDecimalParse("1E-28", NumberStyles.AllowExponent, invariantCulture, oneScale28); passed &= VerifyExactDecimalParse("1E-29", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("1E-30", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("1E-31", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("1E-50", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("1E-100", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-27", NumberStyles.AllowExponent, invariantCulture, zeroScale27); passed &= VerifyExactDecimalParse("0E-28", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-29", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-30", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-31", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-50", NumberStyles.AllowExponent, invariantCulture, zeroScale28); passed &= VerifyExactDecimalParse("0E-100", NumberStyles.AllowExponent, invariantCulture, zeroScale28); // make sure parse lines up with compiler //passed &= VerifyExactDecimalParse("0E-50", NumberStyles.AllowExponent, 0E-50m); // V2->V4 compiler change passed &= VerifyExactDecimalParse("1E-50", NumberStyles.AllowExponent, 1E-50m); passed &= VerifyExactDecimalParse("2E-100", NumberStyles.AllowExponent, 2E-100m); passed &= VerifyExactDecimalParse("100E-29", NumberStyles.AllowExponent, 100E-29m); passed &= VerifyExactDecimalParse("200E-29", NumberStyles.AllowExponent, 200E-29m); passed &= VerifyExactDecimalParse("500E-29", NumberStyles.AllowExponent, 500E-29m); passed &= VerifyExactDecimalParse("900E-29", NumberStyles.AllowExponent, 900E-29m); passed &= VerifyExactDecimalParse("1900E-29", NumberStyles.AllowExponent, 1900E-29m); passed &= VerifyExactDecimalParse("10900E-29", NumberStyles.AllowExponent, 10900E-29m); passed &= VerifyExactDecimalParse("10900E-30", NumberStyles.AllowExponent, 10900E-30m); passed &= VerifyExactDecimalParse("10900E-31", NumberStyles.AllowExponent, 10900E-31m); passed &= VerifyExactDecimalParse("10900E-32", NumberStyles.AllowExponent, 10900E-32m); passed &= VerifyExactDecimalParse("10900E-33", NumberStyles.AllowExponent, 10900E-33m); passed &= VerifyExactDecimalParse("10900E-34", NumberStyles.AllowExponent, 10900E-34m); passed &= VerifyExactDecimalParse("10900E-340", NumberStyles.AllowExponent, 10900E-340m); passed &= VerifyExactDecimalParse("10900E-512", NumberStyles.AllowExponent, 10900E-512m); passed &= VerifyExactDecimalParse("10900E-678", NumberStyles.AllowExponent, 10900E-678m); passed &= VerifyExactDecimalParse("10900E-999", NumberStyles.AllowExponent, 10900E-999m); /////////// TryParse(String) //// Pass cases passed &= VerifyDecimalTryParse("5", 5, true); passed &= VerifyDecimalTryParse(" 5 ", 5, true); passed &= VerifyDecimalTryParse("-5", -5, true); passed &= VerifyDecimalTryParse("5\0", 5, true); passed &= VerifyDecimalTryParse("5 \0", 5, true); passed &= VerifyDecimalTryParse("5\0\0\0", 5, true); passed &= VerifyDecimalTryParse("893382737", 893382737, true); passed &= VerifyDecimalTryParse("-893382737", -893382737, true); passed &= VerifyDecimalTryParse("1234567891", 1234567891, true); passed &= VerifyDecimalTryParse("-1234567891", -1234567891, true); passed &= VerifyDecimalTryParse("123456789123456789", 123456789123456789, true); passed &= VerifyDecimalTryParse("-123456789123456789", -123456789123456789, true); passed &= VerifyDecimalTryParse("123456789123456789123", 123456789123456789123m, true); passed &= VerifyDecimalTryParse("-123456789123456789123", -123456789123456789123m, true); passed &= VerifyDecimalTryParse("18446744073709551615", 18446744073709551615, true); passed &= VerifyDecimalTryParse("79228162514264337593543950335", 79228162514264337593543950335m, true); passed &= VerifyDecimalTryParse("-79228162514264337593543950335", -79228162514264337593543950335m, true); passed &= VerifyDecimalTryParse("7.3", 7.3m, true); passed &= VerifyDecimalTryParse(".297", 0.297m, true); passed &= VerifyDecimalTryParse("5.555555555", 5.555555555m, true); passed &= VerifyDecimalTryParse("1.000000", 1.000000m, true); //// Fail cases passed &= VerifyDecimalTryParse(null, 0, false); passed &= VerifyDecimalTryParse("", 0, false); passed &= VerifyDecimalTryParse("Garbage", 0, false); passed &= VerifyDecimalTryParse("5\0Garbage", 0, false); passed &= VerifyDecimalTryParse("FF", 0, false); passed &= VerifyDecimalTryParse("23 5", 0, false); passed &= VerifyDecimalTryParse("NaN", 0, false); passed &= VerifyDecimalTryParse("Infinity", 0, false); passed &= VerifyDecimalTryParse("-Infinity", 0, false); passed &= VerifyDecimalTryParse("79228162514264337593543950336", 0, false); passed &= VerifyDecimalTryParse("-79228162514264337593543950336", 0, false); passed &= VerifyDecimalTryParse("1.234+E05", 0, false); passed &= VerifyDecimalTryParse("1.234E+05", 0, false); /////////// TryParse(TryParse(String, NumberStyles, IFormatProvider, ref Decimal) //// Pass cases passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5, true); passed &= VerifyDecimalTryParse("-5", NumberStyles.Integer, CultureInfo.InvariantCulture, -5, true); // Variations on NumberStyles passed &= VerifyDecimalTryParse(" 5", NumberStyles.AllowLeadingWhite, goodNFI, 5, true); passed &= VerifyDecimalTryParse("5", NumberStyles.Number, goodNFI, 5, true); passed &= VerifyDecimalTryParse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5.0m, true); passed &= VerifyDecimalTryParse("5.3", NumberStyles.AllowDecimalPoint, goodNFI, 5.3m, true); // Variations on IFP passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, goodNFI, 5, true); passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, null, 5, true); passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, new DateTimeFormatInfo(), 5, true); passed &= VerifyDecimalTryParse("^42", NumberStyles.Any, customNFI, -42, true); passed &= VerifyDecimalTryParse("123", NumberStyles.Integer, germanCulture, 123, true); passed &= VerifyDecimalTryParse("123", NumberStyles.Integer, japaneseCulture, 123, true); passed &= VerifyDecimalTryParse("123.456", NumberStyles.Any, germanCulture, 123456, true); passed &= VerifyDecimalTryParse("123,456", NumberStyles.Any, japaneseCulture, 123456, true); passed &= VerifyDecimalTryParse("123,456", NumberStyles.AllowDecimalPoint, germanCulture, 123.456m, true); passed &= VerifyDecimalTryParse("123.456", NumberStyles.AllowDecimalPoint, japaneseCulture, 123.456m, true); passed &= VerifyDecimalTryParse("5,23 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5.23m, true); // currency passed &= VerifyDecimalTryParse("5.23 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 523, true); // currency // //// Fail cases passed &= VerifyDecimalTryParse("-79228162514264337593543950336", NumberStyles.Integer, CultureInfo.InvariantCulture, 0, false); passed &= VerifyDecimalTryParse("-42", NumberStyles.Any, customNFI, 0, false); passed &= VerifyDecimalTryParse("5 ", NumberStyles.AllowLeadingWhite, goodNFI, 0, false); passed &= VerifyDecimalTryParse("1.234+E05", NumberStyles.AllowExponent, goodNFI, 0, false); passed &= VerifyDecimalTryParse("5.3", NumberStyles.None, goodNFI, 0, false); //// Exception cases passed &= VerifyDecimalTryParseException("12", NumberStyles.HexNumber, CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyDecimalTryParseException("5", NumberStyles.AllowHexSpecifier | NumberStyles.AllowParentheses, null, typeof(ArgumentException)); passed &= VerifyDecimalTryParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException)); passed &= VerifyDecimalTryParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException)); // NumberStyles/NFI variations // passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, corruptNFI, 5, true); passed &= VerifyDecimalTryParse("5", NumberStyles.Number, corruptNFI, 5, true); passed &= VerifyDecimalTryParse("5.3", NumberStyles.Number, corruptNFI, 5.3m, true); passed &= VerifyDecimalTryParse("5,3", NumberStyles.Number, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("5.2.3", NumberStyles.Number, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("$5.3", NumberStyles.Currency, corruptNFI, 5.3m, true); passed &= VerifyDecimalTryParse("$5,3", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("$5.2.3", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("5.3", NumberStyles.Currency, corruptNFI, 5.3m, true); passed &= VerifyDecimalTryParse("5,3", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("5.2.3", NumberStyles.Currency, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("5.3", NumberStyles.Any, corruptNFI, 5.3m, true); passed &= VerifyDecimalTryParse("5,3", NumberStyles.Any, corruptNFI, 0, false); passed &= VerifyDecimalTryParse("5.2.3", NumberStyles.Any, corruptNFI, 0, false); // passed &= VerifyDecimalTryParse("5", NumberStyles.Integer, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("1,234", NumberStyles.Integer, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("5", NumberStyles.Number, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("5.0", NumberStyles.Number, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("1,234", NumberStyles.Number, swappedNFI, 1234, true); passed &= VerifyDecimalTryParse("1,234.0", NumberStyles.Number, swappedNFI, 1234, true); passed &= VerifyDecimalTryParse("5.000.000", NumberStyles.Number, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("5.000,00", NumberStyles.Number, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("5.000", NumberStyles.Currency, swappedNFI, 5, true); //??? passed &= VerifyDecimalTryParse("5.000,00", NumberStyles.Currency, swappedNFI, 0, false); //??? passed &= VerifyDecimalTryParse("$5.000", NumberStyles.Currency, swappedNFI, 5000, true); passed &= VerifyDecimalTryParse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000, true); passed &= VerifyDecimalTryParse("5.000", NumberStyles.Any, swappedNFI, 5, true); //? passed &= VerifyDecimalTryParse("5.000,00", NumberStyles.Any, swappedNFI, 0, false); //? passed &= VerifyDecimalTryParse("$5.000", NumberStyles.Any, swappedNFI, 5000, true); passed &= VerifyDecimalTryParse("$5.000,00", NumberStyles.Any, swappedNFI, 5000, true); passed &= VerifyDecimalTryParse("5,0", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("$5,0", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("5,000", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("$5,000", NumberStyles.Currency, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("5,000.0", NumberStyles.Currency, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("$5,000.0", NumberStyles.Currency, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("5,000", NumberStyles.Any, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("$5,000", NumberStyles.Any, swappedNFI, 5, true); passed &= VerifyDecimalTryParse("5,000.0", NumberStyles.Any, swappedNFI, 0, false); passed &= VerifyDecimalTryParse("$5,000.0", NumberStyles.Any, swappedNFI, 0, false); // passed &= VerifyDecimalTryParse("5.0", NumberStyles.Number, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("1,234.0", NumberStyles.Number, distinctNFI, 1234, true); passed &= VerifyDecimalTryParse("5.0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("1,234.0", NumberStyles.Currency, distinctNFI, 1234, true); passed &= VerifyDecimalTryParse("5.0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("1,234.0", NumberStyles.Any, distinctNFI, 1234, true); passed &= VerifyDecimalTryParse("$5.0", NumberStyles.Currency, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("$5.0", NumberStyles.Any, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("5:0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("5;0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("$5:0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("5:0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("5:000", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("5;000", NumberStyles.Currency, distinctNFI, 5000, true); passed &= VerifyDecimalTryParse("$5:0", NumberStyles.Currency, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("$5;0", NumberStyles.Currency, distinctNFI, 50, true); passed &= VerifyDecimalTryParse("5:0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("5;0", NumberStyles.Any, distinctNFI, 50, true); passed &= VerifyDecimalTryParse("$5:0", NumberStyles.Any, distinctNFI, 5, true); passed &= VerifyDecimalTryParse("$5;0", NumberStyles.Any, distinctNFI, 50, true); passed &= VerifyDecimalTryParse("123,456;789.0", NumberStyles.Number, distinctNFI, 0, false); passed &= VerifyDecimalTryParse("123,456;789.0", NumberStyles.Currency, distinctNFI, 123456789, true); passed &= VerifyDecimalTryParse("123,456;789.0", NumberStyles.Any, distinctNFI, 123456789, true); passed &= VerifyDecimalTryParse("$123,456;789.0", NumberStyles.Any, distinctNFI, 0, false); // Underflow cases - see VSWhidbey #576556 passed &= VerifyExactDecimalTryParse("0E-27", NumberStyles.AllowExponent, invariantCulture, zeroScale27, true); passed &= VerifyExactDecimalTryParse("0E-28", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0E-29", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0E-30", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0E-31", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0E-50", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0E-100", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("0.000000000000000000000000000", zeroScale27, true); passed &= VerifyExactDecimalTryParse("0.0000000000000000000000000000", zeroScale28, true); //28 passed &= VerifyExactDecimalTryParse("0.00000000000000000000000000000", zeroScale28, true); //29 passed &= VerifyExactDecimalTryParse("0.000000000000000000000000000000", zeroScale28, true); //30 passed &= VerifyExactDecimalTryParse("0.0000000000000000000000000000000", zeroScale28, true); //31 passed &= VerifyExactDecimalTryParse("0.0", new Decimal(0, 0, 0, false, 1), true); passed &= VerifyExactDecimalTryParse("0E-15", NumberStyles.AllowExponent, invariantCulture, new Decimal(0, 0, 0, false, 15), true); passed &= VerifyExactDecimalTryParse("0", Decimal.Zero, true); passed &= VerifyExactDecimalTryParse("1E-27", NumberStyles.AllowExponent, invariantCulture, oneScale27, true); passed &= VerifyExactDecimalTryParse("1E-28", NumberStyles.AllowExponent, invariantCulture, oneScale28, true); passed &= VerifyExactDecimalTryParse("1E-29", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("1E-30", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("1E-31", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("1E-50", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); passed &= VerifyExactDecimalTryParse("1E-100", NumberStyles.AllowExponent, invariantCulture, zeroScale28, true); // make sure parse lines up with compiler //passed &= VerifyExactDecimalTryParse("0E-50", NumberStyles.AllowExponent, invariantCulture, 0E-50m, true); // V2->V4 compiler change passed &= VerifyExactDecimalTryParse("1E-50", NumberStyles.AllowExponent, invariantCulture, 1E-50m, true); passed &= VerifyExactDecimalTryParse("2E-100", NumberStyles.AllowExponent, invariantCulture, 2E-100m, true); passed &= VerifyExactDecimalTryParse("100E-29", NumberStyles.AllowExponent, invariantCulture, 100E-29m, true); passed &= VerifyExactDecimalTryParse("200E-29", NumberStyles.AllowExponent, invariantCulture, 200E-29m, true); passed &= VerifyExactDecimalTryParse("500E-29", NumberStyles.AllowExponent, invariantCulture, 500E-29m, true); passed &= VerifyExactDecimalTryParse("900E-29", NumberStyles.AllowExponent, invariantCulture, 900E-29m, true); passed &= VerifyExactDecimalTryParse("1900E-29", NumberStyles.AllowExponent, invariantCulture, 1900E-29m, true); passed &= VerifyExactDecimalTryParse("10900E-29", NumberStyles.AllowExponent, invariantCulture, 10900E-29m, true); passed &= VerifyExactDecimalTryParse("10900E-30", NumberStyles.AllowExponent, invariantCulture, 10900E-30m, true); passed &= VerifyExactDecimalTryParse("10900E-31", NumberStyles.AllowExponent, invariantCulture, 10900E-31m, true); passed &= VerifyExactDecimalTryParse("10900E-32", NumberStyles.AllowExponent, invariantCulture, 10900E-32m, true); passed &= VerifyExactDecimalTryParse("10900E-33", NumberStyles.AllowExponent, invariantCulture, 10900E-33m, true); passed &= VerifyExactDecimalTryParse("10900E-34", NumberStyles.AllowExponent, invariantCulture, 10900E-34m, true); passed &= VerifyExactDecimalTryParse("10900E-340", NumberStyles.AllowExponent, invariantCulture, 10900E-340m, true); passed &= VerifyExactDecimalTryParse("10900E-512", NumberStyles.AllowExponent, invariantCulture, 10900E-512m, true); passed &= VerifyExactDecimalTryParse("10900E-678", NumberStyles.AllowExponent, invariantCulture, 10900E-678m, true); passed &= VerifyExactDecimalTryParse("10900E-999", NumberStyles.AllowExponent, invariantCulture, 10900E-999m, true); // Should these pass or fail? Current parse behavior is to pass, so they might be // parse bugs, but they're not tryparse bugs. passed &= VerifyDecimalParse("5", NumberStyles.AllowExponent, goodNFI, 5); passed &= VerifyDecimalTryParse("5", NumberStyles.AllowExponent, goodNFI, 5, true); // I expect ArgumentException with an ambiguous NFI passed &= VerifyDecimalParse("^42", NumberStyles.Any, ambigNFI, -42); passed &= VerifyDecimalTryParse("^42", NumberStyles.Any, ambigNFI, -42, true); /// END TEST CASES } catch (Exception e) { TestLibrary.Logging.WriteLine("Unexpected exception!! " + e.ToString()); passed = false; } if (passed) { TestLibrary.Logging.WriteLine("paSs"); return 100; } else { TestLibrary.Logging.WriteLine("FAiL"); return 1; } } public static bool VerifyDecimalTryParse(string value, Decimal expectedResult, bool expectedReturn) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.TryParse, Value = '{0}', Expected Result = {1}, Expected Return = {2}", value, expectedResult, expectedReturn); } Decimal result = 0; try { bool returnValue = Decimal.TryParse(value, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedReturn, returnValue); return false; } if (result != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyDecimalTryParse(string value, NumberStyles style, IFormatProvider provider, Decimal expectedResult, bool expectedReturn) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Result = {3}, Expected Return = {4}", value, style, provider, expectedResult, expectedReturn); } Decimal result = 0; try { bool returnValue = Decimal.TryParse(value, style, provider, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Style = {1}, Provider = {2}, Expected Return = {3}, Actual Return = {4}", value, style, provider, expectedReturn, returnValue); return false; } if (result != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyDecimalTryParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}", value, style, provider, exceptionType); } try { Decimal result = 0; Boolean returnValue = Decimal.TryParse(value, style, provider, out result); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyDecimalParse(string value, Decimal expectedResult) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Expected Result, {1}", value, expectedResult); } try { Decimal returnValue = Decimal.Parse(value); if (returnValue != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyDecimalParse(string value, NumberStyles style, IFormatProvider provider, Decimal expectedResult) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Style = {1}, provider = {2}, Expected Result = {3}", value, style, provider, expectedResult); } try { Decimal returnValue = Decimal.Parse(value, style, provider); if (returnValue != expectedResult) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static String HexValue(Decimal value) { Int32[] bits = Decimal.GetBits(value); return String.Format("{{0x{0:X8} {1:X8} {2:X8} {3:X8} }}", bits[0], bits[1], bits[2], bits[3]); } // Verify that decimals have the same bits, not just the same values. public static Boolean CompareExact(Decimal x, Decimal y) { Int32[] arrayX = Decimal.GetBits(x); Int32[] arrayY = Decimal.GetBits(y); for (int i = 0; i < 4; i++) { if (arrayX[i] != arrayY[i]) { return false; } } return true; } public static bool VerifyExactDecimalParse(string value, Decimal expectedResult) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Expected Result = {1}", value, expectedResult); } try { Decimal returnValue = Decimal.Parse(value); if (!CompareExact(returnValue, expectedResult)) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, HexValue(expectedResult), HexValue(returnValue)); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyExactDecimalParse(string value, NumberStyles style, Decimal expectedResult) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Style = {1}, Expected Result = {2}", value, style, expectedResult); } try { Decimal returnValue = Decimal.Parse(value, style); if (!CompareExact(returnValue, expectedResult)) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, HexValue(expectedResult), HexValue(returnValue)); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyExactDecimalParse(string value, NumberStyles style, IFormatProvider provider, Decimal expectedResult) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Style = {1}, provider = {2}, Expected Result = {3}", value, style, provider, expectedResult); } try { Decimal returnValue = Decimal.Parse(value, style, provider); if (!CompareExact(returnValue, expectedResult)) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, HexValue(expectedResult), HexValue(returnValue)); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyExactDecimalTryParse(string value, Decimal expectedResult, bool expectedReturn) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.TryParse, Value = '{0}', Expected Result = {1}, Expected Return = {2}", value, expectedResult, expectedReturn); } Decimal result = 0; try { bool returnValue = Decimal.TryParse(value, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedReturn, returnValue); return false; } if (!CompareExact(result, expectedResult)) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, HexValue(expectedResult), HexValue(result)); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyExactDecimalTryParse(string value, NumberStyles style, IFormatProvider provider, Decimal expectedResult, bool expectedReturn) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Result = {3}, Expected Return = {4}", value, style, provider, expectedResult, expectedReturn); } Decimal result = 0; try { bool returnValue = Decimal.TryParse(value, style, provider, out result); if (returnValue != expectedReturn) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Style = {1}, Provider = {2}, Expected Return = {3}, Actual Return = {4}", value, style, provider, expectedReturn, returnValue); return false; } if (!CompareExact(result, expectedResult)) { TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, HexValue(expectedResult), HexValue(result)); return false; } return true; } catch (Exception ex) { TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex); return false; } } public static bool VerifyDecimalParseException(string value, Type exceptionType) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Expected Exception, {1}", value, exceptionType); } try { Decimal returnValue = Decimal.Parse(value); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyDecimalParseException(string value, NumberStyles style, Type exceptionType) { if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Style = {1}, Expected Exception = {3}", value, style, exceptionType); } try { Decimal returnValue = Decimal.Parse(value, style); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } public static bool VerifyDecimalParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (provider == null) return true; if (verbose) { TestLibrary.Logging.WriteLine("Test: Decimal.Parse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}", value, style, provider, exceptionType); } try { Decimal returnValue = Decimal.Parse(value, style, provider); TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType); return false; } catch (Exception ex) { if (!ex.GetType().IsAssignableFrom(exceptionType)) { TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType); return false; } return true; } } }
#pragma warning disable 1634, 1691 using System; using System.Text; using System.CodeDom; using System.Reflection; using System.Globalization; using System.Collections.Generic; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Serialization; using System.Workflow.Activities.Common; namespace System.Workflow.Activities.Rules { [Serializable] public abstract class RuleAction { public abstract bool Validate(RuleValidation validator); public abstract void Execute(RuleExecution context); public abstract ICollection<string> GetSideEffects(RuleValidation validation); public abstract RuleAction Clone(); } [Serializable] public class RuleHaltAction : RuleAction { public override bool Validate(RuleValidation validator) { // Trivial... nothing to validate. return true; } public override void Execute(RuleExecution context) { if (context == null) throw new ArgumentNullException("context"); context.Halted = true; } public override ICollection<string> GetSideEffects(RuleValidation validation) { return null; } public override RuleAction Clone() { return (RuleAction)this.MemberwiseClone(); } public override string ToString() { return "Halt"; } public override bool Equals(object obj) { return (obj is RuleHaltAction); } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] public class RuleUpdateAction : RuleAction { private string path; public RuleUpdateAction(string path) { this.path = path; } public RuleUpdateAction() { } public string Path { get { return path; } set { path = value; } } public override bool Validate(RuleValidation validator) { if (validator == null) throw new ArgumentNullException("validator"); bool success = true; if (path == null) { ValidationError error = new ValidationError(Messages.NullUpdate, ErrorNumbers.Error_ParameterNotSet); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; } // now make sure that the path is valid string[] parts = path.Split('/'); if (parts[0] == "this") { Type currentType = validator.ThisType; for (int i = 1; i < parts.Length; ++i) { if (parts[i] == "*") { if (i < parts.Length - 1) { // The "*" occurred in the middle of the path, which is a no-no. ValidationError error = new ValidationError(Messages.InvalidWildCardInPathQualifier, ErrorNumbers.Error_InvalidWildCardInPathQualifier); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; break; } else { // It occurred at the end, which is okay. break; } } else if (string.IsNullOrEmpty(parts[i]) && i == parts.Length - 1) { // It's okay to end with a "/". break; } while (currentType.IsArray) currentType = currentType.GetElementType(); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (validator.AllowInternalMembers(currentType)) bindingFlags |= BindingFlags.NonPublic; FieldInfo field = currentType.GetField(parts[i], bindingFlags); if (field != null) { currentType = field.FieldType; } else { PropertyInfo property = currentType.GetProperty(parts[i], bindingFlags); if (property != null) { currentType = property.PropertyType; } else { string message = string.Format(CultureInfo.CurrentCulture, Messages.UpdateUnknownFieldOrProperty, parts[i]); ValidationError error = new ValidationError(message, ErrorNumbers.Error_InvalidUpdate); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; break; } } } } else { ValidationError error = new ValidationError(Messages.UpdateNotThis, ErrorNumbers.Error_InvalidUpdate); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; } return success; } public override void Execute(RuleExecution context) { // This action has no execution behaviour. } public override ICollection<string> GetSideEffects(RuleValidation validation) { return new string[] { this.path }; } public override RuleAction Clone() { return (RuleAction)this.MemberwiseClone(); } public override string ToString() { return "Update(\"" + this.path + "\")"; } public override bool Equals(object obj) { #pragma warning disable 56506 RuleUpdateAction other = obj as RuleUpdateAction; return ((other != null) && (string.Equals(this.Path, other.Path, StringComparison.Ordinal))); #pragma warning restore 56506 } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] public class RuleStatementAction : RuleAction { private CodeStatement codeDomStatement; public RuleStatementAction(CodeStatement codeDomStatement) { this.codeDomStatement = codeDomStatement; } public RuleStatementAction(CodeExpression codeDomExpression) { this.codeDomStatement = new CodeExpressionStatement(codeDomExpression); } public RuleStatementAction() { } public CodeStatement CodeDomStatement { get { return codeDomStatement; } set { codeDomStatement = value; } } public override bool Validate(RuleValidation validator) { if (validator == null) throw new ArgumentNullException("validator"); if (codeDomStatement == null) { ValidationError error = new ValidationError(Messages.NullStatement, ErrorNumbers.Error_ParameterNotSet); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); return false; } else { return CodeDomStatementWalker.Validate(validator, codeDomStatement); } } public override void Execute(RuleExecution context) { if (codeDomStatement == null) throw new InvalidOperationException(Messages.NullStatement); CodeDomStatementWalker.Execute(context, codeDomStatement); } public override ICollection<string> GetSideEffects(RuleValidation validation) { RuleAnalysis analysis = new RuleAnalysis(validation, true); if (codeDomStatement != null) CodeDomStatementWalker.AnalyzeUsage(analysis, codeDomStatement); return analysis.GetSymbols(); } public override RuleAction Clone() { RuleStatementAction newAction = (RuleStatementAction)this.MemberwiseClone(); newAction.codeDomStatement = CodeDomStatementWalker.Clone(codeDomStatement); return newAction; } public override string ToString() { if (codeDomStatement == null) return ""; StringBuilder decompilation = new StringBuilder(); CodeDomStatementWalker.Decompile(decompilation, codeDomStatement); return decompilation.ToString(); } public override bool Equals(object obj) { #pragma warning disable 56506 RuleStatementAction other = obj as RuleStatementAction; return ((other != null) && (CodeDomStatementWalker.Match(CodeDomStatement, other.CodeDomStatement))); #pragma warning restore 56506 } public override int GetHashCode() { return base.GetHashCode(); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.OpsWorks.Model { /// <summary> /// <para>Describes an instance's Amazon EBS volume.</para> /// </summary> public class Volume { private string volumeId; private string ec2VolumeId; private string name; private string raidArrayId; private string instanceId; private string status; private int? size; private string device; private string mountPoint; private string region; private string availabilityZone; /// <summary> /// The volume ID. /// /// </summary> public string VolumeId { get { return this.volumeId; } set { this.volumeId = value; } } /// <summary> /// Sets the VolumeId property /// </summary> /// <param name="volumeId">The value to set for the VolumeId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithVolumeId(string volumeId) { this.volumeId = volumeId; return this; } // Check to see if VolumeId property is set internal bool IsSetVolumeId() { return this.volumeId != null; } /// <summary> /// The Amazon EC2 volume ID. /// /// </summary> public string Ec2VolumeId { get { return this.ec2VolumeId; } set { this.ec2VolumeId = value; } } /// <summary> /// Sets the Ec2VolumeId property /// </summary> /// <param name="ec2VolumeId">The value to set for the Ec2VolumeId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithEc2VolumeId(string ec2VolumeId) { this.ec2VolumeId = ec2VolumeId; return this; } // Check to see if Ec2VolumeId property is set internal bool IsSetEc2VolumeId() { return this.ec2VolumeId != null; } /// <summary> /// The volume name. /// /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// The RAID array ID. /// /// </summary> public string RaidArrayId { get { return this.raidArrayId; } set { this.raidArrayId = value; } } /// <summary> /// Sets the RaidArrayId property /// </summary> /// <param name="raidArrayId">The value to set for the RaidArrayId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithRaidArrayId(string raidArrayId) { this.raidArrayId = raidArrayId; return this; } // Check to see if RaidArrayId property is set internal bool IsSetRaidArrayId() { return this.raidArrayId != null; } /// <summary> /// The instance ID. /// /// </summary> public string InstanceId { get { return this.instanceId; } set { this.instanceId = value; } } /// <summary> /// Sets the InstanceId property /// </summary> /// <param name="instanceId">The value to set for the InstanceId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithInstanceId(string instanceId) { this.instanceId = instanceId; return this; } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this.instanceId != null; } /// <summary> /// The value returned by <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html">DescribeVolumes</a>. /// /// </summary> public string Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Sets the Status property /// </summary> /// <param name="status">The value to set for the Status property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithStatus(string status) { this.status = status; return this; } // Check to see if Status property is set internal bool IsSetStatus() { return this.status != null; } /// <summary> /// The volume size. /// /// </summary> public int Size { get { return this.size ?? default(int); } set { this.size = value; } } /// <summary> /// Sets the Size property /// </summary> /// <param name="size">The value to set for the Size property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithSize(int size) { this.size = size; return this; } // Check to see if Size property is set internal bool IsSetSize() { return this.size.HasValue; } /// <summary> /// The device name. /// /// </summary> public string Device { get { return this.device; } set { this.device = value; } } /// <summary> /// Sets the Device property /// </summary> /// <param name="device">The value to set for the Device property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithDevice(string device) { this.device = device; return this; } // Check to see if Device property is set internal bool IsSetDevice() { return this.device != null; } /// <summary> /// The volume mount point. For example "/dev/sdh". /// /// </summary> public string MountPoint { get { return this.mountPoint; } set { this.mountPoint = value; } } /// <summary> /// Sets the MountPoint property /// </summary> /// <param name="mountPoint">The value to set for the MountPoint property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithMountPoint(string mountPoint) { this.mountPoint = mountPoint; return this; } // Check to see if MountPoint property is set internal bool IsSetMountPoint() { return this.mountPoint != null; } /// <summary> /// The AWS region. For more information about AWS regions, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and /// Endpoints</a>. /// /// </summary> public string Region { get { return this.region; } set { this.region = value; } } /// <summary> /// Sets the Region property /// </summary> /// <param name="region">The value to set for the Region property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithRegion(string region) { this.region = region; return this; } // Check to see if Region property is set internal bool IsSetRegion() { return this.region != null; } /// <summary> /// The volume Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and /// Endpoints</a>. /// /// </summary> public string AvailabilityZone { get { return this.availabilityZone; } set { this.availabilityZone = value; } } /// <summary> /// Sets the AvailabilityZone property /// </summary> /// <param name="availabilityZone">The value to set for the AvailabilityZone property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Volume WithAvailabilityZone(string availabilityZone) { this.availabilityZone = availabilityZone; return this; } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this.availabilityZone != null; } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Markup; using Fluent.Collections; using Fluent.Extensions; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents quick access toolbar /// </summary> [TemplatePart(Name = "PART_ShowAbove", Type = typeof(MenuItem))] [TemplatePart(Name = "PART_ShowBelow", Type = typeof(MenuItem))] [TemplatePart(Name = "PART_MenuPanel", Type = typeof(Panel))] [TemplatePart(Name = "PART_RootPanel", Type = typeof(Panel))] [ContentProperty(nameof(QuickAccessItems))] [TemplatePart(Name = "PART_MenuDownButton", Type = typeof(DropDownButton))] [TemplatePart(Name = "PART_ToolbarDownButton", Type = typeof(DropDownButton))] [TemplatePart(Name = "PART_ToolBarPanel", Type = typeof(Panel))] [TemplatePart(Name = "PART_ToolBarOverflowPanel", Type = typeof(Panel))] public class QuickAccessToolBar : Control, ILogicalChildSupport { #region Events /// <summary> /// Occured when items are added or removed from Quick Access toolbar /// </summary> public event NotifyCollectionChangedEventHandler? ItemsChanged; #endregion #region Fields private DropDownButton? toolBarDownButton; internal DropDownButton? MenuDownButton { get; private set; } // Show above menu item private MenuItem? showAbove; // Show below menu item private MenuItem? showBelow; // Items of quick access menu private ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem>? quickAccessItems; // Root panel private Panel? rootPanel; // ToolBar panel private Panel? toolBarPanel; // ToolBar overflow panel private Panel? toolBarOverflowPanel; // Items of quick access menu private ObservableCollection<UIElement>? items; private Size cachedConstraint; private int cachedNonOverflowItemsCount = -1; // Itemc collection was changed private bool itemsHadChanged; private double cachedMenuDownButtonWidth; private double cachedOverflowDownButtonWidth; #endregion #region Properties #region Items /// <summary> /// Gets items collection /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ObservableCollection<UIElement> Items { get { if (this.items is null) { this.items = new ObservableCollection<UIElement>(); this.items.CollectionChanged += this.OnItemsCollectionChanged; } return this.items; } } private void OnItemsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { this.cachedNonOverflowItemsCount = this.GetNonOverflowItemsCount(this.DesiredSize.Width); this.UpdateHasOverflowItems(); this.itemsHadChanged = true; this.Refresh(); this.UpdateKeyTips(); if (e.OldItems is not null) { foreach (var item in e.OldItems.OfType<FrameworkElement>()) { item.SizeChanged -= this.OnChildSizeChanged; } } if (e.NewItems is not null) { foreach (var item in e.NewItems.OfType<FrameworkElement>()) { item.SizeChanged += this.OnChildSizeChanged; } } if (e.Action == NotifyCollectionChangedAction.Reset) { foreach (var item in this.Items.OfType<FrameworkElement>()) { item.SizeChanged -= this.OnChildSizeChanged; } } // Raise items changed event this.ItemsChanged?.Invoke(this, e); if ((this.Items.Count == 0 || this.cachedNonOverflowItemsCount == this.Items.Count) && this.toolBarDownButton is not null) { this.toolBarDownButton.IsDropDownOpen = false; } } private void OnChildSizeChanged(object? sender, SizeChangedEventArgs e) { this.InvalidateMeasureOfTitleBar(); } #endregion #region HasOverflowItems /// <summary> /// Gets whether QuickAccessToolBar has overflow items /// </summary> public bool HasOverflowItems { get { return (bool)this.GetValue(HasOverflowItemsProperty); } private set { this.SetValue(HasOverflowItemsPropertyKey, BooleanBoxes.Box(value)); } } // ReSharper disable once InconsistentNaming private static readonly DependencyPropertyKey HasOverflowItemsPropertyKey = DependencyProperty.RegisterReadOnly(nameof(HasOverflowItems), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary>Identifies the <see cref="HasOverflowItems"/> dependency property.</summary> public static readonly DependencyProperty HasOverflowItemsProperty = HasOverflowItemsPropertyKey.DependencyProperty; #endregion #region QuickAccessItems /// <summary> /// Gets quick access menu items /// </summary> public ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem> QuickAccessItems { get { if (this.quickAccessItems is null) { this.quickAccessItems = new ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem>(this); this.quickAccessItems.CollectionChanged += this.OnQuickAccessItemsCollectionChanged; } return this.quickAccessItems; } } /// <summary> /// Handles collection of quick access menu items changes /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnQuickAccessItemsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (this.MenuDownButton is null) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var item in e.NewItems.NullSafe().OfType<QuickAccessMenuItem>()) { var index = this.QuickAccessItems.IndexOf(item); this.MenuDownButton.Items.Insert(index + 1, item); this.QuickAccessItems[index].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; case NotifyCollectionChangedAction.Remove: foreach (var item in e.OldItems.NullSafe().OfType<QuickAccessMenuItem>()) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems.NullSafe().OfType<QuickAccessMenuItem>()) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } foreach (var item in e.NewItems.NullSafe().OfType<QuickAccessMenuItem>()) { var index = this.QuickAccessItems.IndexOf(item); this.MenuDownButton.Items.Insert(index + 1, item); this.QuickAccessItems[index].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; } } #endregion #region ShowAboveRibbon /// <summary> /// Gets or sets whether quick access toolbar showes above ribbon /// </summary> public bool ShowAboveRibbon { get { return (bool)this.GetValue(ShowAboveRibbonProperty); } set { this.SetValue(ShowAboveRibbonProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="ShowAboveRibbon"/> dependency property.</summary> public static readonly DependencyProperty ShowAboveRibbonProperty = DependencyProperty.Register(nameof(ShowAboveRibbon), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region CanQuickAccessLocationChanging /// <summary> /// Gets or sets whether user can change location of QAT /// </summary> public bool CanQuickAccessLocationChanging { get { return (bool)this.GetValue(CanQuickAccessLocationChangingProperty); } set { this.SetValue(CanQuickAccessLocationChangingProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="CanQuickAccessLocationChanging"/> dependency property.</summary> public static readonly DependencyProperty CanQuickAccessLocationChangingProperty = DependencyProperty.Register(nameof(CanQuickAccessLocationChanging), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region DropDownVisibility /// <summary> /// Gets or sets whether the Menu-DropDown is visible or not. /// </summary> public bool IsMenuDropDownVisible { get { return (bool)this.GetValue(IsMenuDropDownVisibleProperty); } set { this.SetValue(IsMenuDropDownVisibleProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="IsMenuDropDownVisible"/> dependency property.</summary> public static readonly DependencyProperty IsMenuDropDownVisibleProperty = DependencyProperty.Register(nameof(IsMenuDropDownVisible), typeof(bool), typeof(QuickAccessToolBar), new FrameworkPropertyMetadata(BooleanBoxes.TrueBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, OnIsMenuDropDownVisibleChanged)); private static void OnIsMenuDropDownVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (QuickAccessToolBar)d; if ((bool)e.NewValue == false) { control.cachedMenuDownButtonWidth = 0; } } #endregion DropDownVisibility #endregion #region Initialization /// <summary> /// Static constructor /// </summary> static QuickAccessToolBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(QuickAccessToolBar), new FrameworkPropertyMetadata(typeof(QuickAccessToolBar))); } /// <summary> /// Creates a new instance. /// </summary> public QuickAccessToolBar() { this.Loaded += (sender, args) => this.InvalidateMeasureOfTitleBar(); } #endregion #region Override /// <inheritdoc /> public override void OnApplyTemplate() { if (this.showAbove is not null) { this.showAbove.Click -= this.OnShowAboveClick; } if (this.showBelow is not null) { this.showBelow.Click -= this.OnShowBelowClick; } this.showAbove = this.GetTemplateChild("PART_ShowAbove") as MenuItem; this.showBelow = this.GetTemplateChild("PART_ShowBelow") as MenuItem; if (this.showAbove is not null) { this.showAbove.Click += this.OnShowAboveClick; } if (this.showBelow is not null) { this.showBelow.Click += this.OnShowBelowClick; } if (this.MenuDownButton is not null) { foreach (var item in this.QuickAccessItems) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } this.QuickAccessItems.AquireLogicalOwnership(); } this.MenuDownButton = this.GetTemplateChild("PART_MenuDownButton") as DropDownButton; if (this.MenuDownButton is not null) { this.QuickAccessItems.ReleaseLogicalOwnership(); for (var i = 0; i < this.QuickAccessItems.Count; i++) { this.MenuDownButton.Items.Insert(i + 1, this.QuickAccessItems[i]); this.QuickAccessItems[i].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } } this.toolBarDownButton = this.GetTemplateChild("PART_ToolbarDownButton") as DropDownButton; // ToolBar panels this.toolBarPanel = this.GetTemplateChild("PART_ToolBarPanel") as Panel; this.toolBarOverflowPanel = this.GetTemplateChild("PART_ToolBarOverflowPanel") as Panel; if (this.rootPanel is not null) { this.RemoveLogicalChild(this.rootPanel); } this.rootPanel = this.GetTemplateChild("PART_RootPanel") as Panel; if (this.rootPanel is not null) { this.AddLogicalChild(this.rootPanel); } // Clears cache this.cachedMenuDownButtonWidth = 0; this.cachedOverflowDownButtonWidth = 0; this.cachedNonOverflowItemsCount = this.GetNonOverflowItemsCount(this.ActualWidth); this.cachedConstraint = default; } /// <summary> /// Handles show below menu item click /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnShowBelowClick(object sender, RoutedEventArgs e) { this.ShowAboveRibbon = false; } /// <summary> /// Handles show above menu item click /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnShowAboveClick(object sender, RoutedEventArgs e) { this.ShowAboveRibbon = true; } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { if (this.IsLoaded == false) { return base.MeasureOverride(constraint); } if ((this.cachedConstraint == constraint) && !this.itemsHadChanged) { return base.MeasureOverride(constraint); } var nonOverflowItemsCount = this.GetNonOverflowItemsCount(constraint.Width); if (this.itemsHadChanged == false && nonOverflowItemsCount == this.cachedNonOverflowItemsCount) { return base.MeasureOverride(constraint); } this.cachedNonOverflowItemsCount = nonOverflowItemsCount; this.UpdateHasOverflowItems(); this.cachedConstraint = constraint; // Clear overflow panel to prevent items from having a visual/logical parent this.toolBarOverflowPanel?.Children.Clear(); if (this.toolBarPanel is not null) { if (this.itemsHadChanged) { // Refill toolbar this.toolBarPanel.Children.Clear(); for (var i = 0; i < this.cachedNonOverflowItemsCount; i++) { this.toolBarPanel.Children.Add(this.Items[i]); } } else { if (this.cachedNonOverflowItemsCount > this.toolBarPanel.Children.Count) { // Add needed items var savedCount = this.toolBarPanel.Children.Count; for (var i = savedCount; i < this.cachedNonOverflowItemsCount; i++) { this.toolBarPanel.Children.Add(this.Items[i]); } } else { // Remove nonneeded items for (var i = this.toolBarPanel.Children.Count - 1; i >= this.cachedNonOverflowItemsCount; i--) { this.toolBarPanel.Children.Remove(this.Items[i]); } } } } this.itemsHadChanged = false; // Move overflowing items to overflow panel for (var i = this.cachedNonOverflowItemsCount; i < this.Items.Count; i++) { this.toolBarOverflowPanel?.Children.Add(this.Items[i]); } if (constraint.Equals(SizeConstants.Infinite)) { this.toolBarPanel?.Measure(constraint); } else { // It seems strange that we have to explicitly measure the toolbar panel, but if we don't do that the base measure call does not seem to measure correctly... if (this.cachedNonOverflowItemsCount > 0) { this.toolBarPanel?.Measure(new Size(Math.Max(0, constraint.Width - this.cachedMenuDownButtonWidth), constraint.Height)); } else { this.toolBarPanel?.Measure(new Size(Math.Max(0, constraint.Width - this.cachedOverflowDownButtonWidth), constraint.Height)); } } return base.MeasureOverride(constraint); } /// <summary> /// We have to use this function because setting a <see cref="DependencyProperty"/> very frequently is quite expensive /// </summary> private void UpdateHasOverflowItems() { var newValue = this.cachedNonOverflowItemsCount < this.Items.Count; // ReSharper disable RedundantCheckBeforeAssignment if (this.HasOverflowItems != newValue) // ReSharper restore RedundantCheckBeforeAssignment { // todo: code runs very often on startup this.HasOverflowItems = newValue; } } #endregion #region Methods /// <summary> /// First calls <see cref="UIElement.InvalidateMeasure"/> and then <see cref="InvalidateMeasureOfTitleBar"/> /// </summary> public void Refresh() { this.InvalidateMeasure(); this.InvalidateMeasureOfTitleBar(); } private void InvalidateMeasureOfTitleBar() { if (this.IsLoaded == false) { return; } var titleBar = RibbonControl.GetParentRibbon(this)?.TitleBar ?? UIHelper.GetParent<RibbonTitleBar>(this); titleBar?.ScheduleForceMeasureAndArrange(); } /// <summary> /// Gets or sets a custom action to generate KeyTips for items in this control. /// </summary> public Action<QuickAccessToolBar>? UpdateKeyTipsAction { get { return (Action<QuickAccessToolBar>?)this.GetValue(UpdateKeyTipsActionProperty); } set { this.SetValue(UpdateKeyTipsActionProperty, value); } } /// <summary>Identifies the <see cref="UpdateKeyTipsAction"/> dependency property.</summary> public static readonly DependencyProperty UpdateKeyTipsActionProperty = DependencyProperty.Register(nameof(UpdateKeyTipsAction), typeof(Action<QuickAccessToolBar>), typeof(QuickAccessToolBar), new PropertyMetadata(OnUpdateKeyTipsActionChanged)); private static void OnUpdateKeyTipsActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var quickAccessToolBar = (QuickAccessToolBar)d; quickAccessToolBar.UpdateKeyTips(); } private void UpdateKeyTips() { if (this.UpdateKeyTipsAction is null) { DefaultUpdateKeyTips(this); return; } this.UpdateKeyTipsAction(this); } // Updates keys for keytip access private static void DefaultUpdateKeyTips(QuickAccessToolBar quickAccessToolBar) { for (var i = 0; i < Math.Min(9, quickAccessToolBar.Items.Count); i++) { // 1, 2, 3, ... , 9 KeyTip.SetKeys(quickAccessToolBar.Items[i], (i + 1).ToString(CultureInfo.InvariantCulture)); } for (var i = 9; i < Math.Min(18, quickAccessToolBar.Items.Count); i++) { // 09, 08, 07, ... , 01 KeyTip.SetKeys(quickAccessToolBar.Items[i], "0" + (18 - i).ToString(CultureInfo.InvariantCulture)); } var startChar = 'A'; for (var i = 18; i < Math.Min(9 + 9 + 26, quickAccessToolBar.Items.Count); i++) { // 0A, 0B, 0C, ... , 0Z KeyTip.SetKeys(quickAccessToolBar.Items[i], "0" + startChar++); } } private int GetNonOverflowItemsCount(in double width) { // Cache width of menuDownButton if (DoubleUtil.AreClose(this.cachedMenuDownButtonWidth, 0) && this.rootPanel is not null && this.MenuDownButton is not null && this.IsMenuDropDownVisible) { this.rootPanel.Measure(SizeConstants.Infinite); this.cachedMenuDownButtonWidth = this.MenuDownButton.DesiredSize.Width; } // Cache width of toolBarDownButton if (DoubleUtil.AreClose(this.cachedOverflowDownButtonWidth, 0) && this.rootPanel is not null && this.MenuDownButton is not null) { this.rootPanel.Measure(SizeConstants.Infinite); this.cachedOverflowDownButtonWidth = this.toolBarDownButton?.DesiredSize.Width ?? default; } // If IsMenuDropDownVisible is true we have less width available var widthReductionWhenNotCompressed = this.IsMenuDropDownVisible ? this.cachedMenuDownButtonWidth : 0; return CalculateNonOverflowItems(this.Items, width, widthReductionWhenNotCompressed, this.cachedOverflowDownButtonWidth); } private static int CalculateNonOverflowItems(IList<UIElement> items, double maxAvailableWidth, double widthReductionWhenNotCompressed, double widthReductionWhenCompressed) { // Calculate how many items we can fit into the available width var maxPossibleItems = GetMaxPossibleItems(maxAvailableWidth - widthReductionWhenNotCompressed, true); if (maxPossibleItems < items.Count) { // If we can't fit all items into the available width // we have to reduce the available width as the overflow button also needs space. var availableWidth = maxAvailableWidth - widthReductionWhenCompressed; return GetMaxPossibleItems(availableWidth, false); } return items.Count; int GetMaxPossibleItems(double availableWidth, bool measureItems) { var currentWidth = 0D; for (var i = 0; i < items.Count; i++) { var currentItem = items[i]; if (measureItems) { currentItem.Measure(SizeConstants.Infinite); } currentWidth += currentItem.DesiredSize.Width; if (currentWidth > availableWidth) { return i; } } return items.Count; } } #endregion /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonQuickAccessToolBarAutomationPeer(this); /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } yield return this.rootPanel; foreach (var item in this.QuickAccessItems.GetLogicalChildren()) { yield return item; } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors; using OpenSim.Services.Connectors.SimianGrid; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryBroker")] public class HGInventoryBroker : ISharedRegionModule, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static bool m_Enabled = false; private static IInventoryService m_LocalGridInventoryService; private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>(); // A cache of userIDs --> ServiceURLs, for HGBroker only protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>(); private List<Scene> m_Scenes = new List<Scene>(); private InventoryCache m_Cache = new InventoryCache(); /// <summary> /// Used to serialize inventory requests. /// </summary> private object m_Lock = new object(); protected IUserManagement m_UserManagement; protected IUserManagement UserManagementModule { get { if (m_UserManagement == null) { m_UserManagement = m_Scenes[0].RequestModuleInterface<IUserManagement>(); if (m_UserManagement == null) m_log.ErrorFormat( "[HG INVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}", m_Scenes[0].RegionInfo.RegionName); } return m_UserManagement; } } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGInventoryBroker"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryServices", ""); if (name == Name) { IConfig inventoryConfig = source.Configs["InventoryService"]; if (inventoryConfig == null) { m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); return; } string localDll = inventoryConfig.GetString("LocalGridInventoryService", String.Empty); //string HGDll = inventoryConfig.GetString("HypergridInventoryService", // String.Empty); if (localDll == String.Empty) { m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService"); //return; throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); } Object[] args = new Object[] { source }; m_LocalGridInventoryService = ServerUtils.LoadPlugin<IInventoryService>(localDll, args); if (m_LocalGridInventoryService == null) { m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service"); return; } m_Enabled = true; m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType()); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scenes.Add(scene); scene.RegisterModuleInterface<IInventoryService>(this); if (m_Scenes.Count == 1) { // FIXME: The local connector needs the scene to extract the UserManager. However, it's not enabled so // we can't just add the region. But this approach is super-messy. if (m_LocalGridInventoryService is RemoteXInventoryServicesConnector) { m_log.DebugFormat( "[HG INVENTORY BROKER]: Manually setting scene in RemoteXInventoryServicesConnector to {0}", scene.RegionInfo.RegionName); ((RemoteXInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene; } else if (m_LocalGridInventoryService is LocalInventoryServicesConnector) { m_log.DebugFormat( "[HG INVENTORY BROKER]: Manually setting scene in LocalInventoryServicesConnector to {0}", scene.RegionInfo.RegionName); ((LocalInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene; } scene.EventManager.OnClientClosed += OnClientClosed; } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scenes.Remove(scene); } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName); } #region URL Cache void OnClientClosed(UUID clientID, Scene scene) { ScenePresence sp = null; foreach (Scene s in m_Scenes) { s.TryGetScenePresence(clientID, out sp); if ((sp != null) && !sp.IsChildAgent && (s != scene)) { m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache", scene.RegionInfo.RegionName, clientID); return; } } if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache DropInventoryServiceURL(clientID); m_Cache.RemoveAll(clientID); } /// <summary> /// Gets the user's inventory URL from its serviceURLs, if the user is foreign, /// and sticks it in the cache /// </summary> /// <param name="userID"></param> private void CacheInventoryServiceURL(UUID userID) { if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(userID)) { // The user is not local; let's cache its service URL string inventoryURL = string.Empty; ScenePresence sp = null; foreach (Scene scene in m_Scenes) { scene.TryGetScenePresence(userID, out sp); if (sp != null) { AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); if (aCircuit == null) return; if (aCircuit.ServiceURLs == null) return; if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) { inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); if (inventoryURL != null && inventoryURL != string.Empty) { inventoryURL = inventoryURL.Trim(new char[] { '/' }); lock (m_InventoryURLs) m_InventoryURLs[userID] = inventoryURL; m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL); return; } } // else // { // m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID); // return; // } } } if (sp == null) { inventoryURL = UserManagementModule.GetUserServerURL(userID, "InventoryServerURI"); if (!string.IsNullOrEmpty(inventoryURL)) { inventoryURL = inventoryURL.Trim(new char[] { '/' }); lock (m_InventoryURLs) m_InventoryURLs[userID] = inventoryURL; m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL); } } } } private void DropInventoryServiceURL(UUID userID) { lock (m_InventoryURLs) { if (m_InventoryURLs.ContainsKey(userID)) { string url = m_InventoryURLs[userID]; m_InventoryURLs.Remove(userID); m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url); } } } public string GetInventoryServiceURL(UUID userID) { lock (m_InventoryURLs) { if (m_InventoryURLs.ContainsKey(userID)) return m_InventoryURLs[userID]; } CacheInventoryServiceURL(userID); lock (m_InventoryURLs) { if (m_InventoryURLs.ContainsKey(userID)) return m_InventoryURLs[userID]; } return null; //it means that the methods should forward to local grid's inventory } #endregion #region IInventoryService public bool CreateUserInventory(UUID userID) { lock (m_Lock) return m_LocalGridInventoryService.CreateUserInventory(userID); } public List<InventoryFolderBase> GetInventorySkeleton(UUID userID) { string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetInventorySkeleton(userID); IInventoryService connector = GetConnector(invURL); return connector.GetInventorySkeleton(userID); } public InventoryFolderBase GetRootFolder(UUID userID) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID); InventoryFolderBase root = m_Cache.GetRootFolder(userID); if (root != null) return root; string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetRootFolder(userID); IInventoryService connector = GetConnector(invURL); root = connector.GetRootFolder(userID); m_Cache.Cache(userID, root); return root; } public InventoryFolderBase GetFolderForType(UUID userID, FolderType type) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type); InventoryFolderBase f = m_Cache.GetFolderForType(userID, type); if (f != null) return f; string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetFolderForType(userID, type); IInventoryService connector = GetConnector(invURL); f = connector.GetFolderForType(userID, type); m_Cache.Cache(userID, type, f); return f; } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetFolderContent(userID, folderID); InventoryCollection c = m_Cache.GetFolderContent(userID, folderID); if (c != null) { m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent found content in cache " + folderID); return c; } IInventoryService connector = GetConnector(invURL); return connector.GetFolderContent(userID, folderID); } public InventoryCollection[] GetMultipleFoldersContent(UUID userID, UUID[] folderIDs) { string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetMultipleFoldersContent(userID, folderIDs); else { InventoryCollection[] coll = new InventoryCollection[folderIDs.Length]; int i = 0; foreach (UUID fid in folderIDs) coll[i++] = GetFolderContent(userID, fid); return coll; } } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetFolderItems(userID, folderID); List<InventoryItemBase> items = m_Cache.GetFolderItems(userID, folderID); if (items != null) { m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems found items in cache " + folderID); return items; } IInventoryService connector = GetConnector(invURL); return connector.GetFolderItems(userID, folderID); } public bool AddFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.AddFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.AddFolder(folder); } public bool UpdateFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.UpdateFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.UpdateFolder(folder); } public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) { if (folderIDs == null) return false; if (folderIDs.Count == 0) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID); string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs); IInventoryService connector = GetConnector(invURL); return connector.DeleteFolders(ownerID, folderIDs); } public bool MoveFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.MoveFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.MoveFolder(folder); } public bool PurgeFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.PurgeFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.PurgeFolder(folder); } public bool AddItem(InventoryItemBase item) { if (item == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID); string invURL = GetInventoryServiceURL(item.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.AddItem(item); IInventoryService connector = GetConnector(invURL); return connector.AddItem(item); } public bool UpdateItem(InventoryItemBase item) { if (item == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID); string invURL = GetInventoryServiceURL(item.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.UpdateItem(item); IInventoryService connector = GetConnector(invURL); return connector.UpdateItem(item); } public bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { if (items == null) return false; if (items.Count == 0) return true; //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID); string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.MoveItems(ownerID, items); IInventoryService connector = GetConnector(invURL); return connector.MoveItems(ownerID, items); } public bool DeleteItems(UUID ownerID, List<UUID> itemIDs) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID); if (itemIDs == null) return false; if (itemIDs.Count == 0) return true; string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs); IInventoryService connector = GetConnector(invURL); return connector.DeleteItems(ownerID, itemIDs); } public InventoryItemBase GetItem(UUID principalID, UUID itemID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID); string invURL = GetInventoryServiceURL(principalID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetItem(principalID, itemID); IInventoryService connector = GetConnector(invURL); return connector.GetItem(principalID, itemID); } public InventoryItemBase[] GetMultipleItems(UUID userID, UUID[] itemIDs) { if (itemIDs == null) return new InventoryItemBase[0]; //m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetMultipleItems(userID, itemIDs); IInventoryService connector = GetConnector(invURL); return connector.GetMultipleItems(userID, itemIDs); } public InventoryFolderBase GetFolder(UUID principalID, UUID folderID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID); string invURL = GetInventoryServiceURL(principalID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetFolder(principalID, folderID); IInventoryService connector = GetConnector(invURL); return connector.GetFolder(principalID, folderID); } public bool HasInventoryForUser(UUID userID) { return false; } public List<InventoryItemBase> GetActiveGestures(UUID userId) { return new List<InventoryItemBase>(); } public int GetAssetPermissions(UUID userID, UUID assetID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve lock (m_Lock) return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID); IInventoryService connector = GetConnector(invURL); return connector.GetAssetPermissions(userID, assetID); } #endregion private IInventoryService GetConnector(string url) { IInventoryService connector = null; lock (m_connectors) { if (m_connectors.ContainsKey(url)) { connector = m_connectors[url]; } else { // Still not as flexible as I would like this to be, // but good enough for now string connectorType = new HeloServicesConnector(url).Helo(); m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType); if (connectorType == "opensim-simian") { connector = new SimianInventoryServiceConnector(url); } else { RemoteXInventoryServicesConnector rxisc = new RemoteXInventoryServicesConnector(url); rxisc.Scene = m_Scenes[0]; connector = rxisc; } m_connectors.Add(url, connector); } } return connector; } } }
using System; using System.Collections.Generic; using System.Linq; using DevExpress.CodeRush.Core; using System.Windows.Forms; using DevExpress.DXCore.Platform.Drawing; using System.ComponentModel; namespace DevExpress.CodeRush.Core { public sealed class MultiSelectServices : Service { private const string STR_ClipboardFormatName = "DXCore.MultiCodeSelect"; private const string STR_MultiSelectList = "MultiSelectList"; private const string STR_RedoMultiSelectList = "RedoMultiSelectList"; private Color _HighlightColor; #region internal constructor... internal MultiSelectServices() { } #endregion #region InitializeService protected override void InitializeService(InitializeCause cause) { base.InitializeService(cause); HookEvents(); SetHighlightColor(OptMultiSelect.DefaultSelectionColor); } #endregion #region FinalizeService protected override void FinalizeService(FinalizeCause cause) { UnhookEvents(); base.FinalizeService(cause); } #endregion // event handlers... #region EventNexus_DocumentRenamed void EventNexus_DocumentRenamed(DocumentRenamedEventArgs ea) { TextDocument textDocument = ea.Document as TextDocument; if (textDocument == null) return; TextView[] textViews = textDocument.GetTextViews(false); foreach (TextView textView in textViews) { MultiSelect multiSelect = CodeRushPlaceholder.MultiSelect.Get(textView); if (multiSelect != null) multiSelect.FileName = ea.NewName; } } #endregion #region EventNexus_OptionsChanged void EventNexus_OptionsChanged(OptionsChangedEventArgs ea) { if (!ea.OptionsPages.Contains(typeof(OptMultiSelect))) return; SetHighlightColor(OptMultiSelect.Storage.ReadColor("Appearance", "SelectionColor")); RefreshAllHighlighting(); } #endregion #region EventNexus_TextChanged void EventNexus_TextChanged(TextChangedEventArgs ea) { foreach (TextView textView in ea.TextDocument.GetTextViews()) Clear(textView); } #endregion // Methods hidden from Intellisense... #region HookEvents [Browsable(false)] internal void HookEvents() { EventNexus.TextChanged += new TextChangedEventHandler(EventNexus_TextChanged); EventNexus.DocumentRenamed += new DocumentRenamedEventHandler(EventNexus_DocumentRenamed); EventNexus.OptionsChanged += new OptionsChangedEventHandler(EventNexus_OptionsChanged); } #endregion #region GetRedo [Browsable(false)] public MultiSelect GetRedo(TextView textView) { return textView.Storage.GetObject(STR_RedoMultiSelectList) as MultiSelect; } #endregion #region Remove /// <summary> /// Removes the MultiSelect object from the specified TextView. /// </summary> /// <param name="textView">The TextView from which to remove the MultiSelect object.</param> [Browsable(false)] public void Remove(TextView textView) { textView.Storage.RemoveObject(STR_MultiSelectList); textView.Storage.RemoveObject(STR_RedoMultiSelectList); } #endregion #region Set /// <summary> /// Sets the MultiSelect object for the specified TextView. /// </summary> /// <param name="textView">The TextView to work with.</param> /// <param name="multiSelect">The MultiSelect instance to assign to the TextView.</param> [Browsable(false)] public void Set(TextView textView, MultiSelect multiSelect) { textView.Storage.AttachObject(STR_MultiSelectList, multiSelect); } #endregion #region SetRedo [Browsable(false)] public void SetRedo(TextView textView, MultiSelect redoMultiSelect) { textView.Storage.AttachObject(STR_RedoMultiSelectList, redoMultiSelect); } #endregion #region UnhookEvents [Browsable(false)] public void UnhookEvents() { EventNexus.TextChanged -= new TextChangedEventHandler(EventNexus_TextChanged); EventNexus.DocumentRenamed -= new DocumentRenamedEventHandler(EventNexus_DocumentRenamed); EventNexus.OptionsChanged -= new OptionsChangedEventHandler(EventNexus_OptionsChanged); } #endregion // protected internal overridden properties... #region Name protected override string Name { get { return "MultiSelect"; } } #endregion // public properties... #region HighlightColor public Color HighlightColor { get { return _HighlightColor; } set { _HighlightColor = value; } } #endregion // public methods... #region Add /// <summary> /// Adds the selection in the specified TextView to this view's MultiSelect list. /// </summary> /// <param name="textView">The TextView containing the MultiSelect list to add to.</param> public void Add(TextView textView) { if (textView == null) return; MultiSelect multiSelect = Get(textView); if (multiSelect == null) { multiSelect = new MultiSelect(); multiSelect.FileName = textView.FileNode.Name; multiSelect.Language = textView.TextDocument.Language; multiSelect.TypeName = CodeRush.Source.ActiveTypeName; Set(textView, multiSelect); } else if (multiSelect.TypeName != CodeRush.Source.ActiveTypeName) // Inconsistent class names, so let's clear it out. multiSelect.TypeName = String.Empty; MultiSelect redoMultiSelect = GetRedo(textView); if (redoMultiSelect != null) redoMultiSelect.Selections.Clear(); multiSelect.AddSelection(textView); } #endregion #region Clear /// <summary> /// Clears the multi-selection and removes it from the specified TextView. /// </summary> /// <param name="textView">The TextView containing the multi-selection to remove.</param> public void Clear(TextView textView) { MultiSelect multiSelect = Get(textView); if (multiSelect == null) return; multiSelect.Clear(); Remove(textView); } #endregion #region CopyToClipboard(MultiSelect multiSelect) /// <summary> /// Copies the specified MultiSelect object to the clipboard. /// </summary> /// <param name="multiSelect">The MultiSelect object to copy to the clipboard.</param> public void CopyToClipboard(MultiSelect multiSelect) { multiSelect.Sort(); DataFormats.Format format = DataFormats.GetFormat(STR_ClipboardFormatName); IDataObject dataObject = new DataObject(); dataObject.SetData(DataFormats.Text, multiSelect.ToText()); dataObject.SetData(format.Name, multiSelect); Clipboard.SetDataObject(dataObject, true); } #endregion #region CopyToClipboard(TextView textView) /// <summary> /// Copies the MultiSelect object from the specified TextView to the clipboard. /// </summary> /// <param name="textView">The TextView containing the MultiSelect object to copy.</param> /// <returns>The MultiSelect object from the active TextView.</returns> public MultiSelect CopyToClipboard(TextView textView) { MultiSelect multiSelect = Get(textView); if (multiSelect != null) multiSelect.CopyToClipboard(); return multiSelect; } #endregion #region CutToClipboard(TextView textView) /// <summary> /// Copies the MultiSelect object from the specified TextView to the clipboard and removes all selections. /// </summary> /// <param name="textView">The TextView containing the MultiSelect object to cut.</param> /// <returns>The MultiSelect object from the active TextView.</returns> public MultiSelect CutToClipboard(TextView textView) { MultiSelect multiSelect = Get(textView); if (multiSelect != null) { multiSelect.WasCut = true; multiSelect.CopyToClipboard(); } return multiSelect; } #endregion #region Delete public void Delete(MultiSelect multiSelect, string operation) { TextDocument textDocument = CodeRush.Documents.Get(multiSelect.FileName) as TextDocument; if (textDocument == null) return; foreach (PartialSelection selection in multiSelect.Selections) textDocument.QueueDelete(selection.Range); textDocument.ApplyQueuedEdits(operation); } #endregion #region FromClipboard public MultiSelect FromClipboard() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject.GetDataPresent(STR_ClipboardFormatName)) return dataObject.GetData(STR_ClipboardFormatName) as MultiSelect; return null; } #endregion #region Get /// <summary> /// Gets the MultiSelect object associated with the specified TextView. Returns null if no multi-selection exists. /// </summary> /// <param name="textView">The TextView to check.</param> public MultiSelect Get(TextView textView) { return textView.Storage.GetObject(STR_MultiSelectList) as MultiSelect; } #endregion #region IsOnClipboard public bool IsOnClipboard() { IDataObject dataObject = Clipboard.GetDataObject(); return dataObject.GetDataPresent(STR_ClipboardFormatName); } #endregion #region Redo public void Redo(TextView textView) { MultiSelect redoMultiSelect = CodeRushPlaceholder.MultiSelect.GetRedo(textView); if (redoMultiSelect == null || redoMultiSelect.Selections.Count <= 0) return; MultiSelect multiSelect = CodeRushPlaceholder.MultiSelect.Get(textView); if (multiSelect == null) return; int lastIndex = redoMultiSelect.Selections.Count - 1; multiSelect.AddSelection(textView, redoMultiSelect.Selections[lastIndex]); redoMultiSelect.Selections.RemoveAt(lastIndex); } #endregion #region RedoIsAvailable /// <summary> /// Returns true if a multi-select Redo operation is available for the specified TextView. /// </summary> /// <param name="textView">The TextView to check.</param> public bool RedoIsAvailable(TextView textView) { MultiSelect redoMultiSelect = GetRedo(textView); return redoMultiSelect != null && redoMultiSelect.Selections.Count > 0; } #endregion #region RefreshAllHighlighting /// <summary> /// Refreshes highlighting for all multi-select instances. /// </summary> public void RefreshAllHighlighting() { foreach (TextView textView in CodeRush.TextViews) { MultiSelect multiSelect = Get(textView); if (multiSelect != null) multiSelect.RefreshHighlighting(textView); } } #endregion #region SelectionExists /// <summary> /// Returns true if the specified TextView contains a MultiSelect object with at least one selection defined. /// </summary> /// <param name="textView">The TextView to check.</param> public bool SelectionExists(TextView textView) { MultiSelect multiSelect = Get(textView); if (multiSelect == null) return false; return multiSelect.Selections.Count > 0; } #endregion #region SetHighlightColor /// <summary> /// Sets the highlight color for multi-select instances. /// </summary> public void SetHighlightColor(System.Drawing.Color thisColor) { _HighlightColor = Color.FromRgb(thisColor.R, thisColor.G, thisColor.B); } #endregion #region Undo public void Undo(TextView activeTextView) { MultiSelect multiSelect = Get(activeTextView); if (multiSelect == null || multiSelect.Selections.Count == 0) return; MultiSelect redoMultiSelect = GetRedo(activeTextView); if (redoMultiSelect == null) { redoMultiSelect = new MultiSelect(); SetRedo(activeTextView, redoMultiSelect); } int lastIndex = multiSelect.Selections.Count - 1; PartialSelection selectionToRemove = multiSelect.GetSelectionAt(lastIndex); redoMultiSelect.Selections.Add(selectionToRemove); selectionToRemove.RemoveHighlighter(); activeTextView.Caret.MoveTo(selectionToRemove.CaretPosition); multiSelect.RemoveSelectionAt(lastIndex); } #endregion #region UndoIsAvailable /// <summary> /// Returns true if a multi-select Undo operation is available for the specified TextView. /// </summary> /// <param name="textView">The TextView to check.</param> public bool UndoIsAvailable(TextView textView) { MultiSelect multiSelect = Get(textView); return multiSelect != null && multiSelect.Selections.Count > 0; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for HybridRunbookWorkerGroupOperations. /// </summary> public static partial class HybridRunbookWorkerGroupOperationsExtensions { /// <summary> /// Delete a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// Automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> public static void Delete(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName) { operations.DeleteAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName).GetAwaiter().GetResult(); } /// <summary> /// Delete a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// Automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> public static HybridRunbookWorkerGroup Get(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName) { return operations.GetAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HybridRunbookWorkerGroup> GetAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='parameters'> /// The hybrid runbook worker group /// </param> public static HybridRunbookWorkerGroup Update(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='parameters'> /// The hybrid runbook worker group /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HybridRunbookWorkerGroup> UpdateAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> public static IPage<HybridRunbookWorkerGroup> ListByAutomationAccount(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName) { return operations.ListByAutomationAccountAsync(resourceGroupName, automationAccountName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<HybridRunbookWorkerGroup>> ListByAutomationAccountAsync(this IHybridRunbookWorkerGroupOperations operations, string resourceGroupName, string automationAccountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountWithHttpMessagesAsync(resourceGroupName, automationAccountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<HybridRunbookWorkerGroup> ListByAutomationAccountNext(this IHybridRunbookWorkerGroupOperations operations, string nextPageLink) { return operations.ListByAutomationAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<HybridRunbookWorkerGroup>> ListByAutomationAccountNextAsync(this IHybridRunbookWorkerGroupOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAutomationAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using UnityEngine; using System; using System.Collections.Generic; // TODO: Have a move list in the inspector instead of order value [AddComponentMenu("Modifiers/Modify Object")] [ExecuteInEditMode] public class MegaModifyObject : MegaModifiers { [HideInInspector] public Mesh cachedMesh; public bool InvisibleUpdate = false; bool visible = true; private static int CompareOrder(MegaModifier m1, MegaModifier m2) { return m1.Order - m2.Order; } [ContextMenu("Resort")] public virtual void Resort() { BuildList(); } [ContextMenu("Help")] public virtual void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=444"); } void OnDestroy() { if ( mesh != cachedMesh ) { if ( Application.isEditor ) DestroyImmediate(mesh); else Destroy(mesh); } } void Start() { if ( dynamicMesh ) cachedMesh = null; } public void GetMesh(bool force) { if ( mesh == null || cachedMesh == null || sverts.Length == 0 || mesh.vertexCount != sverts.Length || force ) { if ( dynamicMesh ) { cachedMesh = FindMesh(gameObject, out sourceObj); mesh = cachedMesh; if ( mesh.vertexCount != 0 ) SetMeshData(); } else { cachedMesh = FindMesh(gameObject, out sourceObj); mesh = MegaCopyObject.DupMesh(cachedMesh, ""); SetMesh(gameObject, mesh); if ( mesh.vertexCount != 0 ) SetMeshData(); } } } void SetMeshData() { bbox = cachedMesh.bounds; sverts = new Vector3[cachedMesh.vertexCount]; verts = cachedMesh.vertices; uvs = cachedMesh.uv; suvs = new Vector2[cachedMesh.uv.Length]; cols = cachedMesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); for ( int i = 0; i < mods.Length; i++ ) { if ( mods[i] != null ) { mods[i].SetModMesh(mesh); mods[i].ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } mapping = null; UpdateMesh = -1; } public void ModReset(MegaModifier m) { if ( m != null ) { m.SetModMesh(cachedMesh); BuildList(); } } // Check, do we need these? void Update() { GetMesh(false); if ( visible || InvisibleUpdate ) { if ( !DoLateUpdate ) ModifyObjectMT(); } } void LateUpdate() { if ( visible || InvisibleUpdate ) { if ( DoLateUpdate ) ModifyObjectMT(); } } void OnBecameVisible() { visible = true; } void OnBecameInvisible() { visible = false; } [ContextMenu("Reset")] public void Reset() { ResetMeshInfo(); } // Mesh related stuff [ContextMenu("Reset Mesh Info")] public void ResetMeshInfo() { if ( mods != null ) { if ( mods.Length > 0 ) { mesh.vertices = mods[0].verts; //_verts; // mesh.vertices = GetVerts(true); } mesh.uv = uvs; //GetUVs(true); if ( recalcnorms ) RecalcNormals(); if ( recalcbounds ) mesh.RecalculateBounds(); } #if false if ( cachedMesh == null ) cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); GetMeshData(false); mesh.vertices = verts; //_verts; // mesh.vertices = GetVerts(true); mesh.uv = uvs; //GetUVs(true); if ( recalcnorms ) RecalcNormals(); if ( recalcbounds ) mesh.RecalculateBounds(); #endif } #if false void Reset() { if ( cachedMesh == null ) cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); BuildList(); ReStart1(true); } #endif // Called by my scripts when the mesh has changed public void MeshUpdated() { GetMesh(true); //cachedMesh = (Mesh)Mesh.Instantiate(FindMesh(gameObject, out sourceObj)); //GetMeshData(true); foreach ( MegaModifier mod in mods ) // Added back in? mod.SetModMesh(cachedMesh); } // Replace mesh data with data from newmesh, called from scripts not used internally public void MeshChanged(Mesh newmesh) { if ( mesh ) { mesh.vertices = newmesh.vertices; mesh.normals = newmesh.normals; mesh.uv = newmesh.uv; #if UNITY_5_0 || UNITY_5_1 || UNITY_5 mesh.uv2 = newmesh.uv2; mesh.uv3 = newmesh.uv3; mesh.uv4 = newmesh.uv4; #else mesh.uv1 = newmesh.uv1; mesh.uv2 = newmesh.uv2; #endif mesh.colors = newmesh.colors; mesh.tangents = newmesh.tangents; mesh.subMeshCount = newmesh.subMeshCount; for ( int i = 0; i < newmesh.subMeshCount; i++ ) mesh.SetTriangles(newmesh.GetTriangles(i), i); bbox = newmesh.bounds; sverts = new Vector3[mesh.vertexCount]; verts = mesh.vertices; uvs = mesh.uv; suvs = new Vector2[mesh.uv.Length]; cols = mesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); foreach ( MegaModifier mod in mods ) { if ( mod != null ) { mod.SetModMesh(newmesh); mod.ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } mapping = null; UpdateMesh = -1; } } #if false public void GetMeshData(bool force) { if ( force || mesh == null ) mesh = FindMesh1(gameObject, out sourceObj); //Utils.GetMesh(gameObject); // Do we use mesh anymore if ( mesh != null ) // was mesh { bbox = cachedMesh.bounds; sverts = new Vector3[cachedMesh.vertexCount]; verts = cachedMesh.vertices; uvs = cachedMesh.uv; suvs = new Vector2[cachedMesh.uv.Length]; cols = cachedMesh.colors; //BuildNormalMapping(cachedMesh, false); mods = GetComponents<MegaModifier>(); Array.Sort(mods, CompareOrder); for ( int i = 0; i < mods.Length; i++ ) { if ( mods[i] != null ) mods[i].ModStart(this); // Some mods like push error if we dont do this, put in error check and disable } } UpdateMesh = -1; } #endif public void SetMesh(GameObject go, Mesh mesh) { if ( go ) { Transform[] trans = (Transform[])go.GetComponentsInChildren<Transform>(true); for ( int i = 0; i < trans.Length; i++ ) { MeshFilter mf = (MeshFilter)trans[i].GetComponent<MeshFilter>(); if ( mf ) { mf.sharedMesh = mesh; return; } SkinnedMeshRenderer skin = (SkinnedMeshRenderer)trans[i].GetComponent<SkinnedMeshRenderer>(); if ( skin ) { skin.sharedMesh = mesh; return; } } } } static public Mesh FindMesh(GameObject go, out GameObject obj) { if ( go ) { Transform[] trans = (Transform[])go.GetComponentsInChildren<Transform>(true); for ( int i = 0; i < trans.Length; i++ ) { MeshFilter mf = (MeshFilter)trans[i].GetComponent<MeshFilter>(); if ( mf ) { if ( mf.gameObject != go ) obj = mf.gameObject; else obj = null; return mf.sharedMesh; } SkinnedMeshRenderer skin = (SkinnedMeshRenderer)trans[i].GetComponent<SkinnedMeshRenderer>(); if ( skin ) { if ( skin.gameObject != go ) obj = skin.gameObject; else obj = null; return skin.sharedMesh; } } } obj = null; return null; } #if false public Mesh FindMesh1(GameObject go, out GameObject obj) { if ( go ) { MeshFilter[] filters = (MeshFilter[])go.GetComponentsInChildren<MeshFilter>(true); if ( filters.Length > 0 ) { if ( filters[0].gameObject != go ) obj = filters[0].gameObject; else obj = null; return filters[0].mesh; } SkinnedMeshRenderer[] skins = (SkinnedMeshRenderer[])go.GetComponentsInChildren<SkinnedMeshRenderer>(true); if ( skins.Length > 0 ) { if ( skins[0].gameObject != go ) obj = skins[0].gameObject; else obj = null; return skins[0].sharedMesh; } } obj = null; return null; } #endif #if false void RestoreMesh(GameObject go, Mesh mesh) { if ( go ) { MeshFilter[] filters = (MeshFilter[])go.GetComponentsInChildren<MeshFilter>(true); if ( filters.Length > 0 ) { filters[0].sharedMesh = (Mesh)Instantiate(mesh); return; } SkinnedMeshRenderer[] skins = (SkinnedMeshRenderer[])go.GetComponentsInChildren<SkinnedMeshRenderer>(true); if ( skins.Length > 0 ) { skins[0].sharedMesh = (Mesh)Instantiate(mesh); return; } } } #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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0 && pkgArray != null) { pkgArray.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle); } private static unsafe int QueryContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer); } private static int SetContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { internal SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new Interop.SspiCli.CredHandle(); } #if TRACE_VERBOSE public override string ToString() { return "0x" + _handle.ToString(); } #endif public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SEC_WINNT_AUTH_IDENTITY_W authdata, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle:{outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SCHANNEL_CRED authdata, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata); int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array. // Not threadsafe. IntPtr copiedPtr = authdata.paCred; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.paCred = certArrayPtr; } outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); } finally { authdata.paCred = copiedPtr; } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; if (target != null) { target.DangerousRelease(); } Target = null; return true; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract partial class SafeDeleteContext : DebugSafeHandle { #else internal abstract partial class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly byte[] s_dummyBytes = new byte[] { 0 }; protected SafeFreeCredentials _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}"); if (inSecBuffers == null) { NetEventSource.Info(null, $"inSecBuffers = (null)"); } else { NetEventSource.Info(null, $"inSecBuffers = {inSecBuffers}"); } } #endif if (outSecBuffer == null) { NetEventSource.Fail(null, "outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc); bool haveInSecurityBufferDescriptor = false; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); haveInSecurityBufferDescriptor = true; } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); haveInSecurityBufferDescriptor = true; } Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); Interop.SspiCli.SecBuffer[] inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (haveInSecurityBufferDescriptor) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } } Interop.SspiCli.SecBuffer[] outUnmanagedBuffer = new Interop.SspiCli.SecBuffer[1]; fixed (void* outUnmanagedBufferPtr = &outUnmanagedBuffer[0]) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr; outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size; outUnmanagedBuffer[0].BufferType = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero; } else { outUnmanagedBuffer[0].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } fixed (char* namePtr = targetName) { errorCode = MustRunInitializeSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[0].BufferType; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].pvBuffer, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecBufferDesc* inputBuffer, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, ref outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}"); if (inSecBuffers == null) { NetEventSource.Info(null, "inSecBuffers = (null)"); } else { NetEventSource.Info(null, $"inSecBuffers[] = (inSecBuffers)"); } } #endif if (outSecBuffer == null) { NetEventSource.Fail(null, "outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc); bool haveInSecurityBufferDescriptor = false; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); haveInSecurityBufferDescriptor = true; } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); haveInSecurityBufferDescriptor = true; } Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (haveInSecurityBufferDescriptor) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } } var outUnmanagedBuffer = new Interop.SspiCli.SecBuffer[1]; fixed (void* outUnmanagedBufferPtr = &outUnmanagedBuffer[0]) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size; outUnmanagedBuffer[0].BufferType = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero; } else { outUnmanagedBuffer[0].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null, inFlags, endianness, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshaling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[0].BufferType; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].pvBuffer, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, Interop.SspiCli.SecBufferDesc* inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, ref outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal static unsafe int CompleteAuthToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken"); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffers[] = {inSecBuffers}"); } if (inSecBuffers == null) { NetEventSource.Fail(null, "inSecBuffers == null"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType: {securityBuffer.type}"); #endif } } Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}"); return errorCode; } internal static unsafe int ApplyControlToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffers[] = length:{inSecBuffers.Length}"); } if (inSecBuffers == null) { NetEventSource.Fail(null, "inSecBuffers == null"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } // TODO: (#3114): Optimizations to remove the unnecesary allocation of a CredHandle, remove the AddRef // if refContext was previously null, refactor the code to unify CompleteAuthToken and ApplyControlToken. Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}"); return errorCode; } } internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext { internal SafeDeleteContext_SECURITY() : base() { } protected override bool ReleaseHandle() { if (this._EffectiveCredential != null) { this._EffectiveCredential.DangerousRelease(); } return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle); } private static unsafe int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS && contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).Bindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Input.Events; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Localisation; using osu.Game.Overlays.Music; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays { public class NowPlayingOverlay : OsuFocusedOverlayContainer, INamedOverlayComponent { public string IconTexture => "Icons/Hexacons/music"; public LocalisableString Title => NowPlayingStrings.HeaderTitle; public LocalisableString Description => NowPlayingStrings.HeaderDescription; private const float player_height = 130; private const float transition_length = 800; private const float progress_height = 10; private const float bottom_black_area_height = 55; private Drawable background; private ProgressBar progressBar; private IconButton prevButton; private IconButton playButton; private IconButton nextButton; private IconButton playlistButton; private SpriteText title, artist; private PlaylistOverlay playlist; private Container dragContainer; private Container playerContainer; protected override string PopInSampleName => "UI/now-playing-pop-in"; protected override string PopOutSampleName => "UI/now-playing-pop-out"; [Resolved] private MusicController musicController { get; set; } [Resolved] private Bindable<WorkingBeatmap> beatmap { get; set; } [Resolved] private OsuColour colours { get; set; } public NowPlayingOverlay() { Width = 400; Margin = new MarginPadding(10); } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { dragContainer = new DragContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { playerContainer = new Container { RelativeSizeAxes = Axes.X, Height = player_height, Masking = true, CornerRadius = 5, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }, Children = new[] { background = new Background(), title = new OsuSpriteText { Origin = Anchor.BottomCentre, Anchor = Anchor.TopCentre, Position = new Vector2(0, 40), Font = OsuFont.GetFont(size: 25, italics: true), Colour = Color4.White, Text = @"Nothing to play", }, artist = new OsuSpriteText { Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Position = new Vector2(0, 45), Font = OsuFont.GetFont(size: 15, weight: FontWeight.Bold, italics: true), Colour = Color4.White, Text = @"Nothing to play", }, new Container { Padding = new MarginPadding { Bottom = progress_height }, Height = bottom_black_area_height, RelativeSizeAxes = Axes.X, Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Children = new Drawable[] { new FillFlowContainer<IconButton> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(5), Origin = Anchor.Centre, Anchor = Anchor.Centre, Children = new[] { prevButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Action = () => musicController.PreviousTrack(), Icon = FontAwesome.Solid.StepBackward, }, playButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(1.4f), IconScale = new Vector2(1.4f), Action = () => musicController.TogglePause(), Icon = FontAwesome.Regular.PlayCircle, }, nextButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Action = () => musicController.NextTrack(), Icon = FontAwesome.Solid.StepForward, }, } }, playlistButton = new MusicIconButton { Origin = Anchor.Centre, Anchor = Anchor.CentreRight, Position = new Vector2(-bottom_black_area_height / 2, 0), Icon = FontAwesome.Solid.Bars, Action = togglePlaylist }, } }, progressBar = new HoverableProgressBar { Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Height = progress_height / 2, FillColour = colours.Yellow, BackgroundColour = colours.YellowDarker.Opacity(0.5f), OnSeek = musicController.SeekTo } }, }, } } }; } private void togglePlaylist() { if (playlist == null) { LoadComponentAsync(playlist = new PlaylistOverlay { RelativeSizeAxes = Axes.X, Y = player_height + 10, }, _ => { dragContainer.Add(playlist); playlist.BeatmapSets.BindTo(musicController.BeatmapSets); playlist.State.BindValueChanged(s => playlistButton.FadeColour(s.NewValue == Visibility.Visible ? colours.Yellow : Color4.White, 200, Easing.OutQuint), true); togglePlaylist(); }); return; } if (!beatmap.Disabled) playlist.ToggleVisibility(); } protected override void LoadComplete() { base.LoadComplete(); beatmap.BindDisabledChanged(beatmapDisabledChanged, true); musicController.TrackChanged += trackChanged; trackChanged(beatmap.Value); } protected override void PopIn() { base.PopIn(); this.FadeIn(transition_length, Easing.OutQuint); dragContainer.ScaleTo(1, transition_length, Easing.OutElastic); } protected override void PopOut() { base.PopOut(); this.FadeOut(transition_length, Easing.OutQuint); dragContainer.ScaleTo(0.9f, transition_length, Easing.OutQuint); } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); Height = dragContainer.Height; } protected override void Update() { base.Update(); if (pendingBeatmapSwitch != null) { pendingBeatmapSwitch(); pendingBeatmapSwitch = null; } var track = musicController.CurrentTrack; if (!track.IsDummyDevice) { progressBar.EndTime = track.Length; progressBar.CurrentTime = track.CurrentTime; playButton.Icon = track.IsRunning ? FontAwesome.Regular.PauseCircle : FontAwesome.Regular.PlayCircle; } else { progressBar.CurrentTime = 0; progressBar.EndTime = 1; playButton.Icon = FontAwesome.Regular.PlayCircle; } } private Action pendingBeatmapSwitch; private void trackChanged(WorkingBeatmap beatmap, TrackChangeDirection direction = TrackChangeDirection.None) { // avoid using scheduler as our scheduler may not be run for a long time, holding references to beatmaps. pendingBeatmapSwitch = delegate { // todo: this can likely be replaced with WorkingBeatmap.GetBeatmapAsync() Task.Run(() => { if (beatmap?.Beatmap == null) // this is not needed if a placeholder exists { title.Text = @"Nothing to play"; artist.Text = @"Nothing to play"; } else { BeatmapMetadata metadata = beatmap.Metadata; title.Text = new RomanisableString(metadata.TitleUnicode, metadata.Title); artist.Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist); } }); LoadComponentAsync(new Background(beatmap) { Depth = float.MaxValue }, newBackground => { switch (direction) { case TrackChangeDirection.Next: newBackground.Position = new Vector2(400, 0); newBackground.MoveToX(0, 500, Easing.OutCubic); background.MoveToX(-400, 500, Easing.OutCubic); break; case TrackChangeDirection.Prev: newBackground.Position = new Vector2(-400, 0); newBackground.MoveToX(0, 500, Easing.OutCubic); background.MoveToX(400, 500, Easing.OutCubic); break; } background.Expire(); background = newBackground; playerContainer.Add(newBackground); }); }; } private void beatmapDisabledChanged(bool disabled) { if (disabled) playlist?.Hide(); prevButton.Enabled.Value = !disabled; nextButton.Enabled.Value = !disabled; playlistButton.Enabled.Value = !disabled; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (musicController != null) musicController.TrackChanged -= trackChanged; } private class MusicIconButton : IconButton { public MusicIconButton() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(OsuColour colours) { HoverColour = colours.YellowDark.Opacity(0.6f); FlashColour = colours.Yellow; } protected override void LoadComplete() { base.LoadComplete(); // works with AutoSizeAxes above to make buttons autosize with the scale animation. Content.AutoSizeAxes = Axes.None; Content.Size = new Vector2(DEFAULT_BUTTON_SIZE); } } private class Background : BufferedContainer { private readonly Sprite sprite; private readonly WorkingBeatmap beatmap; public Background(WorkingBeatmap beatmap = null) { this.beatmap = beatmap; Depth = float.MaxValue; RelativeSizeAxes = Axes.Both; CacheDrawnFrameBuffer = true; Children = new Drawable[] { sprite = new Sprite { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(150), FillMode = FillMode.Fill, }, new Box { RelativeSizeAxes = Axes.X, Height = bottom_black_area_height, Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Colour = Color4.Black.Opacity(0.5f) } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { sprite.Texture = beatmap?.Background ?? textures.Get(@"Backgrounds/bg4"); } } private class DragContainer : Container { protected override bool OnDragStart(DragStartEvent e) { return true; } protected override void OnDrag(DragEvent e) { Vector2 change = e.MousePosition - e.MouseDownPosition; // Diminish the drag distance as we go further to simulate "rubber band" feeling. change *= change.Length <= 0 ? 0 : MathF.Pow(change.Length, 0.7f) / change.Length; this.MoveTo(change); } protected override void OnDragEnd(DragEndEvent e) { this.MoveTo(Vector2.Zero, 800, Easing.OutElastic); base.OnDragEnd(e); } } private class HoverableProgressBar : ProgressBar { public HoverableProgressBar() : base(true) { } protected override bool OnHover(HoverEvent e) { this.ResizeHeightTo(progress_height, 500, Easing.OutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { this.ResizeHeightTo(progress_height / 2, 500, Easing.OutQuint); base.OnHoverLost(e); } } } }
using System; using System.Threading.Tasks; using Xunit; using TinyPubSubLib; namespace TinyPubSub.Tests { // Dummy class for instance sending public class TestEventType { public int Sklep { get; set; } = 5; } // Dummy class for instance sending with inheritance public class InheritedTestEventType : TestEventType { public int MyOtherInt { get; set; } = 2; } public class PubSubTests { [Fact] public void SubscribeWithArgumentTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, (x) => testsuccessful = (x == "duck")); // Act TinyPubSubLib.TinyPubSub.Publish(channel, "duck"); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribeWithTypeTest() { // Arrange var testsuccessful = false; var tstType = new TestEventType(); var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe<TestEventType>(channel, (x) => testsuccessful = (x.Sklep == 5)); // Act TinyPubSubLib.TinyPubSub.Publish(channel, tstType); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribeWithEventArguments() { // Arrange var testsuccessful = 0; var tstType = new TestEventType(); var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe<TestEventType>(null, channel, (TestEventType x) => { testsuccessful = 3; }); TinyPubSubLib.TinyPubSub.Subscribe<TestEventType>(null, channel, (TestEventType x, TinyPubSubLib.TinyEventArgs evtargs) => { evtargs.HaltExecution = true; }); TinyPubSubLib.TinyPubSub.Subscribe<TestEventType>(null, channel, (TestEventType x) => { testsuccessful = 4; }); // Act var ret = TinyPubSubLib.TinyPubSub.PublishControlled(channel, tstType); // Assert Assert.True(testsuccessful == 3 && ret.Handled == true); } [Fact] public void SubscribeWithTypeInheritanceTest() { // Arrange var testsuccessful = false; var tstType = new InheritedTestEventType(); var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe<TestEventType>(channel, (x) => testsuccessful = (x.Sklep == 5)); // Act TinyPubSubLib.TinyPubSub.Publish<TestEventType>(channel, tstType); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribeWithArgumentMissingTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = true); // Act TinyPubSubLib.TinyPubSub.Publish(channel, "dumbargument"); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribeWithArgumentMissingButArgumentedSubscriptionTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, (x) => testsuccessful = (x == null)); // Act TinyPubSubLib.TinyPubSub.Publish(channel); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribePublishTheMostCommonWayTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = true); // Act TinyPubSubLib.TinyPubSub.Publish(channel); // Assert Assert.True(testsuccessful); } [Fact] public void SubscribePublishExceptionHandling() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); var subId = TinyPubSubLib.TinyPubSub.Subscribe(channel, () => throw new Exception("Error in handling")); TinyPubSubLib.TinyPubSub.Subscribe<TinyPubSubLib.TinyException>(TinyPubSubLib.TinyException.DefaultChannel, (msg) => testsuccessful = msg.SubscriptionTag == subId); // Act TinyPubSubLib.TinyPubSub.Publish(channel); // Assert Assert.True(testsuccessful); } [Fact] public async Task DelayedSubscribePublishTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = true); // Act TinyPubSubLib.TinyPubSub.PublishAsTask(channel); await Task.Delay(100); // Assert Assert.True(testsuccessful); } [Fact] public void DelayedSubscribePublishNotWaitingForCompletionTest() { // Arrange var testsuccessful = true; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = false); // Act TinyPubSubLib.TinyPubSub.PublishAsTask(channel); // Assert Assert.True(testsuccessful); } [Fact] public async Task DelayedSubscribePublishWithArgumentsTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, (x) => testsuccessful = x == "duck"); // Act TinyPubSubLib.TinyPubSub.PublishAsTask(channel, "duck"); await Task.Delay(100); // Assert Assert.True(testsuccessful); } [Fact] public async Task PublishAsyncTest() { // Arrange var testsuccessful = false; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = true); // Act await TinyPubSubLib.TinyPubSub.PublishAsync(channel); // Assert Assert.True(testsuccessful); } [Fact] public async Task PublishAsyncWithExceptionTest() { // Arrange var testsuccessful = true; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => throw new Exception()); // Act await TinyPubSubLib.TinyPubSub.PublishAsync(channel); // Assert Assert.True(testsuccessful); } [Fact] public async Task PublishWithOnErrorActionTest() { // Arrange var testsuccessful = true; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => throw new Exception("Boom")); // Act await TinyPubSubLib.TinyPubSub.PublishAsync(channel, onError: (ex, s) => testsuccessful = ex.Message == "Boom"); // Assert Assert.True(testsuccessful); } [Fact] public void PublishWithEventArgsTest() { // Arrange var testsuccessful = true; var channel = Guid.NewGuid().ToString(); TinyPubSubLib.TinyPubSub.Subscribe(channel, (string argument, TinyEventArgs args) => args.HaltExecution = true); TinyPubSubLib.TinyPubSub.Subscribe(channel, () => testsuccessful = false); // This subscription should never be called // Act TinyPubSubLib.TinyPubSub.PublishControlled(channel); // Assert Assert.True(testsuccessful); } } }
using System.Collections.Generic; using System.IO; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Search.Payloads { /* * 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 IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery; using SpanOrQuery = Lucene.Net.Search.Spans.SpanOrQuery; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using Spans = Lucene.Net.Search.Spans.Spans; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; /// <summary> /// Experimental class to get set of payloads for most standard Lucene queries. /// Operates like Highlighter - <see cref="Index.IndexReader"/> should only contain doc of interest, /// best to use MemoryIndex. /// <para/> /// @lucene.experimental /// </summary> public class PayloadSpanUtil { private readonly IndexReaderContext context; // LUCENENET: marked readonly /// <param name="context"> /// that contains doc with payloads to extract /// </param> /// <seealso cref="Index.IndexReader.Context"/> public PayloadSpanUtil(IndexReaderContext context) { this.context = context; } /// <summary> /// Query should be rewritten for wild/fuzzy support. /// </summary> /// <param name="query"> rewritten query </param> /// <returns> payloads Collection </returns> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public virtual ICollection<byte[]> GetPayloadsForQuery(Query query) { var payloads = new List<byte[]>(); QueryToSpanQuery(query, payloads); return payloads; } private void QueryToSpanQuery(Query query, ICollection<byte[]> payloads) { if (query is BooleanQuery booleanQuery) { BooleanClause[] queryClauses = booleanQuery.GetClauses(); for (int i = 0; i < queryClauses.Length; i++) { if (!queryClauses[i].IsProhibited) { QueryToSpanQuery(queryClauses[i].Query, payloads); } } } else if (query is PhraseQuery phraseQuery) { Term[] phraseQueryTerms = phraseQuery.GetTerms(); SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.Length]; for (int i = 0; i < phraseQueryTerms.Length; i++) { clauses[i] = new SpanTermQuery(phraseQueryTerms[i]); } int slop = phraseQuery.Slop; bool inorder = false; if (slop == 0) { inorder = true; } SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder) { Boost = query.Boost }; GetPayloads(payloads, sp); } else if (query is TermQuery termQuery) { SpanTermQuery stq = new SpanTermQuery(termQuery.Term) { Boost = query.Boost }; GetPayloads(payloads, stq); } else if (query is SpanQuery spanQuery) { GetPayloads(payloads, spanQuery); } else if (query is FilteredQuery filteredQuery) { QueryToSpanQuery(filteredQuery.Query, payloads); } else if (query is DisjunctionMaxQuery disjunctionMaxQuery) { foreach (var q in disjunctionMaxQuery) { QueryToSpanQuery(q, payloads); } } else if (query is MultiPhraseQuery mpq) { IList<Term[]> termArrays = mpq.GetTermArrays(); int[] positions = mpq.GetPositions(); if (positions.Length > 0) { int maxPosition = positions[positions.Length - 1]; for (int i = 0; i < positions.Length - 1; ++i) { if (positions[i] > maxPosition) { maxPosition = positions[i]; } } // LUCENENET: Changed from Query to SpanQuery to eliminate the O(n) cast // required to instantiate SpanOrQuery below IList<SpanQuery>[] disjunctLists = new List<SpanQuery>[maxPosition + 1]; int distinctPositions = 0; for (int i = 0; i < termArrays.Count; ++i) { Term[] termArray = termArrays[i]; IList<SpanQuery> disjuncts = disjunctLists[positions[i]]; // LUCENENET: Changed from Query to SpanQuery if (disjuncts == null) { disjuncts = (disjunctLists[positions[i]] = new List<SpanQuery>(termArray.Length)); // LUCENENET: Changed from Query to SpanQuery ++distinctPositions; } foreach (Term term in termArray) { disjuncts.Add(new SpanTermQuery(term)); } } int positionGaps = 0; int position = 0; SpanQuery[] clauses = new SpanQuery[distinctPositions]; for (int i = 0; i < disjunctLists.Length; ++i) { IList<SpanQuery> disjuncts = disjunctLists[i]; // LUCENENET: Changed from Query to SpanQuery if (disjuncts != null) { clauses[position++] = new SpanOrQuery(disjuncts); } else { ++positionGaps; } } int slop = mpq.Slop; bool inorder = (slop == 0); SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder); sp.Boost = query.Boost; GetPayloads(payloads, sp); } } } private void GetPayloads(ICollection<byte[]> payloads, SpanQuery query) { IDictionary<Term, TermContext> termContexts = new Dictionary<Term, TermContext>(); var terms = new JCG.SortedSet<Term>(); query.ExtractTerms(terms); foreach (Term term in terms) { termContexts[term] = TermContext.Build(context, term); } foreach (AtomicReaderContext atomicReaderContext in context.Leaves) { Spans spans = query.GetSpans(atomicReaderContext, atomicReaderContext.AtomicReader.LiveDocs, termContexts); while (spans.MoveNext() == true) { if (spans.IsPayloadAvailable) { var payload = spans.GetPayload(); foreach (var bytes in payload) { payloads.Add(bytes); } } } } } } }
using UnityEngine; using UnityEngine.PostProcessing; using System; using System.Collections.Generic; namespace UnityEditor.PostProcessing { using Settings = ColorGradingModel.Settings; using Tonemapper = ColorGradingModel.Tonemapper; using ColorWheelMode = ColorGradingModel.ColorWheelMode; [PostProcessingModelEditor(typeof(ColorGradingModel))] public class ColorGradingModelEditor : PostProcessingModelEditor { static GUIContent[] s_Tonemappers = { new GUIContent("None"), new GUIContent("Filmic (ACES)"), new GUIContent("Neutral") }; struct TonemappingSettings { public SerializedProperty tonemapper; public SerializedProperty neutralBlackIn; public SerializedProperty neutralWhiteIn; public SerializedProperty neutralBlackOut; public SerializedProperty neutralWhiteOut; public SerializedProperty neutralWhiteLevel; public SerializedProperty neutralWhiteClip; } struct BasicSettings { public SerializedProperty exposure; public SerializedProperty temperature; public SerializedProperty tint; public SerializedProperty hueShift; public SerializedProperty saturation; public SerializedProperty contrast; } struct ChannelMixerSettings { public SerializedProperty[] channels; public SerializedProperty currentEditingChannel; } struct ColorWheelsSettings { public SerializedProperty mode; public SerializedProperty log; public SerializedProperty linear; } static GUIContent[] s_Curves = { new GUIContent("YRGB"), new GUIContent("Hue VS Hue"), new GUIContent("Hue VS Sat"), new GUIContent("Sat VS Sat"), new GUIContent("Lum VS Sat") }; struct CurvesSettings { public SerializedProperty master; public SerializedProperty red; public SerializedProperty green; public SerializedProperty blue; public SerializedProperty hueVShue; public SerializedProperty hueVSsat; public SerializedProperty satVSsat; public SerializedProperty lumVSsat; public SerializedProperty currentEditingCurve; public SerializedProperty curveY; public SerializedProperty curveR; public SerializedProperty curveG; public SerializedProperty curveB; } TonemappingSettings m_Tonemapping; BasicSettings m_Basic; ChannelMixerSettings m_ChannelMixer; ColorWheelsSettings m_ColorWheels; CurvesSettings m_Curves; CurveEditor m_CurveEditor; Dictionary<SerializedProperty, Color> m_CurveDict; // Neutral tonemapping curve helper const int k_CurveResolution = 24; const float k_NeutralRangeX = 2f; const float k_NeutralRangeY = 1f; Vector3[] m_RectVertices = new Vector3[4]; Vector3[] m_LineVertices = new Vector3[2]; Vector3[] m_CurveVertices = new Vector3[k_CurveResolution]; Rect m_NeutralCurveRect; public override void OnEnable() { // Tonemapping settings m_Tonemapping = new TonemappingSettings { tonemapper = FindSetting((Settings x) => x.tonemapping.tonemapper), neutralBlackIn = FindSetting((Settings x) => x.tonemapping.neutralBlackIn), neutralWhiteIn = FindSetting((Settings x) => x.tonemapping.neutralWhiteIn), neutralBlackOut = FindSetting((Settings x) => x.tonemapping.neutralBlackOut), neutralWhiteOut = FindSetting((Settings x) => x.tonemapping.neutralWhiteOut), neutralWhiteLevel = FindSetting((Settings x) => x.tonemapping.neutralWhiteLevel), neutralWhiteClip = FindSetting((Settings x) => x.tonemapping.neutralWhiteClip) }; // Basic settings m_Basic = new BasicSettings { exposure = FindSetting((Settings x) => x.basic.postExposure), temperature = FindSetting((Settings x) => x.basic.temperature), tint = FindSetting((Settings x) => x.basic.tint), hueShift = FindSetting((Settings x) => x.basic.hueShift), saturation = FindSetting((Settings x) => x.basic.saturation), contrast = FindSetting((Settings x) => x.basic.contrast) }; // Channel mixer m_ChannelMixer = new ChannelMixerSettings { channels = new[] { FindSetting((Settings x) => x.channelMixer.red), FindSetting((Settings x) => x.channelMixer.green), FindSetting((Settings x) => x.channelMixer.blue) }, currentEditingChannel = FindSetting((Settings x) => x.channelMixer.currentEditingChannel) }; // Color wheels m_ColorWheels = new ColorWheelsSettings { mode = FindSetting((Settings x) => x.colorWheels.mode), log = FindSetting((Settings x) => x.colorWheels.log), linear = FindSetting((Settings x) => x.colorWheels.linear) }; // Curves m_Curves = new CurvesSettings { master = FindSetting((Settings x) => x.curves.master.curve), red = FindSetting((Settings x) => x.curves.red.curve), green = FindSetting((Settings x) => x.curves.green.curve), blue = FindSetting((Settings x) => x.curves.blue.curve), hueVShue = FindSetting((Settings x) => x.curves.hueVShue.curve), hueVSsat = FindSetting((Settings x) => x.curves.hueVSsat.curve), satVSsat = FindSetting((Settings x) => x.curves.satVSsat.curve), lumVSsat = FindSetting((Settings x) => x.curves.lumVSsat.curve), currentEditingCurve = FindSetting((Settings x) => x.curves.e_CurrentEditingCurve), curveY = FindSetting((Settings x) => x.curves.e_CurveY), curveR = FindSetting((Settings x) => x.curves.e_CurveR), curveG = FindSetting((Settings x) => x.curves.e_CurveG), curveB = FindSetting((Settings x) => x.curves.e_CurveB) }; // Prepare the curve editor and extract curve display settings m_CurveDict = new Dictionary<SerializedProperty, Color>(); var settings = CurveEditor.Settings.defaultSettings; m_CurveEditor = new CurveEditor(settings); AddCurve(m_Curves.master, new Color(1f, 1f, 1f), 2, false); AddCurve(m_Curves.red, new Color(1f, 0f, 0f), 2, false); AddCurve(m_Curves.green, new Color(0f, 1f, 0f), 2, false); AddCurve(m_Curves.blue, new Color(0f, 0.5f, 1f), 2, false); AddCurve(m_Curves.hueVShue, new Color(1f, 1f, 1f), 0, true); AddCurve(m_Curves.hueVSsat, new Color(1f, 1f, 1f), 0, true); AddCurve(m_Curves.satVSsat, new Color(1f, 1f, 1f), 0, false); AddCurve(m_Curves.lumVSsat, new Color(1f, 1f, 1f), 0, false); } void AddCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop) { var state = CurveEditor.CurveState.defaultState; state.color = color; state.visible = false; state.minPointCount = minPointCount; state.onlyShowHandlesOnSelection = true; state.zeroKeyConstantValue = 0.5f; state.loopInBounds = loop; m_CurveEditor.Add(prop, state); m_CurveDict.Add(prop, color); } public override void OnDisable() { m_CurveEditor.RemoveAll(); } public override void OnInspectorGUI() { DoGUIFor("Tonemapping", DoTonemappingGUI); EditorGUILayout.Space(); DoGUIFor("Basic", DoBasicGUI); EditorGUILayout.Space(); DoGUIFor("Channel Mixer", DoChannelMixerGUI); EditorGUILayout.Space(); DoGUIFor("Trackballs", DoColorWheelsGUI); EditorGUILayout.Space(); DoGUIFor("Grading Curves", DoCurvesGUI); } void DoGUIFor(string title, Action func) { EditorGUILayout.LabelField(title, EditorStyles.boldLabel); EditorGUI.indentLevel++; func(); EditorGUI.indentLevel--; } void DoTonemappingGUI() { int tid = EditorGUILayout.Popup(EditorGUIHelper.GetContent("Tonemapper"), m_Tonemapping.tonemapper.intValue, s_Tonemappers); if (tid == (int)Tonemapper.Neutral) { DrawNeutralTonemappingCurve(); EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackIn, EditorGUIHelper.GetContent("Black In")); EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteIn, EditorGUIHelper.GetContent("White In")); EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackOut, EditorGUIHelper.GetContent("Black Out")); EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteOut, EditorGUIHelper.GetContent("White Out")); EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteLevel, EditorGUIHelper.GetContent("White Level")); EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteClip, EditorGUIHelper.GetContent("White Clip")); } m_Tonemapping.tonemapper.intValue = tid; } void DrawNeutralTonemappingCurve() { using (new GUILayout.HorizontalScope()) { GUILayout.Space(EditorGUI.indentLevel * 15f); m_NeutralCurveRect = GUILayoutUtility.GetRect(128, 80); } // Background m_RectVertices[0] = PointInRect( 0f, 0f); m_RectVertices[1] = PointInRect(k_NeutralRangeX, 0f); m_RectVertices[2] = PointInRect(k_NeutralRangeX, k_NeutralRangeY); m_RectVertices[3] = PointInRect( 0f, k_NeutralRangeY); Handles.DrawSolidRectangleWithOutline( m_RectVertices, Color.white * 0.1f, Color.white * 0.4f ); // Horizontal lines for (var i = 1; i < k_NeutralRangeY; i++) DrawLine(0, i, k_NeutralRangeX, i, 0.4f); // Vertical lines for (var i = 1; i < k_NeutralRangeX; i++) DrawLine(i, 0, i, k_NeutralRangeY, 0.4f); // Label Handles.Label( PointInRect(0, k_NeutralRangeY) + Vector3.right, "Neutral Tonemapper", EditorStyles.miniLabel ); // Precompute some values var tonemap = ((ColorGradingModel)target).settings.tonemapping; const float scaleFactor = 20f; const float scaleFactorHalf = scaleFactor * 0.5f; float inBlack = tonemap.neutralBlackIn * scaleFactor + 1f; float outBlack = tonemap.neutralBlackOut * scaleFactorHalf + 1f; float inWhite = tonemap.neutralWhiteIn / scaleFactor; float outWhite = 1f - tonemap.neutralWhiteOut / scaleFactor; float blackRatio = inBlack / outBlack; float whiteRatio = inWhite / outWhite; const float a = 0.2f; float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio)); float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio); float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio)); const float e = 0.02f; const float f = 0.30f; float whiteLevel = tonemap.neutralWhiteLevel; float whiteClip = tonemap.neutralWhiteClip / scaleFactorHalf; // Tonemapping curve var vcount = 0; while (vcount < k_CurveResolution) { float x = k_NeutralRangeX * vcount / (k_CurveResolution - 1); float y = NeutralTonemap(x, a, b, c, d, e, f, whiteLevel, whiteClip); if (y < k_NeutralRangeY) { m_CurveVertices[vcount++] = PointInRect(x, y); } else { if (vcount > 1) { // Extend the last segment to the top edge of the rect. var v1 = m_CurveVertices[vcount - 2]; var v2 = m_CurveVertices[vcount - 1]; var clip = (m_NeutralCurveRect.y - v1.y) / (v2.y - v1.y); m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip; } break; } } if (vcount > 1) { Handles.color = Color.white * 0.9f; Handles.DrawAAPolyLine(2.0f, vcount, m_CurveVertices); } } void DrawLine(float x1, float y1, float x2, float y2, float grayscale) { m_LineVertices[0] = PointInRect(x1, y1); m_LineVertices[1] = PointInRect(x2, y2); Handles.color = Color.white * grayscale; Handles.DrawAAPolyLine(2f, m_LineVertices); } Vector3 PointInRect(float x, float y) { x = Mathf.Lerp(m_NeutralCurveRect.x, m_NeutralCurveRect.xMax, x / k_NeutralRangeX); y = Mathf.Lerp(m_NeutralCurveRect.yMax, m_NeutralCurveRect.y, y / k_NeutralRangeY); return new Vector3(x, y, 0); } float NeutralCurve(float x, float a, float b, float c, float d, float e, float f) { return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f; } float NeutralTonemap(float x, float a, float b, float c, float d, float e, float f, float whiteLevel, float whiteClip) { x = Mathf.Max(0f, x); // Tonemap float whiteScale = 1f / NeutralCurve(whiteLevel, a, b, c, d, e, f); x = NeutralCurve(x * whiteScale, a, b, c, d, e, f); x *= whiteScale; // Post-curve white point adjustment x /= whiteClip; return x; } void DoBasicGUI() { EditorGUILayout.PropertyField(m_Basic.exposure, EditorGUIHelper.GetContent("Post Exposure (EV)")); EditorGUILayout.PropertyField(m_Basic.temperature); EditorGUILayout.PropertyField(m_Basic.tint); EditorGUILayout.PropertyField(m_Basic.hueShift); EditorGUILayout.PropertyField(m_Basic.saturation); EditorGUILayout.PropertyField(m_Basic.contrast); } void DoChannelMixerGUI() { int currentChannel = m_ChannelMixer.currentEditingChannel.intValue; EditorGUI.BeginChangeCheck(); { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel("Channel"); if (GUILayout.Toggle(currentChannel == 0, EditorGUIHelper.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0; if (GUILayout.Toggle(currentChannel == 1, EditorGUIHelper.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1; if (GUILayout.Toggle(currentChannel == 2, EditorGUIHelper.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2; } } if (EditorGUI.EndChangeCheck()) { GUI.FocusControl(null); } var serializedChannel = m_ChannelMixer.channels[currentChannel]; m_ChannelMixer.currentEditingChannel.intValue = currentChannel; var v = serializedChannel.vector3Value; v.x = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Red|Modify influence of the red channel within the overall mix."), v.x, -2f, 2f); v.y = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Green|Modify influence of the green channel within the overall mix."), v.y, -2f, 2f); v.z = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Blue|Modify influence of the blue channel within the overall mix."), v.z, -2f, 2f); serializedChannel.vector3Value = v; } void DoColorWheelsGUI() { int wheelMode = m_ColorWheels.mode.intValue; using (new EditorGUILayout.HorizontalScope()) { GUILayout.Space(15); if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Linear, "Linear", EditorStyles.miniButtonLeft)) wheelMode = (int)ColorWheelMode.Linear; if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Log, "Log", EditorStyles.miniButtonRight)) wheelMode = (int)ColorWheelMode.Log; } m_ColorWheels.mode.intValue = wheelMode; EditorGUILayout.Space(); if (wheelMode == (int)ColorWheelMode.Linear) { EditorGUILayout.PropertyField(m_ColorWheels.linear); WheelSetTitle(GUILayoutUtility.GetLastRect(), "Linear Controls"); } else if (wheelMode == (int)ColorWheelMode.Log) { EditorGUILayout.PropertyField(m_ColorWheels.log); WheelSetTitle(GUILayoutUtility.GetLastRect(), "Log Controls"); } } static void WheelSetTitle(Rect position, string label) { var matrix = GUI.matrix; var rect = new Rect(position.x - 10f, position.y, TrackballGroupDrawer.m_Size, TrackballGroupDrawer.m_Size); GUIUtility.RotateAroundPivot(-90f, rect.center); GUI.Label(rect, label, FxStyles.centeredMiniLabel); GUI.matrix = matrix; } void ResetVisibleCurves() { foreach (var curve in m_CurveDict) { var state = m_CurveEditor.GetCurveState(curve.Key); state.visible = false; m_CurveEditor.SetCurveState(curve.Key, state); } } void SetCurveVisible(SerializedProperty prop) { var state = m_CurveEditor.GetCurveState(prop); state.visible = true; m_CurveEditor.SetCurveState(prop, state); } bool SpecialToggle(bool value, string name, out bool rightClicked) { var rect = GUILayoutUtility.GetRect(EditorGUIHelper.GetContent(name), EditorStyles.toolbarButton); var e = Event.current; rightClicked = (e.type == EventType.MouseUp && rect.Contains(e.mousePosition) && e.button == 1); return GUI.Toggle(rect, value, name, EditorStyles.toolbarButton); } static Material s_MaterialSpline; void DoCurvesGUI() { EditorGUILayout.Space(); EditorGUI.indentLevel -= 2; ResetVisibleCurves(); using (new EditorGUI.DisabledGroupScope(serializedProperty.serializedObject.isEditingMultipleObjects)) { int curveEditingId = 0; // Top toolbar using (new GUILayout.HorizontalScope(EditorStyles.toolbar)) { curveEditingId = EditorGUILayout.Popup(m_Curves.currentEditingCurve.intValue, s_Curves, EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f)); bool y = false, r = false, g = false, b = false; if (curveEditingId == 0) { EditorGUILayout.Space(); bool rightClickedY, rightClickedR, rightClickedG, rightClickedB; y = SpecialToggle(m_Curves.curveY.boolValue, "Y", out rightClickedY); r = SpecialToggle(m_Curves.curveR.boolValue, "R", out rightClickedR); g = SpecialToggle(m_Curves.curveG.boolValue, "G", out rightClickedG); b = SpecialToggle(m_Curves.curveB.boolValue, "B", out rightClickedB); if (!y && !r && !g && !b) { r = g = b = false; y = true; } if (rightClickedY || rightClickedR || rightClickedG || rightClickedB) { y = rightClickedY; r = rightClickedR; g = rightClickedG; b = rightClickedB; } if (y) SetCurveVisible(m_Curves.master); if (r) SetCurveVisible(m_Curves.red); if (g) SetCurveVisible(m_Curves.green); if (b) SetCurveVisible(m_Curves.blue); m_Curves.curveY.boolValue = y; m_Curves.curveR.boolValue = r; m_Curves.curveG.boolValue = g; m_Curves.curveB.boolValue = b; } else { switch (curveEditingId) { case 1: SetCurveVisible(m_Curves.hueVShue); break; case 2: SetCurveVisible(m_Curves.hueVSsat); break; case 3: SetCurveVisible(m_Curves.satVSsat); break; case 4: SetCurveVisible(m_Curves.lumVSsat); break; } } GUILayout.FlexibleSpace(); if (GUILayout.Button("Reset", EditorStyles.toolbarButton)) { switch (curveEditingId) { case 0: if (y) m_Curves.master.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); if (r) m_Curves.red.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); if (g) m_Curves.green.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); if (b) m_Curves.blue.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case 1: m_Curves.hueVShue.animationCurveValue = new AnimationCurve(); break; case 2: m_Curves.hueVSsat.animationCurveValue = new AnimationCurve(); break; case 3: m_Curves.satVSsat.animationCurveValue = new AnimationCurve(); break; case 4: m_Curves.lumVSsat.animationCurveValue = new AnimationCurve(); break; } } m_Curves.currentEditingCurve.intValue = curveEditingId; } // Curve area var settings = m_CurveEditor.settings; var rect = GUILayoutUtility.GetAspectRect(2f); var innerRect = settings.padding.Remove(rect); if (Event.current.type == EventType.Repaint) { // Background EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f)); if (s_MaterialSpline == null) s_MaterialSpline = new Material(Shader.Find("Hidden/Post FX/UI/Curve Background")) { hideFlags = HideFlags.HideAndDontSave }; if (curveEditingId == 1 || curveEditingId == 2) DrawBackgroundTexture(innerRect, 0); else if (curveEditingId == 3 || curveEditingId == 4) DrawBackgroundTexture(innerRect, 1); // Bounds Handles.color = Color.white; Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f)); // Grid setup Handles.color = new Color(1f, 1f, 1f, 0.05f); int hLines = (int)Mathf.Sqrt(innerRect.width); int vLines = (int)(hLines / (innerRect.width / innerRect.height)); // Vertical grid int gridOffset = Mathf.FloorToInt(innerRect.width / hLines); int gridPadding = ((int)(innerRect.width) % hLines) / 2; for (int i = 1; i < hLines; i++) { var offset = i * Vector2.right * gridOffset; offset.x += gridPadding; Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset); } // Horizontal grid gridOffset = Mathf.FloorToInt(innerRect.height / vLines); gridPadding = ((int)(innerRect.height) % vLines) / 2; for (int i = 1; i < vLines; i++) { var offset = i * Vector2.up * gridOffset; offset.y += gridPadding; Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset); } } // Curve editor if (m_CurveEditor.OnGUI(rect)) { Repaint(); GUI.changed = true; } if (Event.current.type == EventType.Repaint) { // Borders Handles.color = Color.black; Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f)); Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax)); Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax)); Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f)); // Selection info var selection = m_CurveEditor.GetSelection(); if (selection.curve != null && selection.keyframeIndex > -1) { var key = selection.keyframe.Value; var infoRect = innerRect; infoRect.x += 5f; infoRect.width = 100f; infoRect.height = 30f; GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), FxStyles.preLabel); } } } /* EditorGUILayout.HelpBox( @"Curve editor cheat sheet: - [Del] or [Backspace] to remove a key - [Ctrl] to break a tangent handle - [Shift] to align tangent handles - [Double click] to create a key on the curve(s) at mouse position - [Alt] + [Double click] to create a key on the curve(s) at a given time", MessageType.Info); */ EditorGUILayout.Space(); EditorGUI.indentLevel += 2; } void DrawBackgroundTexture(Rect rect, int pass) { float scale = EditorGUIUtility.pixelsPerPoint; var oldRt = RenderTexture.active; var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); s_MaterialSpline.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f); s_MaterialSpline.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint); Graphics.Blit(null, rt, s_MaterialSpline, pass); RenderTexture.active = oldRt; GUI.DrawTexture(rect, rt); RenderTexture.ReleaseTemporary(rt); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Collections.ObjectModel { public class ReadOnlyCollection<T> : IList<T>, ICollection<T>, IEnumerable<T>, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { /// <summary> /// Implementation of ICollection.get_Count /// </summary> public extern virtual int Count { get; } // Summary: // Initializes a new instance of the System.Collections.ObjectModel.ReadOnlyCollection<T> // class that is a read-only wrapper around the specified list. // // Parameters: // list: // The list to wrap. // // Exceptions: // System.ArgumentNullException: // list is null. public ReadOnlyCollection(IList<T> list) { Contract.Requires(list != null); Contract.Ensures(Count == list.Count); } // // Summary: // Returns the System.Collections.Generic.IList<T> that the System.Collections.ObjectModel.ReadOnlyCollection<T> // wraps. // // Returns: // The System.Collections.Generic.IList<T> that the System.Collections.ObjectModel.ReadOnlyCollection<T> // wraps. protected IList<T> Items { get { Contract.Ensures(Contract.Result<IList<T>>() != null); return default(IList<T>); } } // Summary: // Gets the element at the specified index. // // Parameters: // index: // The zero-based index of the element to get. // // Returns: // The element at the specified index. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than zero. -or- index is equal to or greater than System.Collections.ObjectModel.ReadOnlyCollection<T>.Count. #if SILVERLIGHT_5_0 || NETFRAMEWORK_4_5 virtual #endif public T this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < this.Count); return default(T); } } #region IList<T> Members T System.Collections.Generic.IList<T>.this[int index] { get { return default(T); } set { } } public int IndexOf(T item) { throw new NotImplementedException(); } void System.Collections.Generic.IList<T>.Insert(int index, T item) { throw new NotImplementedException(); } void System.Collections.Generic.IList<T>.RemoveAt(int index) { throw new NotImplementedException(); } #endregion #region ICollection<T> Members bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw new NotImplementedException(); } } void System.Collections.Generic.ICollection<T>.Add(T item) { throw new NotImplementedException(); } void System.Collections.Generic.ICollection<T>.Clear() { throw new NotImplementedException(); } [Pure] public bool Contains(T item) { throw new NotImplementedException(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } bool System.Collections.Generic.ICollection<T>.Remove(T item) { throw new NotImplementedException(); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } [ContractModel] public object[] Model { [ContractRuntimeIgnored] get { throw new NotImplementedException(); } } #endregion #region IEnumerable Members [ContractModel] object[] IEnumerable.Model { [ContractRuntimeIgnored] get { throw new NotImplementedException(); } } #endregion #region IList Members bool System.Collections.IList.IsFixedSize { get { throw new NotImplementedException(); } } bool System.Collections.IList.IsReadOnly { get { throw new NotImplementedException(); } } object System.Collections.IList.this[int index] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } int System.Collections.IList.Add(object value) { throw new NotImplementedException(); } void System.Collections.IList.Clear() { throw new NotImplementedException(); } bool System.Collections.IList.Contains(object value) { throw new NotImplementedException(); } int System.Collections.IList.IndexOf(object value) { throw new NotImplementedException(); } void System.Collections.IList.Insert(int index, object value) { throw new NotImplementedException(); } void System.Collections.IList.Remove(object value) { throw new NotImplementedException(); } void System.Collections.IList.RemoveAt(int index) { throw new NotImplementedException(); } #endregion #region ICollection Members bool System.Collections.ICollection.IsSynchronized { get { throw new NotImplementedException(); } } object System.Collections.ICollection.SyncRoot { get { throw new NotImplementedException(); } } void System.Collections.ICollection.CopyTo(Array array, int index) { throw new NotImplementedException(); } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using IR = Microsoft.Zelig.CodeGeneration.IR; public sealed class ContainerVisualItem : VisualItem { // // State // private List< VisualItem > m_children; private bool m_boundsValid; // // Constructor Methods // public ContainerVisualItem( object context ) : base( context ) { m_children = new List< VisualItem >(); } // // Helper Methods // public override void CollectDepths( GrowOnlySet< int > set ) { set.Insert( m_depth ); foreach(VisualItem child in m_children) { child.CollectDepths( set ); } } public override bool Draw( GraphicsContext ctx , PointF absoluteOrigin , int depth ) { bool isVisible = base.Draw( ctx, absoluteOrigin, depth ); if(isVisible) { absoluteOrigin.X += m_relativeOrigin.X; absoluteOrigin.Y += m_relativeOrigin.Y; foreach(VisualItem child in m_children) { child.Draw( ctx, absoluteOrigin, depth ); } } return isVisible; } public override VisualItem Contains( PointF pt , bool fLeafOnly , out PointF relHitPt ) { if(base.Contains( pt, fLeafOnly, out relHitPt ) != null) { pt.X -= m_relativeOrigin.X; pt.Y -= m_relativeOrigin.Y; foreach(VisualItem child in m_children) { VisualItem hit = child.Contains( pt, fLeafOnly, out relHitPt ); if(hit != null) { return hit; } } if(fLeafOnly == false) { return this; } } return null; } public override VisualItem ContainsVertically( float y , out float relHitY ) { if(base.ContainsVertically( y, out relHitY ) != null) { y -= m_relativeOrigin.Y; foreach(VisualItem child in m_children) { VisualItem hit = child.ContainsVertically( y, out relHitY ); if(hit != null) { return hit; } } } return null; } public override VisualItem FindMatch( object o ) { foreach(VisualItem child in m_children) { VisualItem match = child.FindMatch( o ); if(match != null) { return match; } } return null; } public override bool EnumerateTree( CodeView.EnumerationCallback dlg ) { if(base.EnumerateTree( dlg ) == false) { foreach(VisualItem child in m_children) { if(child.EnumerateTree( dlg )) { return true; } } } return false; } //--// public override void InvalidateBounds() { m_boundsValid = false; base.InvalidateBounds(); } public void InsertAt( VisualItem itemNew , int pos ) { m_children.Insert( pos, itemNew ); itemNew.Parent = this; InvalidateBounds(); } public void Add( VisualItem item ) { m_children.Add( item ); item.Parent = this; InvalidateBounds(); } public void Remove( VisualItem item ) { m_children.Remove( item ); item.Parent = null; InvalidateBounds(); } public void Clear() { m_children.Clear(); InvalidateBounds(); } public void ExpandVerticalSpaceAfter( VisualItem item , VisualItem newItem ) { RectangleF newBounds = newItem.RelativeBounds; RectangleF bounds = item .RelativeBounds; bounds.Offset( item.RelativeOrigin ); newItem.RelativeOrigin = new PointF( bounds.X, bounds.Bottom ); foreach(VisualItem child in m_children) { PointF childPos = child.RelativeOrigin; if(childPos.Y > item.RelativeOrigin.Y) { childPos.Y += newBounds.Height; child.RelativeOrigin = childPos; } } Add( newItem ); } internal void RemoveVerticalSpace( VisualItem item ) { RectangleF bounds = item.RelativeBounds; bounds.Offset( item.RelativeOrigin ); foreach(VisualItem child in m_children) { PointF childPos = child.RelativeOrigin; if(childPos.Y > item.RelativeOrigin.Y) { childPos.Y -= bounds.Height; child.RelativeOrigin = childPos; } } Remove( item ); } // // Access Methods // public override RectangleF RelativeBounds { get { if(m_boundsValid == false) { bool fFirst = true; m_relativeBounds = new RectangleF(); foreach(VisualItem child in m_children) { RectangleF childBounds = child.RelativeBounds; childBounds.Offset( child.RelativeOrigin ); if(fFirst) { fFirst = false; m_relativeBounds = childBounds; } else { m_relativeBounds = RectangleF.Union( m_relativeBounds, childBounds ); } } m_boundsValid = true; } return m_relativeBounds; } } public List< VisualItem > Children { get { return m_children; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace NVelocity.Context { using System.Collections; using System.Collections.Generic; using System.Linq; using Exception; using Runtime; using Runtime.Parser; using Runtime.Parser.Node; /// <summary> Context for Velocity macro arguments. /// /// This special context combines ideas of earlier VMContext and VMProxyArgs /// by implementing routing functionality internally. This significantly /// reduces memory allocation upon macro invocations. /// Since the macro AST is now shared and RuntimeMacro directive is used, /// the earlier implementation of precalculating VMProxyArgs would not work. /// /// See <a href="http://issues.apache.org/jira/browse/VELOCITY-607">Issue 607</a> /// for more Info on this class. /// </summary> /// <author> <a href="mailto:[email protected]">Jarkko Viinamaki</a> /// </author> /// <version> $Id$ /// </version> /// <since> 1.6 /// </since> public class ProxyVMContext : ChainedInternalContextAdapter { /// <seealso cref="org.apache.velocity.context.Context.getKeys()"> /// </seealso> public override object[] Keys { get { if ((localcontext.Count == 0)) { object[] vmproxyhashKeys = new object[vmproxyhash.Count]; vmproxyhash.Keys.CopyTo(vmproxyhashKeys, 0); return vmproxyhashKeys; } else if ((vmproxyhash.Count == 0)) { object[] localcontextKeys = new object[localcontext.Count]; localcontext.Keys.CopyTo(localcontextKeys, 0); return localcontextKeys; } HashSet<object> keys = new HashSet<object>(); foreach (object o in localcontext.Keys) { keys.Add(o); } foreach (object o in vmproxyhash.Keys) { keys.Add(o); } return keys.ToArray(); } } // internal Dictionary<object, object> vmproxyhash = new Dictionary<object, object>(8, 0.8f); internal Dictionary<object, object> vmproxyhash = new Dictionary<object, object>(8); /// <summary>container for any local or constant macro arguments. Size must be power of 2. </summary> /// internal IDictionary localcontext = new Dictionary<object, object>(8, 0.8f); internal IDictionary localcontext = new Dictionary<object, object>(8); /// <summary>support for local context scope feature, where all references are local </summary> private bool localContextScope; /// <summary>needed for writing Log entries. </summary> private IRuntimeServices rsvc; /// <param name="inner">Velocity context for processing /// </param> /// <param name="rsvc">RuntimeServices provides logging reference /// </param> /// <param name="localContextScope">if true, all references are set to be local /// </param> public ProxyVMContext(IInternalContextAdapter inner, IRuntimeServices rsvc, bool localContextScope) : base(inner) { this.localContextScope = localContextScope; this.rsvc = rsvc; } /// <summary> Used to Put Velocity macro arguments into this context. /// /// </summary> /// <param name="context">rendering context /// </param> /// <param name="macroArgumentName">name of the macro argument that we received /// </param> /// <param name="literalMacroArgumentName">".literal.$"+macroArgumentName /// </param> /// <param name="argumentValue">parameters value of the macro argument /// /// </param> /// <throws> MethodInvocationException </throws> public virtual void AddVMProxyArg(IInternalContextAdapter context, string macroArgumentName, string literalMacroArgumentName, INode argumentValue) { if (IsConstant(argumentValue)) { localcontext[macroArgumentName] = argumentValue.Value(context); } else { vmproxyhash[macroArgumentName] = argumentValue; localcontext[literalMacroArgumentName] = argumentValue; } } /// <summary> AST nodes that are considered constants can be directly /// saved into the context. Dynamic values are stored in /// another argument hashmap. /// /// </summary> /// <param name="node">macro argument as AST node /// </param> /// <returns> true if the node is a constant value /// </returns> private bool IsConstant(INode node) { switch (node.Type) { case ParserTreeConstants.JJTINTEGERRANGE: case ParserTreeConstants.JJTREFERENCE: case ParserTreeConstants.JJTOBJECTARRAY: case ParserTreeConstants.JJTMAP: case ParserTreeConstants.JJTSTRINGLITERAL: case ParserTreeConstants.JJTTEXT: return (false); default: return (true); } } /// <summary> Impl of the Context.Put() method. /// /// </summary> /// <param name="key">name of item to set /// </param> /// <param name="value">object to set to key /// </param> /// <returns> old stored object /// </returns> public override object Put(string key, object value) { return Put(key, value, localContextScope); } /// <summary> Allows callers to explicitly Put objects in the local context, no matter what the /// velocimacro.context.local setting says. Needed e.g. for loop variables in foreach. /// /// </summary> /// <param name="key">name of item to set. /// </param> /// <param name="value">object to set to key. /// </param> /// <returns> old stored object /// </returns> public override object LocalPut(string key, object value) { return Put(key, value, true); } /// <summary> Internal Put method to select between local and global scope. /// /// </summary> /// <param name="key">name of item to set /// </param> /// <param name="value">object to set to key /// </param> /// <param name="forceLocal">True forces the object into the local scope. /// </param> /// <returns> old stored object /// </returns> protected internal virtual object Put(string key, object value, bool forceLocal) { INode astNode = (INode)vmproxyhash[key]; if (astNode != null) { if (astNode.Type == ParserTreeConstants.JJTREFERENCE) { ASTReference ref_Renamed = (ASTReference)astNode; if (ref_Renamed.GetNumChildren() > 0) { ref_Renamed.SetValue(innerContext, value); return null; } else { return innerContext.Put(ref_Renamed.RootString, value); } } } object tempObject; tempObject = localcontext[key]; localcontext[key] = value; object old = tempObject; if (!forceLocal) { old = base.Put(key, value); } return old; } /// <summary> Implementation of the Context.Get() method. First checks /// localcontext, then arguments, then global context. /// /// </summary> /// <param name="key">name of item to Get /// </param> /// <returns> stored object or null /// </returns> public override object Get(string key) { object o = localcontext[key]; if (o != null) { return o; } INode astNode = (INode)vmproxyhash[key]; if (astNode != null) { int type = astNode.Type; // if the macro argument (astNode) is a reference, we need to Evaluate it // in case it is a multilevel node if (type == NVelocity.Runtime.Parser.ParserTreeConstants.JJTREFERENCE) { ASTReference ref_Renamed = (ASTReference)astNode; if (ref_Renamed.GetNumChildren() > 0) { return ref_Renamed.Execute((object)null, innerContext); } else { object obj = innerContext.Get(ref_Renamed.RootString); if (obj == null && ref_Renamed.strictRef) { if (!innerContext.ContainsKey(ref_Renamed.RootString)) { throw new MethodInvocationException("Parameter '" + ref_Renamed.RootString + "' not defined", null, key, ref_Renamed.TemplateName, ref_Renamed.Line, ref_Renamed.Column); } } return obj; } } else if (type == NVelocity.Runtime.Parser.ParserTreeConstants.JJTTEXT) { // this really shouldn't happen. text is just a throwaway arg for #foreach() try { System.IO.StringWriter writer = new System.IO.StringWriter(); astNode.Render(innerContext, writer); return writer.ToString(); } catch (System.SystemException e) { throw e; } catch (System.Exception e) { string msg = "ProxyVMContext.Get() : error rendering reference"; rsvc.Log.Error(msg, e); throw new VelocityException(msg, e); } } else { // use value method to render other dynamic nodes return astNode.Value(innerContext); } } return base.Get(key); } /// <seealso cref="org.apache.velocity.context.Context.containsKey(java.lang.Object)"> /// </seealso> public override bool ContainsKey(object key) { return vmproxyhash.ContainsKey(key) || localcontext.Contains(key) || base.ContainsKey(key); } /// <seealso cref="org.apache.velocity.context.Context.remove(java.lang.Object)"> /// </seealso> public override object Remove(object key) { object tempObject; tempObject = localcontext[key]; localcontext.Remove(key); object loc = tempObject; object tempObject2; tempObject2 = vmproxyhash[key]; vmproxyhash.Remove(key); object arg = tempObject2; object glo = null; if (!localContextScope) { glo = base.Remove(key); } if (loc != null) { return loc; } return glo; } } }
// // XmlDataDocumentTestTest.cs - NUnit Test Cases for XmlDataDocument // // Authors: // Ville Palo ([email protected]) // Martin Willemoes Hansen ([email protected]) // // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data; using System.Xml; using System.Xml.XPath; using System.IO; using System.Threading; using System.Globalization; namespace MonoTests.System.Data.Xml { [TestFixture] public class XmlDataDocumentTest : DataSetAssertion { static string EOL = "\n"; [SetUp] public void GetReady() { Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US"); } [Test] public void NewInstance () { XmlDataDocument doc = new XmlDataDocument (); AssertDataSet ("#1", doc.DataSet, "NewDataSet", 0, 0); AssertEquals (false, doc.DataSet.EnforceConstraints); XmlElement el = doc.CreateElement ("TEST"); AssertDataSet ("#2", doc.DataSet, "NewDataSet", 0, 0); AssertNull (doc.GetRowFromElement (el)); doc.AppendChild (el); AssertDataSet ("#3", doc.DataSet, "NewDataSet", 0, 0); DataSet ds = new DataSet (); doc = new XmlDataDocument (ds); AssertEquals (true, doc.DataSet.EnforceConstraints); } [Test] public void SimpleLoad () { string xml001 = "<root/>"; XmlDataDocument doc = new XmlDataDocument (); DataSet ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml001), null); doc.LoadXml (xml001); string xml002 = "<root><child/></root>"; doc = new XmlDataDocument (); ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml002), null); doc.LoadXml (xml002); string xml003 = "<root><col1>test</col1><col1></col1></root>"; doc = new XmlDataDocument (); ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml003), null); doc.LoadXml (xml003); string xml004 = "<set><tab1><col1>test</col1><col1>test2</col1></tab1><tab2><col2>test3</col2><col2>test4</col2></tab2></set>"; doc = new XmlDataDocument (); ds = new DataSet (); ds.InferXmlSchema (new StringReader (xml004), null); doc.LoadXml (xml004); } [Test] public void CloneNode () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlDataDocument doc2 = (XmlDataDocument)doc.CloneNode (false); AssertEquals ("#I01", 0, doc2.ChildNodes.Count); AssertEquals ("#I02", "<?xml version=\"1.0\" encoding=\"utf-16\"?>", doc2.DataSet.GetXmlSchema ().Substring (0, 39)); doc2 = (XmlDataDocument)doc.CloneNode (true); AssertEquals ("#I03", 2, doc2.ChildNodes.Count); AssertEquals ("#I04", "<?xml version=\"1.0\" encoding=\"utf-16\"?>", doc2.DataSet.GetXmlSchema ().Substring (0, 39)); doc.DataSet.Tables [0].Rows [0][0] = "64"; AssertEquals ("#I05", "1", doc2.DataSet.Tables [0].Rows [0][0].ToString ()); } [Test] public void EditingXmlTree () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlElement Element = doc.GetElementFromRow (doc.DataSet.Tables [0].Rows [1]); Element.FirstChild.InnerText = "64"; AssertEquals ("test#01", "64", doc.DataSet.Tables [0].Rows [1] [0]); DataSet Set = new DataSet (); Set.ReadXml ("Test/System.Xml/region.xml"); doc = new XmlDataDocument (Set); Element = doc.GetElementFromRow (doc.DataSet.Tables [0].Rows [1]); AssertNotNull (Element); try { Element.FirstChild.InnerText = "64"; Fail ("test#02"); } catch (InvalidOperationException) { } AssertEquals ("test#05", "2", doc.DataSet.Tables [0].Rows [1] [0]); Set.EnforceConstraints = false; Element.FirstChild.InnerText = "64"; AssertEquals ("test#06", "64", doc.DataSet.Tables [0].Rows [1] [0]); } [Test] public void EditingDataSet () { string xml = "<Root><Region><RegionID>1</RegionID><RegionDescription>Eastern\r\n </RegionDescription></Region><Region><RegionID>2</RegionID><RegionDescription>Western\r\n </RegionDescription></Region><Region><RegionID>3</RegionID><RegionDescription>Northern\r\n </RegionDescription></Region><Region><RegionID>4</RegionID><RegionDescription>Southern\r\n </RegionDescription></Region><MoreData><Column1>12</Column1><Column2>Hi There</Column2></MoreData><MoreData><Column1>12</Column1><Column2>Hi There</Column2></MoreData></Root>"; XmlReader Reader = new XmlTextReader ("Test/System.Xml/region.xml"); XmlDataDocument Doc = new XmlDataDocument (); Doc.DataSet.ReadXml (Reader); StringWriter sw = new StringWriter (); XmlTextWriter xw = new XmlTextWriter (sw); Doc.DataSet.WriteXml (xw); string s = sw.ToString (); AssertEquals (xml, s); AssertEquals (xml, Doc.InnerXml); AssertEquals ("test#01", "EndOfFile", Reader.ReadState.ToString ()); DataSet Set = Doc.DataSet; AssertEquals ("test#01.5", "2", Set.Tables [0].Rows [1] [0]); Set.Tables [0].Rows [1] [0] = "64"; AssertEquals ("test#02", "64", Doc.FirstChild.FirstChild.NextSibling.FirstChild.InnerText); } [Test] public void CreateElement1 () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlElement Element = doc.CreateElement ("prefix", "localname", "namespaceURI"); AssertEquals ("test#01", "prefix", Element.Prefix); AssertEquals ("test#02", "localname", Element.LocalName); AssertEquals ("test#03", "namespaceURI", Element.NamespaceURI); doc.ImportNode (Element, false); TextWriter text = new StringWriter (); doc.Save(text); string substring = ""; string TextString = text.ToString (); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("test#05", substring.IndexOf ("<Root>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("test#06", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("test#07", substring.IndexOf (" <RegionID>1</RegionID>") != -1); for (int i = 0; i < 26; i++) { substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); } substring = TextString.Substring (0, TextString.Length); Assert ("test#07", substring.IndexOf ("</Root>") != -1); } [Test] public void CreateElement2 () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlElement Element = doc.CreateElement ("ElementName"); AssertEquals ("test#01", "", Element.Prefix); AssertEquals ("test#02", "ElementName", Element.LocalName); AssertEquals ("test#03", "", Element.NamespaceURI); Element = doc.CreateElement ("prefix:ElementName"); AssertEquals ("test#04", "prefix", Element.Prefix); AssertEquals ("test#05", "ElementName", Element.LocalName); AssertEquals ("test#06", "", Element.NamespaceURI); } [Test] public void CreateElement3 () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlElement Element = doc.CreateElement ("ElementName", "namespace"); AssertEquals ("test#01", "", Element.Prefix); AssertEquals ("test#02", "ElementName", Element.LocalName); AssertEquals ("test#03", "namespace", Element.NamespaceURI); Element = doc.CreateElement ("prefix:ElementName", "namespace"); AssertEquals ("test#04", "prefix", Element.Prefix); AssertEquals ("test#05", "ElementName", Element.LocalName); AssertEquals ("test#06", "namespace", Element.NamespaceURI); } [Test] public void Navigator () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XPathNavigator Nav = doc.CreateNavigator (); Nav.MoveToRoot (); Nav.MoveToFirstChild (); AssertEquals ("test#01", "Root", Nav.Name.ToString ()); AssertEquals ("test#02", "", Nav.NamespaceURI.ToString ()); AssertEquals ("test#03", "False", Nav.IsEmptyElement.ToString ()); AssertEquals ("test#04", "Element", Nav.NodeType.ToString ()); AssertEquals ("test#05", "", Nav.Prefix); Nav.MoveToFirstChild (); Nav.MoveToNext (); AssertEquals ("test#06", "Region", Nav.Name.ToString ()); AssertEquals ("test#07", "2Western", Nav.Value.Substring(0, Nav.Value.IndexOf ("\n") - 1)); Nav.MoveToFirstChild (); AssertEquals ("test#08", "2", Nav.Value); Nav.MoveToRoot (); AssertEquals ("test#09", "Root", Nav.NodeType.ToString ()); } // Test constructor [Test] public void Test1() { //Create an XmlDataDocument. XmlDataDocument doc = new XmlDataDocument(); //Load the schema file. doc.DataSet.ReadXmlSchema("Test/System.Xml/store.xsd"); Console.WriteLine ("books: " + doc.DataSet.Tables.Count); //Load the XML data. doc.Load("Test/System.Xml/2books.xml"); //Update the price on the first book using the DataSet methods. DataTable books = doc.DataSet.Tables["book"]; Console.WriteLine ("books: " + doc.DataSet.Tables [0].TableName); books.Rows[0]["price"] = "12.95"; //string outstring = ""; TextWriter text = new StringWriter (); text.NewLine = "\n"; doc.Save(text); //str.Read (bytes, 0, (int)str.Length); //String OutString = new String (bytes); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A01", substring.IndexOf ("<?xml version=\"1.0\" encoding=\"utf-16\"?>") == 0); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A02", substring.IndexOf ("<!--sample XML fragment-->") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A03", substring.IndexOf ("<bookstore>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A04", substring.IndexOf (" <book genre=\"novel\" ISBN=\"10-861003-324\">") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A05", substring.IndexOf (" <title>The Handmaid's Tale</title>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#A06", " <price>12.95</price>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A07", substring.IndexOf (" </book>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A08", substring.IndexOf (" <book genre=\"novel\" ISBN=\"1-861001-57-5\">") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A09", substring.IndexOf (" <title>Pride And Prejudice</title>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A10", substring.IndexOf (" <price>24.95</price>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#A11", substring.IndexOf (" </book>") != -1); substring = TextString; Assert ("#A12", substring.IndexOf ("</bookstore>") != -1); } // Test public fields [Test] public void Test2() { DataSet RegionDS = new DataSet (); DataRow RegionRow; RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); AssertEquals ("Was read correct?", 1, RegionDS.Tables.Count); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); DataDoc.Load("Test/System.Xml/region.xml" ); RegionRow = RegionDS.Tables[0].Rows[0]; RegionDS.AcceptChanges (); RegionRow["RegionDescription"] = "Reeeeeaalllly Far East!"; RegionDS.AcceptChanges (); TextWriter text = new StringWriter (); text.NewLine = "\n"; DataDoc.Save (text); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); //AssertEquals ("#B01", "<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#B02", "<Root>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B03", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B04", substring.IndexOf (" <RegionID>1</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#B05", " <RegionDescription>Reeeeeaalllly Far East!</RegionDescription>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B06", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B07", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B08", substring.IndexOf (" <RegionID>2</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B09", substring.IndexOf (" <RegionDescription>Western") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B10", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B11", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B12", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B13", substring.IndexOf (" <RegionID>3</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B14", substring.IndexOf (" <RegionDescription>Northern") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B15", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B16", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B17", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B18", substring.IndexOf (" <RegionID>4</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B19", substring.IndexOf (" <RegionDescription>Southern") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B20", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B21", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B22", substring.IndexOf (" <MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B23", substring.IndexOf (" <Column1>12</Column1>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B24", substring.IndexOf (" <Column2>Hi There</Column2>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B25", substring.IndexOf (" </MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B26", substring.IndexOf (" <MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B27", substring.IndexOf (" <Column1>12</Column1>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B28", substring.IndexOf (" <Column2>Hi There</Column2>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#B29", substring.IndexOf (" </MoreData>") != -1); } [Test] public void Test3() { XmlDataDocument DataDoc = new XmlDataDocument (); DataSet dataset = DataDoc.DataSet; dataset.ReadXmlSchema ("Test/System.Xml/region.xsd"); DataDoc.Load("Test/System.Xml/region.xml" ); DataDoc.GetElementsByTagName ("Region") [0].RemoveAll (); TextWriter text = new StringWriter (); text.NewLine = "\n"; dataset.WriteXml (text); //DataDoc.Save (text); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C01", substring.IndexOf ("<Root>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#C02", " <Region />", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#C03", " <Region>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#C04", " <RegionID>2</RegionID>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); // Regardless of NewLine value, original xml contains CR // (but in the context of XML spec, it should be normalized) AssertEquals ("#C05", " <RegionDescription>Western\r", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C06", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#C07", " </Region>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C08", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C09", substring.IndexOf (" <RegionID>3</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); // Regardless of NewLine value, original xml contains CR // (but in the context of XML spec, it should be normalized) AssertEquals ("#C10", " <RegionDescription>Northern\r", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C11", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C12", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C13", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C14", substring.IndexOf (" <RegionID>4</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C15", substring.IndexOf (" <RegionDescription>Southern") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C16", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#C17", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.Length); Assert ("#C18", substring.IndexOf ("</Root>") != -1); } [Test] public void Test4 () { DataSet RegionDS = new DataSet (); RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); DataDoc.Load("Test/System.Xml/region.xml" ); AssertEquals (true, RegionDS.EnforceConstraints); DataTable table = DataDoc.DataSet.Tables ["Region"]; DataRow newRow = table.NewRow (); newRow [0] = "new row"; newRow [1] = "new description"; table.Rows.Add (newRow); TextWriter text = new StringWriter (); text.NewLine = "\n"; DataDoc.Save (text); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F02", substring.IndexOf ("<Root>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F03", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F04", substring.IndexOf (" <RegionID>1</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); // Regardless of NewLine value, original xml contains CR // (but in the context of XML spec, it should be normalized) AssertEquals ("#F05", " <RegionDescription>Eastern\r", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); AssertEquals ("#F06", " </RegionDescription>", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F07", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F08", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F09", substring.IndexOf (" <RegionID>2</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F10", substring.IndexOf (" <RegionDescription>Western") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F11", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F12", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F13", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F14", substring.IndexOf (" <RegionID>3</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F15", substring.IndexOf (" <RegionDescription>Northern") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F16", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F17", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F18", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F19", substring.IndexOf (" <RegionID>4</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); // Regardless of NewLine value, original xml contains CR // (but in the context of XML spec, it should be normalized) AssertEquals ("#F20", " <RegionDescription>Southern\r", substring); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F21", substring.IndexOf (" </RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F22", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F23", substring.IndexOf (" <MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F24", substring.IndexOf (" <Column1>12</Column1>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F25", substring.IndexOf (" <Column2>Hi There</Column2>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F26", substring.IndexOf (" </MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F27", substring.IndexOf (" <MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F28", substring.IndexOf (" <Column1>12</Column1>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F29", substring.IndexOf (" <Column2>Hi There</Column2>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F30", substring.IndexOf (" </MoreData>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F31", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F32", substring.IndexOf (" <RegionID>new row</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F33", substring.IndexOf (" <RegionDescription>new description</RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf(EOL)); TextString = TextString.Substring (TextString.IndexOf(EOL) + EOL.Length); Assert ("#F34", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.Length); Assert ("#F35", substring.IndexOf ("</Root>") != -1); } [Test] public void Test5 () { DataSet RegionDS = new DataSet (); RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); DataDoc.Load("Test/System.Xml/region.xml" ); try { DataDoc.DocumentElement.AppendChild (DataDoc.DocumentElement.FirstChild); Fail ("#G01"); } catch (Exception e) { AssertEquals ("#G02", typeof (InvalidOperationException), e.GetType ()); AssertEquals ("#G03", "Please set DataSet.EnforceConstraints == false before trying to edit " + "XmlDataDocument using XML operations.", e.Message); DataDoc.DataSet.EnforceConstraints = false; } XmlElement newNode = DataDoc.CreateElement ("Region"); XmlElement newChildNode = DataDoc.CreateElement ("RegionID"); newChildNode.InnerText = "64"; XmlElement newChildNode2 = DataDoc.CreateElement ("RegionDescription"); newChildNode2.InnerText = "test node"; newNode.AppendChild (newChildNode); newNode.AppendChild (newChildNode2); DataDoc.DocumentElement.AppendChild (newNode); TextWriter text = new StringWriter (); //DataDoc.Save (text); DataDoc.DataSet.WriteXml(text); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); for (int i = 0; i < 21; i++) { substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); } Assert ("#G04", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("#G05", substring.IndexOf (" <RegionID>64</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("#G06", substring.IndexOf (" <RegionDescription>test node</RegionDescription>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("#G07", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.Length); Assert ("#G08", substring.IndexOf ("</Root>") != -1); } [Test] public void Test6 () { DataSet RegionDS = new DataSet (); RegionDS.ReadXmlSchema ("Test/System.Xml/region.xsd"); XmlDataDocument DataDoc = new XmlDataDocument (RegionDS); DataDoc.Load("Test/System.Xml/region.xml" ); DataDoc.DataSet.EnforceConstraints = false; XmlElement newNode = DataDoc.CreateElement ("Region"); XmlElement newChildNode = DataDoc.CreateElement ("RegionID"); newChildNode.InnerText = "64"; XmlElement newChildNode2 = null; try { newChildNode2 = DataDoc.CreateElement ("something else"); Fail ("#H01"); } catch (XmlException) { } newChildNode2 = DataDoc.CreateElement ("something_else"); newChildNode2.InnerText = "test node"; newNode.AppendChild (newChildNode); newNode.AppendChild (newChildNode2); DataDoc.DocumentElement.AppendChild (newNode); TextWriter text = new StringWriter (); //DataDoc.Save (text); DataDoc.DataSet.WriteXml(text); string TextString = text.ToString (); string substring = TextString.Substring (0, TextString.IndexOf("\n") - 1); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); for (int i = 0; i < 21; i++) { substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); } Assert ("#H03", substring.IndexOf (" <Region>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n")); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("#H04", substring.IndexOf (" <RegionID>64</RegionID>") != -1); substring = TextString.Substring (0, TextString.IndexOf("\n") ); TextString = TextString.Substring (TextString.IndexOf("\n") + 1); Assert ("#H05", substring.IndexOf (" </Region>") != -1); substring = TextString.Substring (0, TextString.Length); Assert ("#H06", substring.IndexOf ("</Root>") != -1); } [Test] public void GetElementFromRow () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); DataTable table = doc.DataSet.Tables ["Region"]; XmlElement element = doc.GetElementFromRow (table.Rows [2]); AssertEquals ("#D01", "Region", element.Name); AssertEquals ("#D02", "3", element ["RegionID"].InnerText); try { element = doc.GetElementFromRow (table.Rows [4]); Fail ("#D03"); } catch (Exception e) { AssertEquals ("#D04", typeof (IndexOutOfRangeException), e.GetType ()); AssertEquals ("#D05", "There is no row at position 4.", e.Message); } } [Test] public void GetRowFromElement () { XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema ("Test/System.Xml/region.xsd"); doc.Load ("Test/System.Xml/region.xml"); XmlElement root = doc.DocumentElement; DataRow row = doc.GetRowFromElement((XmlElement)root.FirstChild); AssertEquals ("#E01", "1", row [0]); row = doc.GetRowFromElement((XmlElement)root.ChildNodes [2]); AssertEquals ("#E02", "3", row [0]); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { // Linear constraint (point-to-line) // d = p2 - p1 = x2 + r2 - x1 - r1 // C = dot(perp, d) // Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) // J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] // // Angular constraint // C = a2 - a1 + a_initial // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // // K = J * invM * JT // // J = [-a -s1 a s2] // [0 -1 0 1] // a = perp // s1 = cross(d + r1, a) = cross(p2 - x1, a) // s2 = cross(r2, a) = cross(p2 - x2, a) // Motor/Limit linear constraint // C = dot(ax1, d) // Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) // J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] // Block Solver // We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even // when the mass has poor distribution (leading to large torques about the joint anchor points). // // The Jacobian has 3 rows: // J = [-uT -s1 uT s2] // linear // [0 -1 0 1] // angular // [-vT -a1 vT a2] // limit // // u = perp // v = axis // s1 = cross(d + r1, u), s2 = cross(r2, u) // a1 = cross(d + r1, v), a2 = cross(r2, v) // M * (v2 - v1) = JT * df // J * v2 = bias // // v2 = v1 + invM * JT * df // J * (v1 + invM * JT * df) = bias // K * df = bias - J * v1 = -Cdot // K = J * invM * JT // Cdot = J * v1 - bias // // Now solve for f2. // df = f2 - f1 // K * (f2 - f1) = -Cdot // f2 = invK * (-Cdot) + f1 // // Clamp accumulated limit impulse. // lower: f2(3) = max(f2(3), 0) // upper: f2(3) = min(f2(3), 0) // // Solve for correct f2(1:2) // K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 // = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) // K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) // // Now compute impulse to be applied: // df = f2 - f1 /// <summary> /// A prismatic joint. This joint provides one degree of freedom: translation /// along an axis fixed in body1. Relative rotation is prevented. You can /// use a joint limit to restrict the range of motion and a joint motor to /// drive the motion or to model joint friction. /// </summary> public class PrismaticJoint : Joint { public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; private Mat33 _K; private float _a1, _a2; private Vector2 _axis; private bool _enableLimit; private bool _enableMotor; private Vector3 _impulse; private LimitState _limitState; private Vector2 _localXAxis1; private Vector2 _localYAxis1; private float _lowerTranslation; private float _maxMotorForce; private float _motorImpulse; private float _motorMass; // effective mass for motor/limit translational constraint. private float _motorSpeed; private Vector2 _perp; private float _refAngle; private float _s1, _s2; private float _upperTranslation; /// <summary> /// This requires defining a line of /// motion using an axis and an anchor point. The definition uses local /// anchor points and a local axis so that the initial configuration /// can violate the constraint slightly. The joint translation is zero /// when the local anchor points coincide in world space. Using local /// anchors and a local axis helps when saving and loading a game. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="localAnchorA">The first body anchor.</param> /// <param name="localAnchorB">The second body anchor.</param> /// <param name="axis">The axis.</param> public PrismaticJoint(Body bodyA, Body bodyB, Vector2 localAnchorA, Vector2 localAnchorB, Vector2 axis) : base(bodyA, bodyB) { JointType = JointType.Prismatic; LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; _localXAxis1 = BodyA.GetLocalVector(axis); _localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1); _refAngle = BodyB.Rotation - BodyA.Rotation; _limitState = LimitState.Inactive; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// Get the current joint translation, usually in meters. /// </summary> /// <value></value> public float JointTranslation { get { Vector2 d = BodyB.GetWorldPoint(LocalAnchorB) - BodyA.GetWorldPoint(LocalAnchorA); Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1); return Vector2.Dot(d, axis); } } /// <summary> /// Get the current joint translation speed, usually in meters per second. /// </summary> /// <value></value> public float JointSpeed { get { Transform xf1, xf2; BodyA.GetTransform(out xf1); BodyB.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - BodyA.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - BodyB.LocalCenter); Vector2 p1 = BodyA.Sweep.C + r1; Vector2 p2 = BodyB.Sweep.C + r2; Vector2 d = p2 - p1; Vector2 axis = BodyA.GetWorldVector(ref _localXAxis1); Vector2 v1 = BodyA.LinearVelocityInternal; Vector2 v2 = BodyB.LinearVelocityInternal; float w1 = BodyA.AngularVelocityInternal; float w2 = BodyB.AngularVelocityInternal; float speed = Vector2.Dot(d, MathUtils.Cross(w1, axis)) + Vector2.Dot(axis, v2 + MathUtils.Cross(w2, r2) - v1 - MathUtils.Cross(w1, r1)); return speed; } } /// <summary> /// Is the joint limit enabled? /// </summary> /// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value> public bool LimitEnabled { get { return _enableLimit; } set { WakeBodies(); _enableLimit = value; } } /// <summary> /// Get the lower joint limit, usually in meters. /// </summary> /// <value></value> public float LowerLimit { get { return _lowerTranslation; } set { WakeBodies(); _lowerTranslation = value; } } /// <summary> /// Get the upper joint limit, usually in meters. /// </summary> /// <value></value> public float UpperLimit { get { return _upperTranslation; } set { WakeBodies(); _upperTranslation = value; } } /// <summary> /// Is the joint motor enabled? /// </summary> /// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value> public bool MotorEnabled { get { return _enableMotor; } set { WakeBodies(); _enableMotor = value; } } /// <summary> /// Set the motor speed, usually in meters per second. /// </summary> /// <value>The speed.</value> public float MotorSpeed { set { WakeBodies(); _motorSpeed = value; } get { return _motorSpeed; } } /// <summary> /// Set the maximum motor force, usually in N. /// </summary> /// <value>The force.</value> public float MaxMotorForce { set { WakeBodies(); _maxMotorForce = value; } } /// <summary> /// Get the current motor force, usually in N. /// </summary> /// <value></value> public float MotorForce { get { return _motorImpulse; } set { _motorImpulse = value; } } public Vector2 LocalXAxis1 { get { return _localXAxis1; } set { _localXAxis1 = BodyA.GetLocalVector(value); _localYAxis1 = MathUtils.Cross(1.0f, _localXAxis1); } } public override Vector2 GetReactionForce(float inv_dt) { return inv_dt*(_impulse.X*_perp + (_motorImpulse + _impulse.Z)*_axis); } public override float GetReactionTorque(float inv_dt) { return inv_dt*_impulse.Y; } internal override void InitVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; LocalCenterA = b1.LocalCenter; LocalCenterB = b2.LocalCenter; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); // Compute the effective masses. Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - LocalCenterA); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - LocalCenterB); Vector2 d = b2.Sweep.C + r2 - b1.Sweep.C - r1; InvMassA = b1.InvMass; InvIA = b1.InvI; InvMassB = b2.InvMass; InvIB = b2.InvI; // Compute motor Jacobian and effective mass. { _axis = MathUtils.Multiply(ref xf1.R, _localXAxis1); _a1 = MathUtils.Cross(d + r1, _axis); _a2 = MathUtils.Cross(r2, _axis); _motorMass = InvMassA + InvMassB + InvIA*_a1*_a1 + InvIB*_a2*_a2; if (_motorMass > Settings.Epsilon) { _motorMass = 1.0f/_motorMass; } } // Prismatic constraint. { _perp = MathUtils.Multiply(ref xf1.R, _localYAxis1); _s1 = MathUtils.Cross(d + r1, _perp); _s2 = MathUtils.Cross(r2, _perp); float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1*_s1*_s1 + i2*_s2*_s2; float k12 = i1*_s1 + i2*_s2; float k13 = i1*_s1*_a1 + i2*_s2*_a2; float k22 = i1 + i2; float k23 = i1*_a1 + i2*_a2; float k33 = m1 + m2 + i1*_a1*_a1 + i2*_a2*_a2; _K.Col1 = new Vector3(k11, k12, k13); _K.Col2 = new Vector3(k12, k22, k23); _K.Col3 = new Vector3(k13, k23, k33); } // Compute motor and limit terms. if (_enableLimit) { float jointTranslation = Vector2.Dot(_axis, d); if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f*Settings.LinearSlop) { _limitState = LimitState.Equal; } else if (jointTranslation <= _lowerTranslation) { if (_limitState != LimitState.AtLower) { _limitState = LimitState.AtLower; _impulse.Z = 0.0f; } } else if (jointTranslation >= _upperTranslation) { if (_limitState != LimitState.AtUpper) { _limitState = LimitState.AtUpper; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; } if (_enableMotor == false) { _motorImpulse = 0.0f; } if (Settings.EnableWarmstarting) { // Account for variable time step. _impulse *= step.dtRatio; _motorImpulse *= step.dtRatio; Vector2 P = _impulse.X*_perp + (_motorImpulse + _impulse.Z)*_axis; float L1 = _impulse.X*_s1 + _impulse.Y + (_motorImpulse + _impulse.Z)*_a1; float L2 = _impulse.X*_s2 + _impulse.Y + (_motorImpulse + _impulse.Z)*_a2; b1.LinearVelocityInternal -= InvMassA*P; b1.AngularVelocityInternal -= InvIA*L1; b2.LinearVelocityInternal += InvMassB*P; b2.AngularVelocityInternal += InvIB*L2; } else { _impulse = Vector3.Zero; _motorImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; Vector2 v1 = b1.LinearVelocityInternal; float w1 = b1.AngularVelocityInternal; Vector2 v2 = b2.LinearVelocityInternal; float w2 = b2.AngularVelocityInternal; // Solve linear motor constraint. if (_enableMotor && _limitState != LimitState.Equal) { float Cdot = Vector2.Dot(_axis, v2 - v1) + _a2*w2 - _a1*w1; float impulse = _motorMass*(_motorSpeed - Cdot); float oldImpulse = _motorImpulse; float maxImpulse = step.dt*_maxMotorForce; _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; Vector2 P = impulse*_axis; float L1 = impulse*_a1; float L2 = impulse*_a2; v1 -= InvMassA*P; w1 -= InvIA*L1; v2 += InvMassB*P; w2 += InvIB*L2; } Vector2 Cdot1 = new Vector2(Vector2.Dot(_perp, v2 - v1) + _s2*w2 - _s1*w1, w2 - w1); if (_enableLimit && _limitState != LimitState.Inactive) { // Solve prismatic and limit constraint in block form. float Cdot2 = Vector2.Dot(_axis, v2 - v1) + _a2*w2 - _a1*w1; Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2); Vector3 f1 = _impulse; Vector3 df = _K.Solve33(-Cdot); _impulse += df; if (_limitState == LimitState.AtLower) { _impulse.Z = Math.Max(_impulse.Z, 0.0f); } else if (_limitState == LimitState.AtUpper) { _impulse.Z = Math.Min(_impulse.Z, 0.0f); } // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) Vector2 b = -Cdot1 - (_impulse.Z - f1.Z)*new Vector2(_K.Col3.X, _K.Col3.Y); Vector2 f2r = _K.Solve22(b) + new Vector2(f1.X, f1.Y); _impulse.X = f2r.X; _impulse.Y = f2r.Y; df = _impulse - f1; Vector2 P = df.X*_perp + df.Z*_axis; float L1 = df.X*_s1 + df.Y + df.Z*_a1; float L2 = df.X*_s2 + df.Y + df.Z*_a2; v1 -= InvMassA*P; w1 -= InvIA*L1; v2 += InvMassB*P; w2 += InvIB*L2; } else { // Limit is inactive, just solve the prismatic constraint in block form. Vector2 df = _K.Solve22(-Cdot1); _impulse.X += df.X; _impulse.Y += df.Y; Vector2 P = df.X*_perp; float L1 = df.X*_s1 + df.Y; float L2 = df.X*_s2 + df.Y; v1 -= InvMassA*P; w1 -= InvIA*L1; v2 += InvMassB*P; w2 += InvIB*L2; } b1.LinearVelocityInternal = v1; b1.AngularVelocityInternal = w1; b2.LinearVelocityInternal = v2; b2.AngularVelocityInternal = w2; } internal override bool SolvePositionConstraints() { Body b1 = BodyA; Body b2 = BodyB; Vector2 c1 = b1.Sweep.C; float a1 = b1.Sweep.A; Vector2 c2 = b2.Sweep.C; float a2 = b2.Sweep.A; // Solve linear limit constraint. float linearError = 0.0f; bool active = false; float C2 = 0.0f; Mat22 R1 = new Mat22(a1); Mat22 R2 = new Mat22(a2); Vector2 r1 = MathUtils.Multiply(ref R1, LocalAnchorA - LocalCenterA); Vector2 r2 = MathUtils.Multiply(ref R2, LocalAnchorB - LocalCenterB); Vector2 d = c2 + r2 - c1 - r1; if (_enableLimit) { _axis = MathUtils.Multiply(ref R1, _localXAxis1); _a1 = MathUtils.Cross(d + r1, _axis); _a2 = MathUtils.Cross(r2, _axis); float translation = Vector2.Dot(_axis, d); if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f*Settings.LinearSlop) { // Prevent large angular corrections C2 = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection); linearError = Math.Abs(translation); active = true; } else if (translation <= _lowerTranslation) { // Prevent large linear corrections and allow some slop. C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f); linearError = _lowerTranslation - translation; active = true; } else if (translation >= _upperTranslation) { // Prevent large linear corrections and allow some slop. C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f, Settings.MaxLinearCorrection); linearError = translation - _upperTranslation; active = true; } } _perp = MathUtils.Multiply(ref R1, _localYAxis1); _s1 = MathUtils.Cross(d + r1, _perp); _s2 = MathUtils.Cross(r2, _perp); Vector3 impulse; Vector2 C1 = new Vector2(Vector2.Dot(_perp, d), a2 - a1 - _refAngle); linearError = Math.Max(linearError, Math.Abs(C1.X)); float angularError = Math.Abs(C1.Y); if (active) { float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1*_s1*_s1 + i2*_s2*_s2; float k12 = i1*_s1 + i2*_s2; float k13 = i1*_s1*_a1 + i2*_s2*_a2; float k22 = i1 + i2; float k23 = i1*_a1 + i2*_a2; float k33 = m1 + m2 + i1*_a1*_a1 + i2*_a2*_a2; _K.Col1 = new Vector3(k11, k12, k13); _K.Col2 = new Vector3(k12, k22, k23); _K.Col3 = new Vector3(k13, k23, k33); Vector3 C = new Vector3(-C1.X, -C1.Y, -C2); impulse = _K.Solve33(C); // negated above } else { float m1 = InvMassA, m2 = InvMassB; float i1 = InvIA, i2 = InvIB; float k11 = m1 + m2 + i1*_s1*_s1 + i2*_s2*_s2; float k12 = i1*_s1 + i2*_s2; float k22 = i1 + i2; _K.Col1 = new Vector3(k11, k12, 0.0f); _K.Col2 = new Vector3(k12, k22, 0.0f); Vector2 impulse1 = _K.Solve22(-C1); impulse.X = impulse1.X; impulse.Y = impulse1.Y; impulse.Z = 0.0f; } Vector2 P = impulse.X*_perp + impulse.Z*_axis; float L1 = impulse.X*_s1 + impulse.Y + impulse.Z*_a1; float L2 = impulse.X*_s2 + impulse.Y + impulse.Z*_a2; c1 -= InvMassA*P; a1 -= InvIA*L1; c2 += InvMassB*P; a2 += InvIB*L2; // TODO_ERIN remove need for this. b1.Sweep.C = c1; b1.Sweep.A = a1; b2.Sweep.C = c2; b2.Sweep.A = a2; b1.SynchronizeTransform(); b2.SynchronizeTransform(); return linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop; } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Linq; using System.Threading.Tasks; using Piranha.Models; using Piranha.Manager.Models; using System.IO; using System.Collections.Generic; using System.Data; namespace Piranha.Manager.Services { public class MediaService { private readonly IApi _api; /// <summary> /// Default constructor. /// </summary> /// <param name="api">The default api</param> public MediaService(IApi api) { _api = api; } /// <summary> /// Get media model by media id /// </summary> /// <param name="id">Media id</param> /// <returns>Model</returns> public async Task<MediaListModel.MediaItem> GetById(Guid id) { var media = await _api.Media.GetByIdAsync(id); if (media == null) return null; return new MediaListModel.MediaItem { Id = media.Id, FolderId = media.FolderId, Type = media.Type.ToString(), Filename = media.Filename, PublicUrl = media.PublicUrl.Replace("~", ""), ContentType = media.ContentType, Title = media.Title, AltText = media.AltText, Description = media.Description, Properties = media.Properties.ToArray().OrderBy(p => p.Key).ToList(), Size = Utils.FormatByteSize(media.Size), Width = media.Width, Height = media.Height, LastModified = media.LastModified.ToString("yyyy-MM-dd") }; } /// <summary> /// Gets the breadcrumb list of the folders from the selected folder id /// </summary> /// <param name="structure">The complete media folder structure</param> /// <param name="folderId">The folder id</param> /// <returns></returns> public async Task<List<MediaFolderSimple>> GetFolderBreadCrumb(MediaStructure structure, Guid? folderId) { var folders = await GetFolderBreadCrumbReversed(structure, folderId); folders.Reverse(); return folders; } /// <summary> /// Gets the breadcrumb list of the folders from the selected folder id in reverse order with child first in list /// </summary> /// <param name="structure">The complete media folder structure</param> /// <param name="folderId">The folder id</param> /// <returns></returns> private async Task<List<MediaFolderSimple>> GetFolderBreadCrumbReversed(MediaStructure structure, Guid? folderId) { var folders = new List<MediaFolderSimple>(); if (!folderId.HasValue) return folders; foreach (var item in structure) { if (item.Id == folderId) { folders.Add(new MediaFolderSimple() { Id = item.Id, Name = item.Name }); return folders; } if (item.Items.Count > 0) { folders = await GetFolderBreadCrumbReversed(item.Items, folderId); if(folders.Count > 0) { folders.Add(new MediaFolderSimple() { Id = item.Id, Name = item.Name }); return folders; } } } return folders; } /// <summary> /// Gets the list model for the specified folder, or the root /// folder if no folder id is given. /// </summary> /// <param name="folderId">The optional folder id</param> /// <param name="filter">The optional content type filter</param> /// <param name="width">The optional width for images</param> /// <param name="height">The optional height for images</param> /// <returns>The list model</returns> public async Task<MediaListModel> GetList(Guid? folderId = null, MediaType? filter = null, int? width = null, int? height = null) { var model = new MediaListModel { CurrentFolderId = folderId, ParentFolderId = null, Structure = await _api.Media.GetStructureAsync() }; model.CurrentFolderBreadcrumb = await GetFolderBreadCrumb(model.Structure, folderId); model.RootCount = model.Structure.MediaCount; model.TotalCount = model.Structure.TotalCount; if (folderId.HasValue) { var partial = model.Structure.GetPartial(folderId, true); if (partial.FirstOrDefault()?.MediaCount == 0 && partial.FirstOrDefault()?.FolderCount == 0) { model.CanDelete = true; } } if (folderId.HasValue) { var folder = await _api.Media.GetFolderByIdAsync(folderId.Value); if (folder != null) { model.CurrentFolderName = folder.Name; model.ParentFolderId = folder.ParentId; } } var holdMedia = (await _api.Media.GetAllByFolderIdAsync(folderId)); if (filter.HasValue) { holdMedia = holdMedia .Where(m => m.Type == filter.Value); } var pairMedia = holdMedia.Select(m => new { media = m, mediaItem = new MediaListModel.MediaItem { Id = m.Id, FolderId = m.FolderId, Type = m.Type.ToString(), Filename = m.Filename, PublicUrl = m.PublicUrl.TrimStart('~'), //Will only enumerate the start of the string, probably a faster operation. ContentType = m.ContentType, Title = m.Title, AltText = m.AltText, Description = m.Description, Properties = m.Properties.ToArray().OrderBy(p => p.Key).ToList(), Size = Utils.FormatByteSize(m.Size), Width = m.Width, Height = m.Height, LastModified = m.LastModified.ToString("yyyy-MM-dd") }}).ToArray(); model.Folders = model.Structure.GetPartial(folderId) .Select(f => new MediaListModel.FolderItem { Id = f.Id, Name = f.Name, ItemCount = f.MediaCount }).ToList(); if (width.HasValue) { foreach (var mp in pairMedia.Where(m => m.media.Type == MediaType.Image)) { if (mp.media.Versions.Any(v => v.Width == width && v.Height == height)) { mp.mediaItem.AltVersionUrl = (await _api.Media.EnsureVersionAsync(mp.media, width.Value, height).ConfigureAwait(false)) .TrimStart('~'); } } } model.Media = pairMedia.Select(m => m.mediaItem).ToList(); model.ViewMode = model.Media.Count(m => m.Type == "Image") > model.Media.Count / 2 ? MediaListModel.GalleryView : MediaListModel.ListView; return model; } public async Task SaveFolder(MediaFolderModel model) { if (model.Id.HasValue) { var folder = await _api.Media.GetFolderByIdAsync(model.Id.Value); folder.Name = model.Name; await _api.Media.SaveFolderAsync(folder); } else { await _api.Media.SaveFolderAsync(new MediaFolder { ParentId = model.ParentId, Name = model.Name }); } } public async Task<Guid?> DeleteFolder(Guid id) { var folder = await _api.Media.GetFolderByIdAsync(id); if (folder != null) { await _api.Media.DeleteFolderAsync(folder); return folder.ParentId; } return null; } /// <summary> /// Save or update media assets to storage /// </summary> /// <param name="model">Upload model</param> /// <returns>The number of upload managed to be saved or updated</returns> public async Task<int> SaveMedia(MediaUploadModel model) { var uploaded = 0; // Go through all of the uploaded files foreach (var upload in model.Uploads) { if (upload.Length > 0 && !string.IsNullOrWhiteSpace(upload.ContentType)) { using (var stream = upload.OpenReadStream()) { await _api.Media.SaveAsync(new StreamMediaContent { Id = model.Uploads.Count() == 1 ? model.Id : null, FolderId = model.ParentId, Filename = Path.GetFileName(upload.FileName), Data = stream }); uploaded++; } } } return uploaded; } /// <summary> /// Saves the updated meta information for the given media asset. /// </summary> /// <param name="media">The media asset</param> /// <returns>If the meta information was updated successful</returns> public async Task<bool> SaveMeta(MediaListModel.MediaItem media) { var model = await _api.Media.GetByIdAsync(media.Id); if (model != null) { // Only update the meta fields model.Title = media.Title; model.AltText = media.AltText; model.Description = media.Description; foreach (var property in media.Properties) { model.Properties[property.Key] = property.Value; } await _api.Media.SaveAsync(model); return true; } return false; } public async Task<Guid?> DeleteMedia(Guid id) { var media = await _api.Media.GetByIdAsync(id); if (media != null) { await _api.Media.DeleteAsync(media); return media.FolderId; } return null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal abstract partial class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var (succeeded, highlights) = await GetDocumentHighlightsInRemoteProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (succeeded) { return highlights; } return await GetDocumentHighlightsInCurrentProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); } private async Task<(bool succeeded, ImmutableArray<DocumentHighlights> highlights)> GetDocumentHighlightsInRemoteProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var session = await document.Project.Solution.TryCreateCodeAnalysisServiceSessionAsync( RemoteFeatureOptions.DocumentHighlightingEnabled, cancellationToken).ConfigureAwait(false); using (session) { if (session == null) { return (succeeded: false, ImmutableArray<DocumentHighlights>.Empty); } var result = await session.InvokeAsync<ImmutableArray<SerializableDocumentHighlights>>( nameof(IRemoteDocumentHighlights.GetDocumentHighlightsAsync), document.Id, position, documentsToSearch.Select(d => d.Id).ToArray()).ConfigureAwait(false); return (true, result.SelectAsArray(h => h.Rehydrate(document.Project.Solution))); } } private async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsInCurrentProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), document, documentsToSearch, cancellationToken).ConfigureAwait(false); } private static async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { // see whether we can use the symbol as it is var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (currentSemanticModel == semanticModel) { return symbol; } // get symbols from current document again return await SymbolFinder.FindSymbolAtPositionAsync(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( SymbolAndProjectId symbolAndProjectId, Document document, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector( StreamingFindReferencesProgress.Instance); await SymbolFinder.FindReferencesAsync( symbolAndProjectId, document.Project.Solution, progress, documentsToSearch, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), document, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private static bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( IEnumerable<ReferencedSymbol> references, Document startingDocument, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken) { var solution = startingDocument.Project.Solution; references = references.FilterToItemsToShow(); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } var additionalReferences = new List<Location>(); foreach (var currentDocument in documentsToSearch) { // 'documentsToSearch' may contain documents from languages other than our own // (for example cshtml files when we're searching the cs document). Since we're // delegating to a virtual method for this language type, we have to make sure // we only process the document if it's also our language. if (currentDocument.Project.Language == startingDocument.Project.Language) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(currentDocument, symbol, cancellationToken).ConfigureAwait(false)); } } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } protected virtual Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<Location>(); } private static async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, IEnumerable<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<DocumentSpan>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count); foreach (var kvp in tagMap) { var spans = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutableAndFree())); } return list.ToImmutableAndFree(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; case SymbolKind.Parameter: // If it's an indexer parameter, we will have also cascaded to the accessor // one that actually receives the references var containingProperty = symbol.ContainingSymbol as IPropertySymbol; if (containingProperty != null && containingProperty.IsIndexer) { return false; } break; } return true; } private static async Task AddLocationSpan(Location location, Solution solution, HashSet<DocumentSpan> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Document, new HighlightSpan(span.Value.SourceSpan, kind)); } } private static async Task<DocumentSpan?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetDocument(tree); var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? new DocumentSpan(document, token.Span) : new DocumentSpan(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } return null; } } }
using Nancy.Diagnostics; namespace Nancy.Conventions { using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Nancy.Helpers; using Nancy.Responses; /// <summary> /// Helper class for defining directory-based conventions for static contents. /// </summary> public class StaticContentConventionBuilder { private static readonly ConcurrentDictionary<ResponseFactoryCacheKey, Func<NancyContext, Response>> ResponseFactoryCache; private static readonly Regex PathReplaceRegex = new Regex(@"[/\\]", RegexOptions.Compiled); static StaticContentConventionBuilder() { ResponseFactoryCache = new ConcurrentDictionary<ResponseFactoryCacheKey, Func<NancyContext, Response>>(); } /// <summary> /// Adds a directory-based convention for static convention. /// </summary> /// <param name="requestedPath">The path that should be matched with the request.</param> /// <param name="contentPath">The path to where the content is stored in your application, relative to the root. If this is <see langword="null" /> then it will be the same as <paramref name="requestedPath"/>.</param> /// <param name="allowedExtensions">A list of extensions that is valid for the conventions. If not supplied, all extensions are valid.</param> /// <returns>A <see cref="GenericFileResponse"/> instance for the requested static contents if it was found, otherwise <see langword="null"/>.</returns> public static Func<NancyContext, string, Response> AddDirectory(string requestedPath, string contentPath = null, params string[] allowedExtensions) { if (!requestedPath.StartsWith("/")) { requestedPath = string.Concat("/", requestedPath); } return (ctx, root) => { var path = HttpUtility.UrlDecode(ctx.Request.Path); var fileName = GetSafeFileName(path); if (string.IsNullOrEmpty(fileName)) { return null; } var pathWithoutFilename = GetPathWithoutFilename(fileName, path); if (!pathWithoutFilename.StartsWith(requestedPath, StringComparison.OrdinalIgnoreCase)) { (ctx.Trace.TraceLog ?? new NullLog()).WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The requested resource '", path, "' does not match convention mapped to '", requestedPath, "'" ))); return null; } contentPath = GetContentPath(requestedPath, contentPath); if (contentPath.Equals("/")) { throw new ArgumentException("This is not the security vulnerability you are looking for. Mapping static content to the root of your application is not a good idea."); } var responseFactory = ResponseFactoryCache.GetOrAdd(new ResponseFactoryCacheKey(path, root), BuildContentDelegate(ctx, root, requestedPath, contentPath, allowedExtensions)); return responseFactory.Invoke(ctx); }; } /// <summary> /// Adds a file-based convention for static convention. /// </summary> /// <param name="requestedFile">The file that should be matched with the request.</param> /// <param name="contentFile">The file that should be served when the requested path is matched.</param> public static Func<NancyContext, string, Response> AddFile(string requestedFile, string contentFile) { return (ctx, root) => { var path = ctx.Request.Path; if (!path.Equals(requestedFile, StringComparison.OrdinalIgnoreCase)) { ctx.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The requested resource '", path, "' does not match convention mapped to '", requestedFile, "'"))); return null; } var responseFactory = ResponseFactoryCache.GetOrAdd(new ResponseFactoryCacheKey(path, root), BuildContentDelegate(ctx, root, requestedFile, contentFile, ArrayCache.Empty<string>())); return responseFactory.Invoke(ctx); }; } private static string GetSafeFileName(string path) { try { return Path.GetFileName(path); } catch (Exception) { } return null; } private static string GetSafeFullPath(string path) { try { return Path.GetFullPath(path); } catch (Exception) { } return null; } private static string GetContentPath(string requestedPath, string contentPath) { contentPath = contentPath ?? requestedPath; if (!contentPath.StartsWith("/")) { contentPath = string.Concat("/", contentPath); } return contentPath; } private static Func<ResponseFactoryCacheKey, Func<NancyContext, Response>> BuildContentDelegate(NancyContext context, string applicationRootPath, string requestedPath, string contentPath, string[] allowedExtensions) { return pathAndRootPair => { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] Attempting to resolve static content '", pathAndRootPair, "'"))); var extension = Path.GetExtension(pathAndRootPair.Path); if (!string.IsNullOrEmpty(extension)) { extension = extension.Substring(1); } if (allowedExtensions.Length != 0 && !allowedExtensions.Any(e => string.Equals(e.TrimStart(new [] {'.'}), extension, StringComparison.OrdinalIgnoreCase))) { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The requested extension '", extension, "' does not match any of the valid extensions for the convention '", string.Join(",", allowedExtensions), "'"))); return ctx => null; } var transformedRequestPath = GetSafeRequestPath(pathAndRootPair.Path, requestedPath, contentPath); transformedRequestPath = GetEncodedPath(transformedRequestPath); var relativeFileName = Path.Combine(applicationRootPath, transformedRequestPath); var fileName = GetSafeFullPath(relativeFileName); if (fileName == null) { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The request '", relativeFileName, "' contains an invalid path character"))); return ctx => null; } var relatveContentRootPath = Path.Combine(applicationRootPath, GetEncodedPath(contentPath)); var contentRootPath = GetSafeFullPath(relatveContentRootPath); if (contentRootPath == null) { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The request '", fileName, "' is trying to access a path inside the content folder, which contains an invalid path character '", relatveContentRootPath, "'"))); return ctx => null; } if (!IsWithinContentFolder(contentRootPath, fileName)) { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The request '", fileName, "' is trying to access a path outside the content folder '", contentPath, "'"))); return ctx => null; } if (!File.Exists(fileName)) { context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] The requested file '", fileName, "' does not exist"))); return ctx => null; } context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat("[StaticContentConventionBuilder] Returning file '", fileName, "'"))); return ctx => new GenericFileResponse(fileName, ctx); }; } private static string GetEncodedPath(string path) { return PathReplaceRegex.Replace(path.TrimStart(new[] { '/' }), Path.DirectorySeparatorChar.ToString()); } private static string GetPathWithoutFilename(string fileName, string path) { var pathWithoutFileName = path.Replace(fileName, string.Empty); return (pathWithoutFileName.Equals("/")) ? pathWithoutFileName : pathWithoutFileName.TrimEnd(new[] {'/'}); } private static string GetSafeRequestPath(string requestPath, string requestedPath, string contentPath) { var actualContentPath = (contentPath.Equals("/") ? string.Empty : contentPath); if (requestedPath.Equals("/")) { return string.Concat(actualContentPath, requestPath); } var expression = new Regex(Regex.Escape(requestedPath), RegexOptions.IgnoreCase); return expression.Replace(requestPath, actualContentPath, 1); } /// <summary> /// Returns whether the given filename is contained within the content folder /// </summary> /// <param name="contentRootPath">Content root path</param> /// <param name="fileName">Filename requested</param> /// <returns>True if contained within the content root, false otherwise</returns> private static bool IsWithinContentFolder(string contentRootPath, string fileName) { return fileName.StartsWith(contentRootPath, StringComparison.Ordinal); } /// <summary> /// Used to uniquely identify a request. Needed for when two Nancy applications want to serve up static content of the same /// name from within the same AppDomain. /// </summary> private class ResponseFactoryCacheKey : IEquatable<ResponseFactoryCacheKey> { private readonly string path; private readonly string rootPath; public ResponseFactoryCacheKey(string path, string rootPath) { this.path = path; this.rootPath = rootPath; } /// <summary> /// The path of the static content for which this response is being issued /// </summary> public string Path { get { return this.path; } } /// <summary> /// The root folder path of the Nancy application for which this response will be issued /// </summary> public string RootPath { get { return this.rootPath; } } public bool Equals(ResponseFactoryCacheKey other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return string.Equals(this.path, other.path) && string.Equals(this.rootPath, other.rootPath); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((ResponseFactoryCacheKey)obj); } public override int GetHashCode() { unchecked { return ((this.path != null ? this.path.GetHashCode() : 0) * 397) ^ (this.rootPath != null ? this.rootPath.GetHashCode() : 0); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.IO; using System.Linq; using System.Xml.XPath; using Examine; using Examine.LuceneEngine.SearchCriteria; using Examine.Providers; using Lucene.Net.Documents; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Models; using UmbracoExamine; using umbraco; using Umbraco.Core.Cache; using Umbraco.Core.Sync; using Umbraco.Web.Cache; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database /// </summary> /// <remarks> /// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly. /// </remarks> internal class PublishedMediaCache : IPublishedMediaCache { public PublishedMediaCache(ApplicationContext applicationContext) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); _applicationContext = applicationContext; } /// <summary> /// Generally used for unit testing to use an explicit examine searcher /// </summary> /// <param name="applicationContext"></param> /// <param name="searchProvider"></param> /// <param name="indexProvider"></param> internal PublishedMediaCache(ApplicationContext applicationContext, BaseSearchProvider searchProvider, BaseIndexProvider indexProvider) { if (applicationContext == null) throw new ArgumentNullException("applicationContext"); if (searchProvider == null) throw new ArgumentNullException("searchProvider"); if (indexProvider == null) throw new ArgumentNullException("indexProvider"); _applicationContext = applicationContext; _searchProvider = searchProvider; _indexProvider = indexProvider; } static PublishedMediaCache() { InitializeCacheConfig(); } private readonly ApplicationContext _applicationContext; private readonly BaseSearchProvider _searchProvider; private readonly BaseIndexProvider _indexProvider; public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return GetUmbracoMedia(nodeId); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { //TODO: We should be able to look these ids first in Examine! var rootMedia = _applicationContext.Services.MediaService.GetRootMedia(); return rootMedia.Select(m => GetUmbracoMedia(m.Id)); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public bool XPathNavigatorIsNavigable { get { return false; } } public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); } private ExamineManager GetExamineManagerSafe() { try { return ExamineManager.Instance; } catch (TypeInitializationException) { return null; } } private BaseIndexProvider GetIndexProviderSafe() { if (_indexProvider != null) return _indexProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher var indexer = eMgr.IndexProviderCollection["InternalIndexer"]; if (indexer.IndexerData.IncludeNodeTypes.Any() || indexer.IndexerData.ExcludeNodeTypes.Any()) { LogHelper.Warn<PublishedMediaCache>("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + "<IndexSet SetName=\"InternalIndexSet\" IndexPath=\"~/App_Data/TEMP/ExamineIndexes/Internal/\" />"); } return indexer; } catch (Exception ex) { LogHelper.Error<PublishedMediaCache>("Could not retrieve the InternalIndexer", ex); //something didn't work, continue returning null. } } return null; } private BaseSearchProvider GetSearchProviderSafe() { if (_searchProvider != null) return _searchProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.SearchProviderCollection["InternalSearcher"]; } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } catch (NullReferenceException) { //This will occur when the search provider cannot be initialized. In newer examine versions the initialization is lazy and therefore // the manager will return the singleton without throwing initialization errors, however if examine isn't configured correctly a null // reference error will occur because the examine settings are null. } } return null; } private IPublishedContent GetUmbracoMedia(int id) { // this recreates an IPublishedContent and model each time // it is called, but at least it should NOT hit the database // nor Lucene each time, relying on the memory cache instead var cacheValues = GetCacheValues(id, GetUmbracoMediaCacheValues); return cacheValues == null ? null : CreateFromCacheValues(cacheValues); } private CacheValues GetUmbracoMediaCacheValues(int id) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); //the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene. //+(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media var results = searchProvider.Search(filter.Compile()); if (results.Any()) { return ConvertFromSearchResult(results.First()); } } catch (FileNotFoundException ex) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex); } } LogHelper.Warn<PublishedMediaCache>( "Could not retrieve media {0} from Examine index, reverting to looking up media via legacy library.GetMedia method", () => id); var media = global::umbraco.library.GetMedia(id, false); return ConvertFromXPathNodeIterator(media, id); } internal CacheValues ConvertFromXPathNodeIterator(XPathNodeIterator media, int id) { if (media != null && media.Current != null) { return media.Current.Name.InvariantEquals("error") ? null : ConvertFromXPathNavigator(media.Current); } LogHelper.Warn<PublishedMediaCache>( "Could not retrieve media {0} from Examine index or from legacy library.GetMedia method", () => id); return null; } internal CacheValues ConvertFromSearchResult(SearchResult searchResult) { //NOTE: Some fields will not be included if the config section for the internal index has been //mucked around with. It should index everything and so the index definition should simply be: // <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" /> var values = new Dictionary<string, string>(searchResult.Fields); //we need to ensure some fields exist, because of the above issue if (!new []{"template", "templateId"}.Any(values.ContainsKey)) values.Add("template", 0.ToString()); if (!new[] { "sortOrder" }.Any(values.ContainsKey)) values.Add("sortOrder", 0.ToString()); if (!new[] { "urlName" }.Any(values.ContainsKey)) values.Add("urlName", ""); if (!new[] { "nodeType" }.Any(values.ContainsKey)) values.Add("nodeType", 0.ToString()); if (!new[] { "creatorName" }.Any(values.ContainsKey)) values.Add("creatorName", ""); if (!new[] { "writerID" }.Any(values.ContainsKey)) values.Add("writerID", 0.ToString()); if (!new[] { "creatorID" }.Any(values.ContainsKey)) values.Add("creatorID", 0.ToString()); if (!new[] { "createDate" }.Any(values.ContainsKey)) values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss")); if (!new[] { "level" }.Any(values.ContainsKey)) { values.Add("level", values["__Path"].Split(',').Length.ToString()); } return new CacheValues { Values = values, FromExamine = true }; //var content = new DictionaryPublishedContent(values, // d => d.ParentId != -1 //parent should be null if -1 // ? GetUmbracoMedia(d.ParentId) // : null, // //callback to return the children of the current node // d => GetChildrenMedia(d.Id), // GetProperty, // true); //return content.CreateModel(); } internal CacheValues ConvertFromXPathNavigator(XPathNavigator xpath, bool forceNav = false) { if (xpath == null) throw new ArgumentNullException("xpath"); var values = new Dictionary<string, string> {{"nodeName", xpath.GetAttribute("nodeName", "")}}; if (!UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) { values["nodeTypeAlias"] = xpath.Name; } var result = xpath.SelectChildren(XPathNodeType.Element); //add the attributes e.g. id, parentId etc if (result.Current != null && result.Current.HasAttributes) { if (result.Current.MoveToFirstAttribute()) { //checking for duplicate keys because of the 'nodeTypeAlias' might already be added above. if (!values.ContainsKey(result.Current.Name)) { values[result.Current.Name] = result.Current.Value; } while (result.Current.MoveToNextAttribute()) { if (!values.ContainsKey(result.Current.Name)) { values[result.Current.Name] = result.Current.Value; } } result.Current.MoveToParent(); } } //add the user props while (result.MoveNext()) { if (result.Current != null && !result.Current.HasAttributes) { string value = result.Current.Value; if (string.IsNullOrEmpty(value)) { if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0) { value = result.Current.OuterXml; } } values[result.Current.Name] = value; } } return new CacheValues { Values = values, XPath = forceNav ? xpath : null // outside of tests we do NOT want to cache the navigator! }; //var content = new DictionaryPublishedContent(values, // d => d.ParentId != -1 //parent should be null if -1 // ? GetUmbracoMedia(d.ParentId) // : null, // //callback to return the children of the current node based on the xml structure already found // d => GetChildrenMedia(d.Id, xpath), // GetProperty, // false); //return content.CreateModel(); } /// <summary> /// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists /// in the results, if it does not, then we'll have to revert to looking up in the db. /// </summary> /// <param name="dd"> </param> /// <param name="alias"></param> /// <returns></returns> private IPublishedProperty GetProperty(DictionaryPublishedContent dd, string alias) { //lets check if the alias does not exist on the document. //NOTE: Examine will not index empty values and we do not output empty XML Elements to the cache - either of these situations // would mean that the property is missing from the collection whether we are getting the value from Examine or from the library media cache. if (dd.Properties.All(x => x.PropertyTypeAlias.InvariantEquals(alias) == false)) { return null; } if (dd.LoadedFromExamine) { //We are going to check for a special field however, that is because in some cases we store a 'Raw' //value in the index such as for xml/html. var rawValue = dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias)); return rawValue ?? dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } //if its not loaded from examine, then just return the property return dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } /// <summary> /// A Helper methods to return the children for media whther it is based on examine or xml /// </summary> /// <param name="parentId"></param> /// <param name="xpath"></param> /// <returns></returns> private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null) { //if there is no navigator, try examine first, then re-look it up if (xpath == null) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.ParentId(parentId).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); //the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene. //+(+parentId:3113 -__Path:-1,-21,*) +__IndexType:media ISearchResults results; //we want to check if the indexer for this searcher has "sortOrder" flagged as sortable. //if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower). var indexer = GetIndexProviderSafe(); var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting); if (useLuceneSort) { //we have a sortOrder field declared to be sorted, so we'll use Examine results = searchProvider.Search( filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile()); } else { results = searchProvider.Search(filter.Compile()); } if (results.Any()) { // var medias = results.Select(ConvertFromSearchResult); var medias = results.Select(x => { int nid; if (int.TryParse(x["__NodeId"], out nid) == false && int.TryParse(x["NodeId"], out nid) == false) throw new Exception("Failed to extract NodeId from search result."); var cacheValues = GetCacheValues(nid, id => ConvertFromSearchResult(x)); return CreateFromCacheValues(cacheValues); }); return useLuceneSort ? medias : medias.OrderBy(x => x.SortOrder); } else { //if there's no result then return null. Previously we defaulted back to library.GetMedia below //but this will always get called for when we are getting descendents since many items won't have //children and then we are hitting the database again! //So instead we're going to rely on Examine to have the correct results like it should. return Enumerable.Empty<IPublishedContent>(); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia } } //falling back to get media var media = library.GetMedia(parentId, true); if (media != null && media.Current != null) { xpath = media.Current; } else { return Enumerable.Empty<IPublishedContent>(); } } var mediaList = new List<IPublishedContent>(); // this is so bad, really var item = xpath.Select("//*[@id='" + parentId + "']"); if (item.Current == null) return Enumerable.Empty<IPublishedContent>(); var items = item.Current.SelectChildren(XPathNodeType.Element); // and this does not work, because... meh //var q = "//* [@id='" + parentId + "']/* [@id]"; //var items = xpath.Select(q); foreach (XPathNavigator itemm in items) { int id; if (int.TryParse(itemm.GetAttribute("id", ""), out id) == false) continue; // wtf? var captured = itemm; var cacheValues = GetCacheValues(id, idd => ConvertFromXPathNavigator(captured)); mediaList.Add(CreateFromCacheValues(cacheValues)); } ////The xpath might be the whole xpath including the current ones ancestors so we need to select the current node //var item = xpath.Select("//*[@id='" + parentId + "']"); //if (item.Current == null) //{ // return Enumerable.Empty<IPublishedContent>(); //} //var children = item.Current.SelectChildren(XPathNodeType.Element); //foreach(XPathNavigator x in children) //{ // //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but // // will leave it here as it must have done something! // if (x.Name != "contents") // { // //make sure it's actually a node, not a property // if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) && // !string.IsNullOrEmpty(x.GetAttribute("id", ""))) // { // mediaList.Add(ConvertFromXPathNavigator(x)); // } // } //} return mediaList; } /// <summary> /// An IPublishedContent that is represented all by a dictionary. /// </summary> /// <remarks> /// This is a helper class and definitely not intended for public use, it expects that all of the values required /// to create an IPublishedContent exist in the dictionary by specific aliases. /// </remarks> internal class DictionaryPublishedContent : PublishedContentBase { // note: I'm not sure this class fully complies with IPublishedContent rules especially // I'm not sure that _properties contains all properties including those without a value, // neither that GetProperty will return a property without a value vs. null... @zpqrtbnk // List of properties that will appear in the XML and do not match // anything in the ContentType, so they must be ignored. private static readonly string[] IgnoredKeys = { "version", "isDoc", "key" }; public DictionaryPublishedContent( IDictionary<string, string> valueDictionary, Func<int, IPublishedContent> getParent, Func<int, XPathNavigator, IEnumerable<IPublishedContent>> getChildren, Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty, XPathNavigator nav, bool fromExamine) { if (valueDictionary == null) throw new ArgumentNullException("valueDictionary"); if (getParent == null) throw new ArgumentNullException("getParent"); if (getProperty == null) throw new ArgumentNullException("getProperty"); _getParent = new Lazy<IPublishedContent>(() => getParent(ParentId)); _getChildren = new Lazy<IEnumerable<IPublishedContent>>(() => getChildren(Id, nav)); _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! // wtf are we dealing with templates for medias?! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection<IPublishedProperty>(); //handle content type properties //make sure we create them even if there's no value foreach (var propertyType in _contentType.PropertyTypes) { var alias = propertyType.PropertyTypeAlias; _keysAdded.Add(alias); string value; const bool isPreviewing = false; // false :: never preview a media var property = valueDictionary.TryGetValue(alias, out value) == false ? new XmlPublishedProperty(propertyType, isPreviewing) : new XmlPublishedProperty(propertyType, isPreviewing, value); _properties.Add(property); } //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => _keysAdded.Contains(x.Key) == false // not already processed && IgnoredKeys.Contains(x.Key) == false)) // not ignorable { if (i.Key.InvariantStartsWith("__")) { // no type for that one, dunno how to convert IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty); _properties.Add(property); } else { // this is a property that does not correspond to anything, ignore and log LogHelper.Warn<PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); } } } private DateTime ParseDateTimeValue(string val) { if (LoadedFromExamine) { try { //we might need to parse the date time using Lucene converters return DateTools.StringToDate(val); } catch (FormatException) { //swallow exception, its not formatted correctly so revert to just trying to parse } } return DateTime.Parse(val); } /// <summary> /// Flag to get/set if this was laoded from examine cache /// </summary> internal bool LoadedFromExamine { get; private set; } //private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent; private readonly Lazy<IPublishedContent> _getParent; //private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren; private readonly Lazy<IEnumerable<IPublishedContent>> _getChildren; private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty; /// <summary> /// Returns 'Media' as the item type /// </summary> public override PublishedItemType ItemType { get { return PublishedItemType.Media; } } public override IPublishedContent Parent { get { return _getParent.Value; } } public int ParentId { get; private set; } public override int Id { get { return _id; } } public override int TemplateId { get { //TODO: should probably throw a not supported exception since media doesn't actually support this. return _templateId; } } public override int SortOrder { get { return _sortOrder; } } public override string Name { get { return _name; } } public override string UrlName { get { return _urlName; } } public override string DocumentTypeAlias { get { return _documentTypeAlias; } } public override int DocumentTypeId { get { return _documentTypeId; } } public override string WriterName { get { return _writerName; } } public override string CreatorName { get { return _creatorName; } } public override int WriterId { get { return _writerId; } } public override int CreatorId { get { return _creatorId; } } public override string Path { get { return _path; } } public override DateTime CreateDate { get { return _createDate; } } public override DateTime UpdateDate { get { return _updateDate; } } public override Guid Version { get { return _version; } } public override int Level { get { return _level; } } public override bool IsDraft { get { return false; } } public override ICollection<IPublishedProperty> Properties { get { return _properties; } } public override IEnumerable<IPublishedContent> Children { get { return _getChildren.Value; } } public override IPublishedProperty GetProperty(string alias) { return _getProperty(this, alias); } public override PublishedContentType ContentType { get { return _contentType; } } // override to implement cache // cache at context level, ie once for the whole request // but cache is not shared by requests because we wouldn't know how to clear it public override IPublishedProperty GetProperty(string alias, bool recurse) { if (recurse == false) return GetProperty(alias); IPublishedProperty property; string key = null; var cache = UmbracoContextCache.Current; if (cache != null) { key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant()); object o; if (cache.TryGetValue(key, out o)) { property = o as IPublishedProperty; if (property == null) throw new InvalidOperationException("Corrupted cache."); return property; } } // else get it for real, no cache property = base.GetProperty(alias, true); if (cache != null) cache[key] = property; return property; } private readonly List<string> _keysAdded = new List<string>(); private int _id; private int _templateId; private int _sortOrder; private string _name; private string _urlName; private string _documentTypeAlias; private int _documentTypeId; private string _writerName; private string _creatorName; private int _writerId; private int _creatorId; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private int _level; private readonly ICollection<IPublishedProperty> _properties; private readonly PublishedContentType _contentType; private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys) { var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null); if (key == null) { throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements"); } setProperty(valueDictionary[key]); _keysAdded.Add(key); } } // REFACTORING // caching the basic atomic values - and the parent id // but NOT caching actual parent nor children and NOT even // the list of children ids - BUT caching the path internal class CacheValues { public IDictionary<string, string> Values { get; set; } public XPathNavigator XPath { get; set; } public bool FromExamine { get; set; } } public const string PublishedMediaCacheKey = "MediaCacheMeh."; private const int PublishedMediaCacheTimespanSeconds = 4 * 60; // 4 mins private static TimeSpan _publishedMediaCacheTimespan; private static bool _publishedMediaCacheEnabled; private static void InitializeCacheConfig() { var value = ConfigurationManager.AppSettings["Umbraco.PublishedMediaCache.Seconds"]; int seconds; if (int.TryParse(value, out seconds) == false) seconds = PublishedMediaCacheTimespanSeconds; if (seconds > 0) { _publishedMediaCacheEnabled = true; _publishedMediaCacheTimespan = TimeSpan.FromSeconds(seconds); } else { _publishedMediaCacheEnabled = false; } } internal IPublishedContent CreateFromCacheValues(CacheValues cacheValues) { var content = new DictionaryPublishedContent( cacheValues.Values, parentId => parentId < 0 ? null : GetUmbracoMedia(parentId), GetChildrenMedia, GetProperty, cacheValues.XPath, // though, outside of tests, that should be null cacheValues.FromExamine ); return content.CreateModel(); } private static CacheValues GetCacheValues(int id, Func<int, CacheValues> func) { if (_publishedMediaCacheEnabled == false) return func(id); var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache; var key = PublishedMediaCacheKey + id; return (CacheValues) cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan); } internal static void ClearCache(int id) { var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache; var sid = id.ToString(); var key = PublishedMediaCacheKey + sid; // we do clear a lot of things... but the cache refresher is somewhat // convoluted and it's hard to tell what to clear exactly ;-( // clear the parent - NOT (why?) //var exist = (CacheValues) cache.GetCacheItem(key); //if (exist != null) // cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID")); // clear the item cache.ClearCacheItem(key); // clear all children - in case we moved and their path has changed var fid = "/" + sid + "/"; cache.ClearCacheObjectTypes<CacheValues>((k, v) => GetValuesValue(v.Values, "path", "__Path").Contains(fid)); } private static string GetValuesValue(IDictionary<string, string> d, params string[] keys) { string value = null; var ignored = keys.Any(x => d.TryGetValue(x, out value)); return value ?? ""; } } }
namespace Mapbox.IO.Compression { using System; using System.Diagnostics; internal class FastEncoderWindow { private byte[] window; // complete bytes window private int bufPos; // the start index of uncompressed bytes private int bufEnd; // the end index of uncompressed bytes // Be very careful about increasing the window size; the code tables will have to // be updated, since they assume that extra_distance_bits is never larger than a // certain size. const int FastEncoderHashShift = 4; const int FastEncoderHashtableSize = 2048; const int FastEncoderHashMask = FastEncoderHashtableSize-1; const int FastEncoderWindowSize = 8192; const int FastEncoderWindowMask = FastEncoderWindowSize - 1; const int FastEncoderMatch3DistThreshold = 16384; internal const int MaxMatch = 258; internal const int MinMatch = 3; // Following constants affect the search, // they should be modifiable if we support different compression levels in future. const int SearchDepth = 32; const int GoodLength = 4; const int NiceLength = 32; const int LazyMatchThreshold = 6; // Hashtable structure private ushort[] prev; // next most recent occurance of chars with same hash value private ushort[] lookup; // hash table to find most recent occurance of chars with same hash value public FastEncoderWindow() { ResetWindow(); } public int BytesAvailable { // uncompressed bytes get { Debug.Assert(bufEnd - bufPos >= 0, "Ending pointer can't be in front of starting pointer!"); return bufEnd - bufPos; } } public DeflateInput UnprocessedInput { get { DeflateInput input = new DeflateInput(); input.Buffer = window; input.StartIndex = bufPos; input.Count = bufEnd - bufPos; return input; } } public void FlushWindow() { ResetWindow(); } private void ResetWindow() { window = new byte[2 * FastEncoderWindowSize + MaxMatch + 4]; prev = new ushort[FastEncoderWindowSize + MaxMatch]; lookup = new ushort[FastEncoderHashtableSize]; bufPos = FastEncoderWindowSize; bufEnd = bufPos; } public int FreeWindowSpace { // Free space in the window get { return 2 * FastEncoderWindowSize - bufEnd; } } // copy bytes from input buffer into window public void CopyBytes(byte[] inputBuffer, int startIndex, int count) { Array.Copy(inputBuffer, startIndex, window, bufEnd, count); bufEnd += count; } // slide the history window to the left by FastEncoderWindowSize bytes public void MoveWindows() { int i; Debug.Assert(bufPos == 2*FastEncoderWindowSize, "only call this at the end of the window"); // verify that the hash table is correct VerifyHashes(); // Debug only code Array.Copy(window, bufPos - FastEncoderWindowSize, window, 0, FastEncoderWindowSize); // move all the hash pointers back for (i = 0; i < FastEncoderHashtableSize; i++) { int val = ((int) lookup[i]) - FastEncoderWindowSize; if (val <= 0) { // too far away now? then set to zero lookup[i] = (ushort) 0; } else { lookup[i] = (ushort) val; } } // prev[]'s are absolute pointers, not relative pointers, so we have to move them back too // making prev[]'s into relative pointers poses problems of its own for (i = 0; i < FastEncoderWindowSize; i++) { long val = ((long) prev[i]) - FastEncoderWindowSize; if (val <= 0) { prev[i] = (ushort) 0; } else { prev[i] = (ushort) val; } } #if DEBUG // For debugging, wipe the window clean, so that if there is a bug in our hashing, // the hash pointers will now point to locations which are not valid for the hash value // (and will be caught by our ASSERTs). Array.Clear(window, FastEncoderWindowSize, window.Length - FastEncoderWindowSize); #endif VerifyHashes(); // debug: verify hash table is correct bufPos = FastEncoderWindowSize; bufEnd = bufPos; } private uint HashValue(uint hash, byte b) { return(hash << FastEncoderHashShift) ^ b; } // insert string into hash table and return most recent location of same hash value private uint InsertString(ref uint hash) { // Note we only use the lowest 11 bits of the hash vallue (hash table size is 11). // This enables fast calculation of hash value for the input string. // If we want to get the next hash code starting at next position, // we can just increment bufPos and call this function. hash = HashValue( hash, window[bufPos+2] ); // Need to assert the hash value uint search = lookup[hash & FastEncoderHashMask]; lookup[hash & FastEncoderHashMask] = (ushort) bufPos; prev[bufPos & FastEncoderWindowMask] = (ushort) search; return search; } // // insert strings into hashtable // Arguments: // hash : intial hash value // matchLen : 1 + number of strings we need to insert. // private void InsertStrings(ref uint hash, int matchLen) { Debug.Assert(matchLen > 0, "Invalid match Len!"); if (bufEnd - bufPos <= matchLen) { bufPos += (matchLen-1); } else { while (--matchLen > 0) { InsertString(ref hash); bufPos++; } } } // // Find out what we should generate next. It can be a symbol, a distance/length pair // or a symbol followed by distance/length pair // internal bool GetNextSymbolOrMatch(Match match) { Debug.Assert(bufPos >= FastEncoderWindowSize && bufPos < (2*FastEncoderWindowSize), "Invalid Buffer Position!"); // initialise the value of the hash, no problem if locations bufPos, bufPos+1 // are invalid (not enough data), since we will never insert using that hash value uint hash = HashValue( 0 , window[bufPos]); hash = HashValue( hash , window[bufPos + 1]); int matchLen; int matchPos = 0; VerifyHashes(); // Debug only code if (bufEnd - bufPos <= 3) { // The hash value becomes corrupt when we get within 3 characters of the end of the // input window, since the hash value is based on 3 characters. We just stop // inserting into the hash table at this point, and allow no matches. matchLen = 0; } else { // insert string into hash table and return most recent location of same hash value int search = (int)InsertString(ref hash); // did we find a recent location of this hash value? if (search != 0) { // yes, now find a match at what we'll call position X matchLen = FindMatch(search, out matchPos, SearchDepth, NiceLength); // truncate match if we're too close to the end of the input window if (bufPos + matchLen > bufEnd) matchLen = bufEnd - bufPos; } else { // no most recent location found matchLen = 0; } } if (matchLen < MinMatch) { // didn't find a match, so output unmatched char match.State = MatchState.HasSymbol; match.Symbol = window[bufPos]; bufPos++; } else { // bufPos now points to X+1 bufPos++; // is this match so good (long) that we should take it automatically without // checking X+1 ? if (matchLen <= LazyMatchThreshold) { int nextMatchLen; int nextMatchPos = 0; // search at position X+1 int search = (int)InsertString(ref hash); // no, so check for a better match at X+1 if (search != 0) { nextMatchLen = FindMatch(search, out nextMatchPos, matchLen < GoodLength ? SearchDepth : (SearchDepth >> 2),NiceLength); // truncate match if we're too close to the end of the window // note: nextMatchLen could now be < MinMatch if (bufPos + nextMatchLen > bufEnd) { nextMatchLen = bufEnd - bufPos; } } else { nextMatchLen = 0; } // right now X and X+1 are both inserted into the search tree if (nextMatchLen > matchLen) { // since nextMatchLen > matchLen, it can't be < MinMatch here // match at X+1 is better, so output unmatched char at X match.State = MatchState.HasSymbolAndMatch; match.Symbol = window[bufPos-1]; match.Position = nextMatchPos; match.Length = nextMatchLen; // insert remainder of second match into search tree // example: (*=inserted already) // // X X+1 X+2 X+3 X+4 // * * // nextmatchlen=3 // bufPos // // If nextMatchLen == 3, we want to perform 2 // insertions (at X+2 and X+3). However, first we must // inc bufPos. // bufPos++; // now points to X+2 matchLen = nextMatchLen; InsertStrings(ref hash, matchLen); } else { // match at X is better, so take it match.State = MatchState.HasMatch; match.Position = matchPos; match.Length = matchLen; // Insert remainder of first match into search tree, minus the first // two locations, which were inserted by the FindMatch() calls. // // For example, if matchLen == 3, then we've inserted at X and X+1 // already (and bufPos is now pointing at X+1), and now we need to insert // only at X+2. // matchLen--; bufPos++; // now bufPos points to X+2 InsertStrings(ref hash, matchLen); } } else { // match_length >= good_match // in assertion: bufPos points to X+1, location X inserted already // first match is so good that we're not even going to check at X+1 match.State = MatchState.HasMatch; match.Position = matchPos; match.Length = matchLen; // insert remainder of match at X into search tree InsertStrings(ref hash, matchLen); } } if (bufPos == 2*FastEncoderWindowSize) { MoveWindows(); } return true; } // // Find a match starting at specified position and return length of match // Arguments: // search : where to start searching // matchPos : return match position here // searchDepth : # links to traverse // NiceLength : stop immediately if we find a match >= NiceLength // int FindMatch(int search, out int matchPos, int searchDepth, int niceLength ) { Debug.Assert(bufPos >= 0 && bufPos < 2*FastEncoderWindowSize, "Invalid Buffer position!"); Debug.Assert(search < bufPos, "Invalid starting search point!"); Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos)); int bestMatch = 0; // best match length found so far int bestMatchPos = 0; // absolute match position of best match found // the earliest we can look int earliest = bufPos - FastEncoderWindowSize; Debug.Assert(earliest >= 0, "bufPos is less than FastEncoderWindowSize!"); byte wantChar = window[bufPos]; while (search > earliest) { // make sure all our hash links are valid Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos), "Corrupted hash link!"); // Start by checking the character that would allow us to increase the match // length by one. This improves performance quite a bit. if (window[search + bestMatch] == wantChar) { int j; // Now make sure that all the other characters are correct for (j = 0; j < MaxMatch; j++) { if (window[bufPos+j] != window[search+j]) break; } if (j > bestMatch) { bestMatch = j; bestMatchPos = search; // absolute position if (j > NiceLength) break; wantChar = window[bufPos+j]; } } if (--searchDepth == 0) { break; } Debug.Assert(prev[search & FastEncoderWindowMask] < search, "we should always go backwards!"); search = prev[search & FastEncoderWindowMask]; } // doesn't necessarily mean we found a match; bestMatch could be > 0 and < MinMatch matchPos = bufPos - bestMatchPos - 1; // convert absolute to relative position // don't allow match length 3's which are too far away to be worthwhile if (bestMatch == 3 && matchPos >= FastEncoderMatch3DistThreshold) { return 0; } Debug.Assert(bestMatch < MinMatch || matchPos < FastEncoderWindowSize, "Only find match inside FastEncoderWindowSize"); return bestMatch; } [Conditional("DEBUG")] void VerifyHashes() { for (int i = 0; i < FastEncoderHashtableSize; i++) { ushort where = lookup[i]; ushort nextWhere; while (where != 0 && bufPos - where < FastEncoderWindowSize) { Debug.Assert(RecalculateHash(where) == i, "Incorrect Hashcode!"); nextWhere = prev[where & FastEncoderWindowMask]; if (bufPos - nextWhere >= FastEncoderWindowSize) { break; } Debug.Assert(nextWhere < where, "pointer is messed up!"); where = nextWhere; } } } // can't use conditional attribute here. uint RecalculateHash(int position) { return (uint)(((window[position] << (2*FastEncoderHashShift)) ^ (window[position+1] << FastEncoderHashShift) ^ (window[position+2])) & FastEncoderHashMask); } } }
using System; using System.Text; using System.Web; using Umbraco.Core; using Umbraco.Core.Configuration; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Web { public static class UriUtility { static string _appPath; static string _appPathPrefix; static UriUtility() { SetAppDomainAppVirtualPath(HttpRuntime.AppDomainAppVirtualPath); } // internal for unit testing only internal static void SetAppDomainAppVirtualPath(string appPath) { _appPath = appPath ?? "/"; _appPathPrefix = _appPath; if (_appPathPrefix == "/") _appPathPrefix = String.Empty; } // will be "/" or "/foo" public static string AppPath { get { return _appPath; } } // will be "" or "/foo" public static string AppPathPrefix { get { return _appPathPrefix; } } // adds the virtual directory if any // see also VirtualPathUtility.ToAbsolute public static string ToAbsolute(string url) { //return ResolveUrl(url); url = url.TrimStart('~'); return _appPathPrefix + url; } // strips the virtual directory if any // see also VirtualPathUtility.ToAppRelative public static string ToAppRelative(string virtualPath) { if (virtualPath.InvariantStartsWith(_appPathPrefix)) virtualPath = virtualPath.Substring(_appPathPrefix.Length); if (virtualPath.Length == 0) virtualPath = "/"; return virtualPath; } // maps an internal umbraco uri to a public uri // ie with virtual directory, .aspx if required... public static Uri UriFromUmbraco(Uri uri) { var path = uri.GetSafeAbsolutePath(); if (path != "/") { if (!GlobalSettings.UseDirectoryUrls) path += ".aspx"; else if (UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash) path += "/"; } path = ToAbsolute(path); return uri.Rewrite(path); } // maps a public uri to an internal umbraco uri // ie no virtual directory, no .aspx, lowercase... public static Uri UriToUmbraco(Uri uri) { // note: no need to decode uri here because we're returning a uri // so it will be re-encoded anyway var path = uri.GetSafeAbsolutePath(); path = path.ToLower(); path = ToAppRelative(path); // strip vdir if any //we need to check if the path is /default.aspx because this will occur when using a //web server pre IIS 7 when requesting the root document //if this is the case we need to change it to '/' if (path.StartsWith("/default.aspx", StringComparison.InvariantCultureIgnoreCase)) { string rempath = path.Substring("/default.aspx".Length, path.Length - "/default.aspx".Length); path = rempath.StartsWith("/") ? rempath : "/" + rempath; } if (path != "/") { path = path.TrimEnd('/'); } //if any part of the path contains .aspx, replace it with nothing. //sometimes .aspx is not at the end since we might have /home/sub1.aspx/customtemplate path = path.Replace(".aspx", ""); return uri.Rewrite(path); } #region ResolveUrl // http://www.codeproject.com/Articles/53460/ResolveUrl-in-ASP-NET-The-Perfect-Solution // note // if browsing http://example.com/sub/page1.aspx then // ResolveUrl("page2.aspx") returns "/page2.aspx" // Page.ResolveUrl("page2.aspx") returns "/sub/page2.aspx" (relative...) // public static string ResolveUrl(string relativeUrl) { if (relativeUrl == null) throw new ArgumentNullException("relativeUrl"); if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\') return relativeUrl; int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal); if (idxOfScheme != -1) { int idxOfQM = relativeUrl.IndexOf('?'); if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl; } StringBuilder sbUrl = new StringBuilder(); sbUrl.Append(_appPathPrefix); if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/'); // found question mark already? query string, do not touch! bool foundQM = false; bool foundSlash; // the latest char was a slash? if (relativeUrl.Length > 1 && relativeUrl[0] == '~' && (relativeUrl[1] == '/' || relativeUrl[1] == '\\')) { relativeUrl = relativeUrl.Substring(2); foundSlash = true; } else foundSlash = false; foreach (char c in relativeUrl) { if (!foundQM) { if (c == '?') foundQM = true; else { if (c == '/' || c == '\\') { if (foundSlash) continue; else { sbUrl.Append('/'); foundSlash = true; continue; } } else if (foundSlash) foundSlash = false; } } sbUrl.Append(c); } return sbUrl.ToString(); } #endregion #region Uri string utilities public static bool HasScheme(string uri) { return uri.IndexOf("://") > 0; } public static string StartWithScheme(string uri) { return StartWithScheme(uri, null); } public static string StartWithScheme(string uri, string scheme) { return HasScheme(uri) ? uri : String.Format("{0}://{1}", scheme ?? Uri.UriSchemeHttp, uri); } public static string EndPathWithSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.EnsureEndsWith('/'); if (pos > 0) path += uri.Substring(pos); return path; } public static string TrimPathEndSlash(string uri) { var pos1 = Math.Max(0, uri.IndexOf('?')); var pos2 = Math.Max(0, uri.IndexOf('#')); var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; path = path.TrimEnd('/'); if (pos > 0) path += uri.Substring(pos); return path; } #endregion /// <summary> /// Returns an faull url with the host, port, etc... /// </summary> /// <param name="absolutePath">An absolute path (i.e. starts with a '/' )</param> /// <param name="httpContext"> </param> /// <returns></returns> /// <remarks> /// Based on http://stackoverflow.com/questions/3681052/get-absolute-url-from-relative-path-refactored-method /// </remarks> internal static Uri ToFullUrl(string absolutePath, HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (String.IsNullOrEmpty(absolutePath)) throw new ArgumentNullException("absolutePath"); if (!absolutePath.StartsWith("/")) throw new FormatException("The absolutePath specified does not start with a '/'"); return new Uri(absolutePath, UriKind.Relative).MakeAbsolute(httpContext.Request.Url); } } }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Text; using FluentWebControls.Extensions; using FluentWebControls.Interfaces; namespace FluentWebControls { public class GridData { public GridData(IPagedListParameters pagedListParameters, string controllerName, string controllerExtension, string actionName, IEnumerable<IGridColumn> gridColumns, int total, IEnumerable<DropDownListData> filters, int rowCount) { Filters = filters; PagedListParameters = pagedListParameters; ControllerName = controllerName; ControllerExtension = controllerExtension; ActionName = actionName; GridColumns = gridColumns; Total = total; RowCount = rowCount; } public string ActionName { get; } public string ControllerExtension { get; } public string ControllerName { get; } public IEnumerable<DropDownListData> Filters { get; } public IEnumerable<IGridColumn> GridColumns { get; } public IPagedListParameters PagedListParameters { get; } public int RowCount { get; } public int Total { get; } } public class GridData<T> { private readonly List<DropDownListData> _filters = new List<DropDownListData>(); private readonly List<IGridColumn> _gridColumns = new List<IGridColumn>(); private readonly IEnumerable<T> _items; public GridData(IPagedListParameters pagedListParameters, string controllerName, string actionName, IEnumerable<T> items, int total) { _items = items; Total = total; PagedListParameters = pagedListParameters; ControllerName = controllerName; ActionName = actionName; } public string ActionName { get; } protected virtual bool ClientSideSortingEnabled => false; public string ControllerExtension { get; set; } public string ControllerName { get; } protected IEnumerable<DropDownListData> Filters => _filters; public IEnumerable<IGridColumn> GridColumns => _gridColumns; public IPagedListParameters PagedListParameters { get; set; } public int Total { get; set; } public void AddColumn(SortableColumn<T> column) { AddColumn(column, ActionName, column.GetItemValue); } public void AddColumn(RegularColumn<T> column) { AddColumn(column, ActionName, column.GetItemValue); } public void AddColumn(GridCommandColumn<T> column) { AddColumn(column, column.ActionName, column.GetItemId); } private void AddColumn(GridColumnBuilder column, string actionName, Func<T, string> getItemValue) { _gridColumns.Add( new GridColumn(column.Type, column.ColumnHeader, column.FieldName, column.Align, column.IsDefaultSortColumn, column.IsClientSideSortable, column.Sorter, actionName, _items.Select(getItemValue).ToList()) ); } public void AddFilter(DropDownListData filter) { _filters.Add(filter); } protected string BuildFilters() { var sb = new StringBuilder(); if (_filters.Any()) { sb.Append("<table width='700px'><tr>"); foreach (var filter in _filters) { sb.Append("<td align='center'>"); sb.Append(filter); sb.Append("</td>"); } sb.Append("</tr></table>"); } return sb.ToString(); } protected string BuildHeaderColumns() { var sb = new StringBuilder(); var columnNumber = 0; foreach (var column in GridColumns) { sb.AppendFormat("<th{0}{1}", AlignAttribute.Center, ClientSideSortingEnabled && !column.IsClientSideSortable ? " class=\"{sorter: false}\"" : ""); var columnSorter = !column.Sorter.IsNullOrEmpty(true) ? " class=\"{sorter: '" + column.Sorter + "'}\"" : ""; sb.AppendFormat("{0}>", columnSorter); switch (column.Type) { case GridColumnType.Sortable: sb.Append(Link .To(ControllerName, ControllerExtension, ActionName) .WithLinkText(column.ColumnHeader) .WithQueryStringData(() => PagedListParameters.SortDirection, GetNextSortDirection(column.FieldName, column.IsDefaultSortColumn)) .WithQueryStringData(() => PagedListParameters.SortField, column.FieldName) .WithQueryStringData(_filters.Select(f => new KeyValuePair<string, string>(((IWebControl)f).Id, ((IDropDownListData)f).SelectedValue))) .WithId("th" + columnNumber) ); break; case GridColumnType.Command: sb.Append("&nbsp;"); break; case GridColumnType.Regular: sb.Append(column.ColumnHeader); break; default: throw new ArgumentOutOfRangeException(); } sb.AppendLine("</th>"); columnNumber++; } return sb.ToString(); } private void BuildRow(int rowId, StringBuilder sb) { sb.Append("<tr>"); foreach (var column in GridColumns) { sb.AppendFormat("<td style='white-space: nowrap'{0}>", column.Align); switch (column.Type) { case GridColumnType.Regular: case GridColumnType.Sortable: sb.Append(column[rowId]); break; case GridColumnType.Command: sb.Append(Link .To(ControllerName, ControllerExtension, column.ActionName) .WithLinkText(column.ActionName) .WithQueryStringData(column.FieldName, column[rowId])); break; default: throw new ArgumentOutOfRangeException(); } sb.Append("</td>"); } sb.AppendLine("</tr>"); } protected string BuildRows() { var sb = new StringBuilder(); var count = _items.Count(); foreach (var rowId in Enumerable.Range(0, count)) { BuildRow(rowId, sb); } return sb.ToString(); } private string GetNextSortDirection(string fieldName, bool isDefaultSortColumn) { if (PagedListParameters.SortField == fieldName) { return string.Compare(PagedListParameters.SortDirection, "Asc", true) == 0 ? "Desc" : "Asc"; } return isDefaultSortColumn ? "Desc" : "Asc"; } } }
// THIS CODE AND INFORMATION IS 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. // // Copyright (c) Microsoft Corporation. All rights reserved using System; using System.Linq; using Prismactic.Events.Properties; namespace Prismactic.Events { /// <summary> /// Defines a class that manages publication and subscription to events. /// </summary> /// <typeparam name="TPayload">The type of message that will be passed to the subscribers.</typeparam> public class PubSubEvent<TPayload> : EventBase { /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread" />. /// <see cref="PubSubEvent{TPayload}" /> will maintain a <seealso cref="WeakReference" /> to the target of the supplied /// <paramref name="action" /> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <returns>A <see cref="SubscriptionToken" /> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action) { return Subscribe(action, ThreadOption.PublisherThread); } /// <summary> /// Subscribes a delegate to an event. /// PubSubEvent will maintain a <seealso cref="WeakReference" /> to the Target of the supplied /// <paramref name="action" /> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is raised.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <returns>A <see cref="SubscriptionToken" /> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption) { return Subscribe(action, threadOption, false); } /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread" />. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="keepSubscriberReferenceAlive"> /// When <see langword="true" />, the <seealso cref="PubSubEvent{TPayload}" /> /// keeps a reference to the subscriber so it does not get garbage collected. /// </param> /// <returns>A <see cref="SubscriptionToken" /> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive" /> is set to <see langword="false" />, /// <see cref="PubSubEvent{TPayload}" /> will maintain a <seealso cref="WeakReference" /> to the Target of the supplied /// <paramref name="action" /> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive" /> is <see langword="true" />), the /// user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or /// unexpected behavior. /// <para /> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, bool keepSubscriberReferenceAlive) { return Subscribe(action, ThreadOption.PublisherThread, keepSubscriberReferenceAlive); } /// <summary> /// Subscribes a delegate to an event. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <param name="keepSubscriberReferenceAlive"> /// When <see langword="true" />, the <seealso cref="PubSubEvent{TPayload}" /> /// keeps a reference to the subscriber so it does not get garbage collected. /// </param> /// <returns>A <see cref="SubscriptionToken" /> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive" /> is set to <see langword="false" />, /// <see cref="PubSubEvent{TPayload}" /> will maintain a <seealso cref="WeakReference" /> to the Target of the supplied /// <paramref name="action" /> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive" /> is <see langword="true" />), the /// user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or /// unexpected behavior. /// <para /> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive) { return Subscribe(action, threadOption, keepSubscriberReferenceAlive, null); } /// <summary> /// Subscribes a delegate to an event. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <param name="keepSubscriberReferenceAlive"> /// When <see langword="true" />, the <seealso cref="PubSubEvent{TPayload}" /> /// keeps a reference to the subscriber so it does not get garbage collected. /// </param> /// <param name="filter">Filter to evaluate if the subscriber should receive the event.</param> /// <returns>A <see cref="SubscriptionToken" /> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive" /> is set to <see langword="false" />, /// <see cref="PubSubEvent{TPayload}" /> will maintain a <seealso cref="WeakReference" /> to the Target of the supplied /// <paramref name="action" /> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive" /> is <see langword="true" />), the /// user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or /// unexpected behavior. /// The PubSubEvent collection is thread-safe. /// </remarks> public virtual SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<TPayload> filter) { IDelegateReference actionReference = new DelegateReference(action, keepSubscriberReferenceAlive); IDelegateReference filterReference; if (filter != null) { filterReference = new DelegateReference(filter, keepSubscriberReferenceAlive); } else { filterReference = new DelegateReference(new Predicate<TPayload>(delegate { return true; }), true); } EventSubscription<TPayload> subscription; switch (threadOption) { case ThreadOption.PublisherThread: subscription = new EventSubscription<TPayload>(actionReference, filterReference); break; case ThreadOption.BackgroundThread: subscription = new BackgroundEventSubscription<TPayload>(actionReference, filterReference); break; case ThreadOption.UIThread: if (SynchronizationContext == null) throw new InvalidOperationException(Resources.EventAggregatorNotConstructedOnUIThread); subscription = new DispatcherEventSubscription<TPayload>(actionReference, filterReference, SynchronizationContext); break; default: subscription = new EventSubscription<TPayload>(actionReference, filterReference); break; } return base.InternalSubscribe(subscription); } /// <summary> /// Publishes the <see cref="PubSubEvent{TPayload}" />. /// </summary> /// <param name="payload">Message to pass to the subscribers.</param> public virtual void Publish(TPayload payload) { base.InternalPublish(payload); } /// <summary> /// Removes the first subscriber matching <seealso cref="Action{TPayload}" /> from the subscribers' list. /// </summary> /// <param name="subscriber">The <see cref="Action{TPayload}" /> used when subscribing to the event.</param> public virtual void Unsubscribe(Action<TPayload> subscriber) { lock (Subscriptions) { IEventSubscription eventSubscription = Subscriptions.Cast<EventSubscription<TPayload>>().FirstOrDefault(evt => evt.Action == subscriber); if (eventSubscription != null) { Subscriptions.Remove(eventSubscription); } } } /// <summary> /// Returns <see langword="true" /> if there is a subscriber matching <seealso cref="Action{TPayload}" />. /// </summary> /// <param name="subscriber">The <see cref="Action{TPayload}" /> used when subscribing to the event.</param> /// <returns> /// <see langword="true" /> if there is an <seealso cref="Action{TPayload}" /> that matches; otherwise /// <see langword="false" />. /// </returns> public virtual bool Contains(Action<TPayload> subscriber) { IEventSubscription eventSubscription; lock (Subscriptions) { eventSubscription = Subscriptions.Cast<EventSubscription<TPayload>>().FirstOrDefault(evt => evt.Action == subscriber); } return eventSubscription != 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 Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security.Principal { [Flags] internal enum PolicyRights { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002, POLICY_GET_PRIVATE_INFORMATION = 0x00000004, POLICY_TRUST_ADMIN = 0x00000008, POLICY_CREATE_ACCOUNT = 0x00000010, POLICY_CREATE_SECRET = 0x00000020, POLICY_CREATE_PRIVILEGE = 0x00000040, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100, POLICY_AUDIT_LOG_ADMIN = 0x00000200, POLICY_SERVER_ADMIN = 0x00000400, POLICY_LOOKUP_NAMES = 0x00000800, POLICY_NOTIFICATION = 0x00001000, } internal static class Win32 { internal const int FALSE = 0; // // Wrapper around advapi32.LsaOpenPolicy // internal static SafeLsaPolicyHandle LsaOpenPolicy( string systemName, PolicyRights rights) { uint ReturnCode; SafeLsaPolicyHandle Result; Interop.LSA_OBJECT_ATTRIBUTES Loa; Loa.Length = Marshal.SizeOf<Interop.LSA_OBJECT_ATTRIBUTES>(); Loa.RootDirectory = IntPtr.Zero; Loa.ObjectName = IntPtr.Zero; Loa.Attributes = 0; Loa.SecurityDescriptor = IntPtr.Zero; Loa.SecurityQualityOfService = IntPtr.Zero; if (0 == (ReturnCode = Interop.mincore.LsaOpenPolicy(systemName, ref Loa, (int)rights, out Result))) { return Result; } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY) { throw new OutOfMemoryException(); } else { int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode)); throw new Win32Exception(win32ErrorCode); } } internal static byte[] ConvertIntPtrSidToByteArraySid(IntPtr binaryForm) { byte[] ResultSid; // // Verify the revision (just sanity, should never fail to be 1) // byte Revision = Marshal.ReadByte(binaryForm, 0); if (Revision != SecurityIdentifier.Revision) { throw new ArgumentException(SR.IdentityReference_InvalidSidRevision, nameof(binaryForm)); } // // Need the subauthority count in order to figure out how many bytes to read // byte SubAuthorityCount = Marshal.ReadByte(binaryForm, 1); if (SubAuthorityCount < 0 || SubAuthorityCount > SecurityIdentifier.MaxSubAuthorities) { throw new ArgumentException(SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), nameof(binaryForm)); } // // Compute the size of the binary form of this SID and allocate the memory // int BinaryLength = 1 + 1 + 6 + SubAuthorityCount * 4; ResultSid = new byte[BinaryLength]; // // Extract the data from the returned pointer // Marshal.Copy(binaryForm, ResultSid, 0, BinaryLength); return ResultSid; } // // Wrapper around advapi32.ConvertStringSidToSidW // internal static int CreateSidFromString( string stringSid, out byte[] resultSid ) { int ErrorCode; IntPtr ByteArray = IntPtr.Zero; try { if (FALSE == Interop.mincore.ConvertStringSidToSid(stringSid, out ByteArray)) { ErrorCode = Marshal.GetLastWin32Error(); goto Error; } resultSid = ConvertIntPtrSidToByteArraySid(ByteArray); } finally { // // Now is a good time to get rid of the returned pointer // Interop.mincore_obsolete.LocalFree(ByteArray); } // // Now invoke the SecurityIdentifier factory method to create the result // return Interop.mincore.Errors.ERROR_SUCCESS; Error: resultSid = null; return ErrorCode; } // // Wrapper around advapi32.CreateWellKnownSid // internal static int CreateWellKnownSid( WellKnownSidType sidType, SecurityIdentifier domainSid, out byte[] resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // uint length = (uint)SecurityIdentifier.MaxBinaryLength; resultSid = new byte[length]; if (FALSE != Interop.mincore.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length)) { return Interop.mincore.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.EqualDomainSid // internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2) { if (sid1 == null || sid2 == null) { return false; } else { bool result; byte[] BinaryForm1 = new Byte[sid1.BinaryLength]; sid1.GetBinaryForm(BinaryForm1, 0); byte[] BinaryForm2 = new Byte[sid2.BinaryLength]; sid2.GetBinaryForm(BinaryForm2, 0); return (Interop.mincore.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result); } } /// <summary> /// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST /// </summary> internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains) { Debug.Assert(referencedDomains != null, "referencedDomains != null"); // We don't know the real size of the referenced domains yet, so we need to set an initial // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of // the domains. referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>()); Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); unsafe { byte* pRdl = null; try { referencedDomains.AcquirePointer(ref pRdl); // If there is a trust information list, then the buffer size is the end of that list minus // the beginning of the domain list. Otherwise, then the buffer is just the size of the // referenced domain list structure, which is what we defaulted to. if (domainList.Domains != IntPtr.Zero) { Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains; pTrustInformation = pTrustInformation + domainList.Entries; long bufferSize = (byte*)pTrustInformation - pRdl; Debug.Assert(bufferSize > 0, "bufferSize > 0"); referencedDomains.Initialize((ulong)bufferSize); } } finally { if (pRdl != null) referencedDomains.ReleasePointer(); } } } // // Wrapper around avdapi32.GetWindowsAccountDomainSid // internal static int GetWindowsAccountDomainSid( SecurityIdentifier sid, out SecurityIdentifier resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // byte[] BinaryForm = new Byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength; byte[] resultSidBinary = new byte[sidLength]; if (FALSE != Interop.mincore.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength)) { resultSid = new SecurityIdentifier(resultSidBinary, 0); return Interop.mincore.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.IsWellKnownSid // internal static bool IsWellKnownSid( SecurityIdentifier sid, WellKnownSidType type ) { byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); if (FALSE == Interop.mincore.IsWellKnownSid(BinaryForm, (int)type)) { return false; } else { return true; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Trollbridge.WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Collections; namespace Google.ProtocolBuffers { public abstract partial class ExtendableMessageLite<TMessage, TBuilder> : GeneratedMessageLite<TMessage, TBuilder> where TMessage : GeneratedMessageLite<TMessage, TBuilder> where TBuilder : GeneratedBuilderLite<TMessage, TBuilder> { protected ExtendableMessageLite() { } private readonly FieldSet extensions = FieldSet.CreateInstance(); /// <summary> /// Access for the builder. /// </summary> internal FieldSet Extensions { get { return extensions; } } public override bool Equals(object obj) { ExtendableMessageLite<TMessage, TBuilder> other = obj as ExtendableMessageLite<TMessage, TBuilder>; return !ReferenceEquals(null, other) && Dictionaries.Equals(extensions.AllFields, other.extensions.AllFields); } public override int GetHashCode() { return Dictionaries.GetHashCode(extensions.AllFields); } /// <summary> /// writes the extensions to the text stream /// </summary> public override void PrintTo(TextWriter writer) { foreach (KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) { string fn = string.Format("[{0}]", entry.Key.FullName); if (entry.Key.IsRepeated) { foreach (object o in ((IEnumerable) entry.Value)) { PrintField(fn, true, o, writer); } } else { PrintField(fn, true, entry.Value, writer); } } } /// <summary> /// Checks if a singular extension is present. /// </summary> public bool HasExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) { VerifyExtensionContainingType(extension); return extensions.HasField(extension.Descriptor); } /// <summary> /// Returns the number of elements in a repeated extension. /// </summary> public int GetExtensionCount<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension) { VerifyExtensionContainingType(extension); return extensions.GetRepeatedFieldCount(extension.Descriptor); } /// <summary> /// Returns the value of an extension. /// </summary> public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) { VerifyExtensionContainingType(extension); object value = extensions[extension.Descriptor]; if (value == null) { return extension.DefaultValue; } else { return (TExtension) extension.FromReflectionType(value); } } /// <summary> /// Returns one element of a repeated extension. /// </summary> public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension, int index) { VerifyExtensionContainingType(extension); return (TExtension) extension.SingularFromReflectionType(extensions[extension.Descriptor, index]); } /// <summary> /// Called to check if all extensions are initialized. /// </summary> protected bool ExtensionsAreInitialized { get { return extensions.IsInitialized; } } public override bool IsInitialized { get { return ExtensionsAreInitialized; } } /// <summary> /// Used by subclasses to serialize extensions. Extension ranges may be /// interleaves with field numbers, but we must write them in canonical /// (sorted by field number) order. This class helps us to write individual /// ranges of extensions at once. /// /// TODO(jonskeet): See if we can improve this in terms of readability. /// </summary> protected class ExtensionWriter { private readonly IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> iterator; private readonly FieldSet extensions; private KeyValuePair<IFieldDescriptorLite, object>? next = null; internal ExtensionWriter(ExtendableMessageLite<TMessage, TBuilder> message) { extensions = message.extensions; iterator = message.extensions.GetEnumerator(); if (iterator.MoveNext()) { next = iterator.Current; } } public void WriteUntil(int end, ICodedOutputStream output) { while (next != null && next.Value.Key.FieldNumber < end) { extensions.WriteField(next.Value.Key, next.Value.Value, output); if (iterator.MoveNext()) { next = iterator.Current; } else { next = null; } } } } protected ExtensionWriter CreateExtensionWriter(ExtendableMessageLite<TMessage, TBuilder> message) { return new ExtensionWriter(message); } /// <summary> /// Called by subclasses to compute the size of extensions. /// </summary> protected int ExtensionsSerializedSize { get { return extensions.SerializedSize; } } internal void VerifyExtensionContainingType<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) { if (!ReferenceEquals(extension.ContainingTypeDefaultInstance, DefaultInstanceForType)) { // This can only happen if someone uses unchecked operations. throw new ArgumentException( String.Format("Extension is for type \"{0}\" which does not match message type \"{1}\".", extension.ContainingTypeDefaultInstance, DefaultInstanceForType )); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using Timer = System.Timers.Timer; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.World.NPC { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NPCModule")] public class NPCModule : INPCModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, NPCAvatar> m_avatars = new Dictionary<UUID, NPCAvatar>(); private NPCOptionsFlags m_NPCOptionFlags; public NPCOptionsFlags NPCOptionFlags {get {return m_NPCOptionFlags;}} public bool Enabled { get; private set; } public void Initialise(IConfigSource source) { IConfig config = source.Configs["NPC"]; Enabled = (config != null && config.GetBoolean("Enabled", false)); m_NPCOptionFlags = NPCOptionsFlags.None; if(Enabled) { if(config.GetBoolean("AllowNotOwned", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowNotOwned; if(config.GetBoolean("AllowSenseAsAvatar", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowSenseAsAvatar; if(config.GetBoolean("AllowCloneOtherAvatars", true)) m_NPCOptionFlags |= NPCOptionsFlags.AllowCloneOtherAvatars; if(config.GetBoolean("NoNPCGroup", true)) m_NPCOptionFlags |= NPCOptionsFlags.NoNPCGroup; } } public void AddRegion(Scene scene) { if (Enabled) scene.RegisterModuleInterface<INPCModule>(this); } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void RemoveRegion(Scene scene) { scene.UnregisterModuleInterface<INPCModule>(this); } public void Close() { } public string Name { get { return "NPCModule"; } } public Type ReplaceableInterface { get { return null; } } public bool IsNPC(UUID agentId, Scene scene) { // FIXME: This implementation could not just use the // ScenePresence.PresenceType (and callers could inspect that // directly). ScenePresence sp = scene.GetScenePresence(agentId); if (sp == null || sp.IsChildAgent) return false; lock (m_avatars) return m_avatars.ContainsKey(agentId); } public bool SetNPCAppearance(UUID agentId, AvatarAppearance appearance, Scene scene) { ScenePresence npc = scene.GetScenePresence(agentId); if (npc == null || npc.IsChildAgent) return false; lock (m_avatars) if (!m_avatars.ContainsKey(agentId)) return false; // Delete existing npc attachments if(scene.AttachmentsModule != null) scene.AttachmentsModule.DeleteAttachmentsFromScene(npc, false); // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet // since it doesn't transfer attachments AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); npc.Appearance = npcAppearance; // Rez needed npc attachments if (scene.AttachmentsModule != null) scene.AttachmentsModule.RezAttachments(npc); IAvatarFactoryModule module = scene.RequestModuleInterface<IAvatarFactoryModule>(); module.SendAppearance(npc.UUID); return true; } public UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance) { return CreateNPC(firstname, lastname, position, UUID.Zero, owner, senseAsAgent, scene, appearance); } public UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID agentID, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance) { NPCAvatar npcAvatar = null; try { if (agentID == UUID.Zero) npcAvatar = new NPCAvatar(firstname, lastname, position, owner, senseAsAgent, scene); else npcAvatar = new NPCAvatar(firstname, lastname, agentID, position, owner, senseAsAgent, scene); } catch (Exception e) { m_log.Info("[NPC MODULE]: exception creating NPC avatar: " + e.ToString()); return UUID.Zero; } npcAvatar.CircuitCode = (uint)Util.RandomClass.Next(0, int.MaxValue); // m_log.DebugFormat( // "[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}", // firstname, lastname, npcAvatar.AgentId, owner, senseAsAgent, position, scene.RegionInfo.RegionName); AgentCircuitData acd = new AgentCircuitData(); acd.AgentID = npcAvatar.AgentId; acd.firstname = firstname; acd.lastname = lastname; acd.ServiceURLs = new Dictionary<string, object>(); AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); acd.Appearance = npcAppearance; /* for (int i = 0; i < acd.Appearance.Texture.FaceTextures.Length; i++) { m_log.DebugFormat( "[NPC MODULE]: NPC avatar {0} has texture id {1} : {2}", acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); } */ // ManualResetEvent ev = new ManualResetEvent(false); // Util.FireAndForget(delegate(object x) { lock (m_avatars) { scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode, acd); scene.AddNewAgent(npcAvatar, PresenceType.Npc); ScenePresence sp; if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp)) { sp.CompleteMovement(npcAvatar, false); m_avatars.Add(npcAvatar.AgentId, npcAvatar); // m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name); } } // ev.Set(); // }); // ev.WaitOne(); // m_log.DebugFormat("[NPC MODULE]: Created NPC with id {0}", npcAvatar.AgentId); return npcAvatar.AgentId; } public bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos, bool noFly, bool landAtTarget, bool running) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { if (sp.IsSatOnObject || sp.SitGround) return false; // m_log.DebugFormat( // "[NPC MODULE]: Moving {0} to {1} in {2}, noFly {3}, landAtTarget {4}", // sp.Name, pos, scene.RegionInfo.RegionName, // noFly, landAtTarget); sp.MoveToTarget(pos, noFly, landAtTarget); sp.SetAlwaysRun = running; return true; } } } return false; } public bool StopMoveToTarget(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.Velocity = Vector3.Zero; sp.ResetMoveToTarget(); return true; } } } return false; } public bool Say(UUID agentID, Scene scene, string text) { return Say(agentID, scene, text, 0); } public bool Say(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Say(channel, text); return true; } } return false; } public bool Shout(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Shout(channel, text); return true; } } return false; } public bool Sit(UUID agentID, UUID partID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.HandleAgentRequestSit(m_avatars[agentID], agentID, partID, Vector3.Zero); return true; } } } return false; } public bool Whisper(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Whisper(channel, text); return true; } } return false; } public bool Stand(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.StandUp(); return true; } } } return false; } public bool Touch(UUID agentID, UUID objectID) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID].Touch(objectID); return false; } } public UUID GetOwner(UUID agentID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(agentID, out av)) return av.OwnerID; } return UUID.Zero; } public INPC GetNPC(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID]; else return null; } } public bool DeleteNPC(UUID agentID, Scene scene) { bool doRemove = false; NPCAvatar av; lock (m_avatars) { if (m_avatars.TryGetValue(agentID, out av)) { /* m_log.DebugFormat("[NPC MODULE]: Found {0} {1} to remove", agentID, av.Name); */ doRemove = true; } } if (doRemove) { scene.CloseAgent(agentID, false); lock (m_avatars) { m_avatars.Remove(agentID); } m_log.DebugFormat("[NPC MODULE]: Removed NPC {0} {1}", agentID, av.Name); return true; } /* m_log.DebugFormat("[NPC MODULE]: Could not find {0} to remove", agentID); */ return false; } public bool CheckPermissions(UUID npcID, UUID callerID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(npcID, out av)) { if (npcID == callerID) return true; return CheckPermissions(av, callerID); } else { return false; } } } /// <summary> /// Check if the caller has permission to manipulate the given NPC. /// </summary> /// <remarks> /// A caller has permission if /// * The caller UUID given is UUID.Zero. /// * The avatar is unowned (owner is UUID.Zero). /// * The avatar is owned and the owner and callerID match. /// * The avatar is owned and the callerID matches its agentID. /// </remarks> /// <param name="av"></param> /// <param name="callerID"></param> /// <returns>true if they do, false if they don't.</returns> private bool CheckPermissions(NPCAvatar av, UUID callerID) { return callerID == UUID.Zero || av.OwnerID == UUID.Zero || av.OwnerID == callerID || av.AgentId == callerID; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using System.Reflection; using OpenMetaverse; using Aurora.Framework; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Agent.AssetTransaction { /// <summary> /// Manage asset transactions for a single agent. /// </summary> public class AgentAssetTransactions { // Fields public AssetTransactionModule Manager; public UUID UserID; public Dictionary<UUID, AssetXferUploader> XferUploaders = new Dictionary<UUID, AssetXferUploader>(); // Methods public AgentAssetTransactions(UUID agentID, AssetTransactionModule manager) { UserID = agentID; Manager = manager; } public AssetXferUploader RequestXferUploader(UUID transactionID) { if (!XferUploaders.ContainsKey(transactionID)) { AssetXferUploader uploader = new AssetXferUploader(this); lock (XferUploaders) { XferUploaders.Add(transactionID, uploader); } return uploader; } return null; } public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data) { lock (XferUploaders) { #if (!ISWIN) foreach (AssetXferUploader uploader in XferUploaders.Values) { if (uploader.XferID == xferID) { uploader.HandleXferPacket(remoteClient, xferID, packetID, data); break; } } #else foreach (AssetXferUploader uploader in XferUploaders.Values.Where(uploader => uploader.XferID == xferID)) { uploader.HandleXferPacket(remoteClient, xferID, packetID, data); break; } #endif } } public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { if (XferUploaders.ContainsKey(transactionID)) { XferUploaders[transactionID].RequestCreateInventoryItem(remoteClient, transactionID, folderID, callbackID, description, name, invType, type, wearableType, nextOwnerMask); } } /// <summary> /// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed. /// </summary> /// <param name = "transactionID"></param> /// <returns>The asset if the upload has completed, null if it has not.</returns> public AssetBase GetTransactionAsset(UUID transactionID) { if (XferUploaders.ContainsKey(transactionID)) { AssetXferUploader uploader = XferUploaders[transactionID]; AssetBase asset = uploader.GetAssetData(); lock (XferUploaders) { XferUploaders.Remove(transactionID); } return asset; } return null; } //private void CreateItemFromUpload(AssetBase asset, IClientAPI ourClient, UUID inventoryFolderID, uint nextPerms, uint wearableType) //{ // Manager.MyScene.CommsManager.AssetCache.AddAsset(asset); // CachedUserInfo userInfo = Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails( // ourClient.AgentId); // if (userInfo != null) // { // InventoryItemBase item = new InventoryItemBase(); // item.Owner = ourClient.AgentId; // item.Creator = ourClient.AgentId; // item.ID = UUID.Random(); // item.AssetID = asset.FullID; // item.Description = asset.Description; // item.Name = asset.Name; // item.AssetType = asset.Type; // item.InvType = asset.Type; // item.Folder = inventoryFolderID; // item.BasePermissions = 0x7fffffff; // item.CurrentPermissions = 0x7fffffff; // item.EveryOnePermissions = 0; // item.NextPermissions = nextPerms; // item.Flags = wearableType; // item.CreationDate = Util.UnixTimeSinceEpoch(); // userInfo.AddItem(item); // ourClient.SendInventoryItemCreateUpdate(item); // } // else // { // MainConsole.Instance.ErrorFormat( // "[ASSET TRANSACTIONS]: Could not find user {0} for inventory item creation", // ourClient.AgentId); // } //} public void RequestUpdateTaskInventoryItem( IClientAPI remoteClient, ISceneChildEntity part, UUID transactionID, TaskInventoryItem item) { if (XferUploaders.ContainsKey(transactionID)) { AssetBase asset = XferUploaders[transactionID].GetAssetData(); if (asset != null) { MainConsole.Instance.DebugFormat( "[ASSET TRANSACTIONS]: Updating task item {0} in {1} with asset in transaction {2}", item.Name, part.Name, transactionID); asset.Name = item.Name; asset.Description = item.Description; asset.Type = (sbyte) item.Type; item.AssetID = asset.ID; IMonitorModule monitorModule = Manager.MyScene.RequestModuleInterface<IMonitorModule>(); if (monitorModule != null) { INetworkMonitor networkMonitor = (INetworkMonitor) monitorModule.GetMonitor(Manager.MyScene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.NetworkMonitor); networkMonitor.AddPendingUploads(-1); } asset.ID = Manager.MyScene.AssetService.Store(asset); item.AssetID = asset.ID; if (part.Inventory.UpdateInventoryItem(item)) { if ((InventoryType) item.InvType == InventoryType.Notecard) remoteClient.SendAgentAlertMessage("Notecard saved", false); else if ((InventoryType) item.InvType == InventoryType.LSL) remoteClient.SendAgentAlertMessage("Script saved", false); else remoteClient.SendAgentAlertMessage("Item saved", false); part.GetProperties(remoteClient); } } } } public void RequestUpdateInventoryItem(IClientAPI remoteClient, UUID transactionID, InventoryItemBase item) { if (XferUploaders.ContainsKey(transactionID)) { UUID assetID = UUID.Combine(transactionID, remoteClient.SecureSessionId); AssetXferUploader uploader = XferUploaders[transactionID]; if (!uploader.Finished) { uploader.FinishedEvent = () => UpdateInventoryItemWithAsset(item, assetID, transactionID); return; } UpdateInventoryItemWithAsset(item, assetID, transactionID); } } private void UpdateInventoryItemWithAsset(InventoryItemBase item, UUID assetID, UUID transactionID) { AssetXferUploader uploader = XferUploaders[transactionID]; AssetBase asset = uploader.GetAssetData(); if (asset != null && asset.ID == assetID) { // Assets never get updated, new ones get created asset.ID = UUID.Random(); asset.Name = item.Name; asset.Description = item.Description; asset.Type = (sbyte)item.AssetType; item.AssetID = asset.ID; asset.ID = Manager.MyScene.AssetService.Store(asset); item.AssetID = asset.ID; XferUploaders.Remove(transactionID); } else return; IMonitorModule monitorModule = Manager.MyScene.RequestModuleInterface<IMonitorModule>(); if (monitorModule != null) { INetworkMonitor networkMonitor = (INetworkMonitor) monitorModule.GetMonitor(Manager.MyScene.RegionInfo.RegionID.ToString(), MonitorModuleHelper.NetworkMonitor); networkMonitor.AddPendingUploads(-1); } IInventoryService invService = Manager.MyScene.InventoryService; invService.UpdateItem(item); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Web; using System.Xml; using Common.Logging; using JenkinsTray.Entities; using JenkinsTray.Utils; using JenkinsTray.Utils.Logging; using JenkinsTray.Utils.Web; using Spring.Collections.Generic; namespace JenkinsTray.BusinessComponents { public class JenkinsService { public static readonly String buildDetailsFilter = "?tree=number,fullDisplayName,timestamp,estimatedDuration,duration,result,userNodes,culprits[fullName],builtOn,url,actions[assignedBy,claimDate,claimed,claimedBy,reason]"; private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); [ThreadStatic] private static WebClient threadWebClient; [ThreadStatic] private static bool ignoreUntrustedCertificate; // cache: key=url, value=xml private IDictionary<string, string> cache = new Dictionary<string, string>(); // URLs visited between 2 calls to RecycleCache() private readonly Spring.Collections.Generic.ISet<string> visitedURLs = new HashedSet<string>(); public JenkinsService() { ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; } public ClaimService ClaimService { get; set; } public IList<Project> LoadProjects(Server server) { var url = NetUtils.ConcatUrls(server.Url, "/api/xml?tree=jobs[name,url,color]"); logger.Info("Loading projects from " + url); var xmlStr = DownloadString(server.Credentials, url, false, server.IgnoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("XML: " + xmlStr); var xml = new XmlDocument(); xml.LoadXml(xmlStr); var jobElements = xml.SelectNodes("/hudson/job"); var projects = GetProjects(jobElements, server); logger.Info("Done loading projects"); return projects; } public List<Project> GetProjects(XmlNodeList jobElements, Server server) { var projects = new List<Project>(); foreach (XmlNode jobElement in jobElements) { var projectName = jobElement.SelectSingleNode("name").InnerText; var projectUrl = jobElement.SelectSingleNode("url").InnerText; var projectColor = jobElement.SelectSingleNode("color"); // If the job is a folder we need to recursively get the jobs within. if (jobElement.SelectSingleNode("color") == null) { var url = NetUtils.ConcatUrls(projectUrl, "/api/xml?tree=jobs[name,url,color]"); var xmlStr = DownloadString(server.Credentials, url, false, server.IgnoreUntrustedCertificate); var xml = new XmlDocument(); xml.LoadXml(xmlStr); var nodes = xml.SelectNodes("/folder/job"); if (nodes.Count == 0) { nodes = xml.SelectNodes("/workflowMultiBranchProject/job"); } projects.AddRange(GetProjects(nodes, server)); } else { var project = new Project(); project.Server = server; project.Name = projectName; project.Url = projectUrl; if (logger.IsDebugEnabled) logger.Debug("Found project " + projectName + " (" + projectUrl + ")"); // Ensure only unique entries in the returned list. if (!projects.Contains(project)) { projects.Add(project); } } } return projects; } public AllBuildDetails UpdateProject(Project project) { var url = NetUtils.ConcatUrls(project.Url, "/api/xml"); //logger.Info("Updating project from " + url); var credentials = project.Server.Credentials; var ignoreUntrustedCertificate = project.Server.IgnoreUntrustedCertificate; var xmlStr = DownloadString(credentials, url, false, ignoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("XML: " + xmlStr); var xml = new XmlDocument(); xml.LoadXml(xmlStr); var displayName = XmlUtils.SelectSingleNodeText(xml, "/*/displayName"); var inQueue = XmlUtils.SelectSingleNodeBoolean(xml, "/*/inQueue"); var inQueueSince = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/inQueueSince"); var queueId = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/id"); var why = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/why"); var stuck = XmlUtils.SelectSingleNodeBoolean(xml, "/*/queueItem/stuck"); var status = xml.SelectSingleNode("/*/color").InnerText; var lastBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastBuild/url"); var lastCompletedBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastCompletedBuild/url"); var lastSuccessfulBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastSuccessfulBuild/url"); var lastFailedBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastFailedBuild/url"); project.DisplayName = displayName; project.Queue.InQueue = inQueue.HasValue && inQueue.Value; if (!string.IsNullOrEmpty(queueId)) { project.Queue.Id = long.Parse(queueId); } if (!string.IsNullOrEmpty(inQueueSince)) { var ts = TimeSpan.FromSeconds(long.Parse(inQueueSince)/1000); var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); date = date.Add(ts); project.Queue.InQueueSince = date; } if (!string.IsNullOrEmpty(why)) { project.Queue.Why = why; } var res = new AllBuildDetails(); res.Status = GetStatus(status, stuck); res.LastBuild = GetBuildDetails(credentials, lastBuildUrl, ignoreUntrustedCertificate); res.LastCompletedBuild = GetBuildDetails(credentials, lastCompletedBuildUrl, ignoreUntrustedCertificate); res.LastSuccessfulBuild = GetBuildDetails(credentials, lastSuccessfulBuildUrl, ignoreUntrustedCertificate); res.LastFailedBuild = GetBuildDetails(credentials, lastFailedBuildUrl, ignoreUntrustedCertificate); //logger.Info("Done updating project"); return res; } // http://javadoc.jenkins-ci.org/hudson/model/BallColor.html private BuildStatus GetStatus(string status, bool? stuck) { BuildStatusEnum value; if (status.StartsWith("grey")) value = BuildStatusEnum.Indeterminate; else if (status.StartsWith("blue") || status.StartsWith("green")) value = BuildStatusEnum.Successful; else if (status.StartsWith("yellow")) value = BuildStatusEnum.Unstable; else if (status.StartsWith("red")) value = BuildStatusEnum.Failed; else if (status.StartsWith("aborted")) value = BuildStatusEnum.Aborted; else if (status.StartsWith("disabled")) value = BuildStatusEnum.Disabled; else value = BuildStatusEnum.Unknown; var isInProgress = status.EndsWith("_anime"); var isStuck = stuck.HasValue && stuck.Value; return new BuildStatus(value, isInProgress, isStuck); } private BuildDetails GetBuildDetails(Credentials credentials, string buildUrl, bool ignoreUntrustedCertificate) { if (buildUrl == null) return null; var url = NetUtils.ConcatUrls(buildUrl, "/api/xml", JenkinsService.buildDetailsFilter); if (logger.IsDebugEnabled) logger.Debug("Getting build details from " + url); var xmlStr = DownloadString(credentials, url, true, ignoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("XML: " + xmlStr); var xml = new XmlDocument(); xml.LoadXml(xmlStr); var number = xml.SelectSingleNode("/*/number").InnerText; var fullDisplayName = xml.SelectSingleNode("/*/fullDisplayName").InnerText; var timestamp = xml.SelectSingleNode("/*/timestamp").InnerText; var estimatedDuration = xml.SelectSingleNode("/*/estimatedDuration").InnerText; var duration = xml.SelectSingleNode("/*/duration").InnerText; var xmlResult = xml.SelectSingleNode("/*/result"); var result = xmlResult == null ? string.Empty : xmlResult.InnerText; var userNodes = xml.SelectNodes("/*/culprit/fullName"); var ts = TimeSpan.FromSeconds(long.Parse(timestamp)/1000); var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); date = date.Add(ts); var estimatedts = TimeSpan.FromSeconds(long.Parse(estimatedDuration)/1000); var durationts = TimeSpan.FromSeconds(long.Parse(estimatedDuration)/1000); Spring.Collections.Generic.ISet<string> users = new HashedSet<string>(); foreach (XmlNode userNode in userNodes) { var userName = StringUtils.ExtractUserName(userNode.InnerText); users.Add(userName); } var res = new BuildDetails(); BuildCauses.FillInBuildCauses(res, xml); res.Number = int.Parse(number); res.DisplayName = fullDisplayName; res.Time = date; res.EstimatedDuration = estimatedts; res.Duration = durationts; res.Result = BuildStatus.StringToBuildStatus(result); res.Users = users; ClaimService.FillInBuildDetails(res, xml); if (logger.IsDebugEnabled) logger.Debug("Done getting build details"); return res; } public void SafeRunBuild(Project project) { try { RunBuild(project); } catch (Exception ex) { LoggingHelper.LogError(logger, ex); throw ex; } } public void RunBuild(Project project) { var url = NetUtils.ConcatUrls(project.Url, "/build?delay=0sec"); if (!string.IsNullOrEmpty(project.AuthenticationToken)) { url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&token=", HttpUtility.UrlEncode(project.AuthenticationToken)); if (!string.IsNullOrEmpty(project.CauseText)) { url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&cause=", HttpUtility.UrlEncode(project.CauseText)); } } logger.Info("Running build at " + url); var credentials = project.Server.Credentials; var str = UploadString(credentials, url, project.Server.IgnoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("Result: " + str); logger.Info("Done running build"); } public void SafeStopBuild(Project project) { try { StopBuild(project); } catch (Exception ex) { LoggingHelper.LogError(logger, ex); throw ex; } } public void StopBuild(Project project) { var url = NetUtils.ConcatUrls(project.Url, "/lastBuild/stop"); if (!string.IsNullOrEmpty(project.AuthenticationToken)) { url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&token=", HttpUtility.UrlEncode(project.AuthenticationToken)); if (!string.IsNullOrEmpty(project.CauseText)) { url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&cause=", HttpUtility.UrlEncode(project.CauseText)); } } logger.Info("Stopping build at " + url); var credentials = project.Server.Credentials; var str = UploadString(credentials, url, project.Server.IgnoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("Result: " + str); logger.Info("Done stopping build"); } public void SafeRemoveFromQueue(Project project) { try { RemoveFromQueue(project.Server, project.Queue.Id); } catch (Exception ex) { LoggingHelper.LogError(logger, ex); throw ex; } } public void RemoveFromQueue(Server server, long queueId) { var url = NetUtils.ConcatUrls(server.Url, "/queue/cancelItem?id=" + queueId); logger.Info("Removing queue item at " + url); var credentials = server.Credentials; try { var str = UploadString(credentials, url, server.IgnoreUntrustedCertificate); if (logger.IsTraceEnabled) logger.Trace("Result: " + str); } catch (WebException webEx) { // Workaround for JENKINS-21311 if (webEx.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse) webEx.Response).StatusCode == HttpStatusCode.NotFound) { // consume error 404 } else throw webEx; } logger.Info("Done removing queue item"); } private string DownloadString(Credentials credentials, string url, bool cacheable, bool ignoreUntrustedCertificate) { string res; if (logger.IsTraceEnabled) logger.Trace("Downloading: " + url); if (cacheable) { lock (this) { // mark the URL as visited visitedURLs.Add(url); // perform a lookup in the cache if (cache.TryGetValue(url, out res)) { if (logger.IsTraceEnabled) logger.Trace("Cache hit: " + url); return res; } } if (logger.IsTraceEnabled) logger.Trace("Cache miss: " + url); } // set the thread-static field JenkinsService.ignoreUntrustedCertificate = ignoreUntrustedCertificate; var webClient = GetWebClient(credentials); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; res = webClient.DownloadString(url); if (logger.IsTraceEnabled) logger.Trace("Downloaded: " + res); if (cacheable) { lock (this) { // store in cache cache[url] = res; } } return res; } private string UploadString(Credentials credentials, string url, bool ignoreUntrustedCertificate) { string res; if (logger.IsTraceEnabled) logger.Trace("Uploading: " + url); // set the thread-static field JenkinsService.ignoreUntrustedCertificate = ignoreUntrustedCertificate; var webClient = GetWebClient(credentials); webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; res = webClient.UploadString(url, ""); if (logger.IsTraceEnabled) logger.Trace("Uploaded: " + res); return res; } private WebClient GetWebClient(Credentials credentials) { if (threadWebClient == null) { logger.Info("Creating web client in thread " + Thread.CurrentThread.ManagedThreadId + " (" + Thread.CurrentThread.Name + ")"); threadWebClient = new CookieAwareWebClient(); threadWebClient.Encoding = Encoding.UTF8; } // reinitialize HTTP headers threadWebClient.Headers = new WebHeaderCollection(); // credentials if (credentials != null) { var authentication = "Basic " + Convert.ToBase64String( Encoding.ASCII.GetBytes(credentials.Username + ":" + credentials.Password)); threadWebClient.Headers.Add("Authorization", authentication); } return threadWebClient; } public void RecycleCache() { lock (this) { if (logger.IsTraceEnabled) logger.Trace("Recycling cache: " + cache.Keys.Count + " items in cache"); var newCache = new Dictionary<string, string>(); foreach (var visitedURL in visitedURLs) { string value; if (cache.TryGetValue(visitedURL, out value)) newCache.Add(visitedURL, value); } cache = newCache; visitedURLs.Clear(); if (logger.IsTraceEnabled) logger.Trace("Recycling cache: " + cache.Keys.Count + " items in cache"); } } public void RemoveFromCache(string url) { lock (this) { cache.Remove(url); } } public string GetConsolePage(Project project) { var res = project.Url; var hasBuild = HasBuild(project.AllBuildDetails); if (hasBuild) res += "lastBuild/console"; return res; } private bool HasBuild(AllBuildDetails allBuildDetails) { // no details, there is no build if (allBuildDetails == null) return false; // if there is a completed build, there is a build if (allBuildDetails.LastCompletedBuild != null) return true; // if there is a build in progress, there is a build var buildInProgress = allBuildDetails.Status.IsInProgress; return buildInProgress; } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (ignoreUntrustedCertificate) return true; return sslPolicyErrors == SslPolicyErrors.None; } } }
/* * ToolTipControl - A limited wrapper around a Windows tooltip control * * For some reason, the ToolTip class in the .NET framework is implemented in a significantly * different manner to other controls. For our purposes, the worst of these problems * is that we cannot get the Handle, so we cannot send Windows level messages to the control. * * Author: Phillip Piper * Date: 2009-05-17 7:22PM * * Change log: * v2.3 * 2009-06-13 JPP - Moved ToolTipShowingEventArgs to Events.cs * v2.2 * 2009-06-06 JPP - Fixed some Vista specific problems * 2009-05-17 JPP - Initial version * * TO DO: * * Copyright (C) 2006-2014 Phillip Piper * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact [email protected]. */ using System; using System.Collections; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Security.Permissions; namespace BrightIdeasSoftware { /// <summary> /// A limited wrapper around a Windows tooltip window. /// </summary> public class ToolTipControl : NativeWindow { #region Constants /// <summary> /// These are the standard icons that a tooltip can display. /// </summary> public enum StandardIcons { /// <summary> /// No icon /// </summary> None = 0, /// <summary> /// Info /// </summary> Info = 1, /// <summary> /// Warning /// </summary> Warning = 2, /// <summary> /// Error /// </summary> Error = 3, /// <summary> /// Large info (Vista and later only) /// </summary> InfoLarge = 4, /// <summary> /// Large warning (Vista and later only) /// </summary> WarningLarge = 5, /// <summary> /// Large error (Vista and later only) /// </summary> ErrorLarge = 6 } const int GWL_STYLE = -16; const int WM_GETFONT = 0x31; const int WM_SETFONT = 0x30; const int WS_BORDER = 0x800000; const int WS_EX_TOPMOST = 8; const int TTM_ADDTOOL = 0x432; const int TTM_ADJUSTRECT = 0x400 + 31; const int TTM_DELTOOL = 0x433; const int TTM_GETBUBBLESIZE = 0x400 + 30; const int TTM_GETCURRENTTOOL = 0x400 + 59; const int TTM_GETTIPBKCOLOR = 0x400 + 22; const int TTM_GETTIPTEXTCOLOR = 0x400 + 23; const int TTM_GETDELAYTIME = 0x400 + 21; const int TTM_NEWTOOLRECT = 0x400 + 52; const int TTM_POP = 0x41c; const int TTM_SETDELAYTIME = 0x400 + 3; const int TTM_SETMAXTIPWIDTH = 0x400 + 24; const int TTM_SETTIPBKCOLOR = 0x400 + 19; const int TTM_SETTIPTEXTCOLOR = 0x400 + 20; const int TTM_SETTITLE = 0x400 + 33; const int TTM_SETTOOLINFO = 0x400 + 54; const int TTF_IDISHWND = 1; //const int TTF_ABSOLUTE = 0x80; const int TTF_CENTERTIP = 2; const int TTF_RTLREADING = 4; const int TTF_SUBCLASS = 0x10; //const int TTF_TRACK = 0x20; //const int TTF_TRANSPARENT = 0x100; const int TTF_PARSELINKS = 0x1000; const int TTS_NOPREFIX = 2; const int TTS_BALLOON = 0x40; const int TTS_USEVISUALSTYLE = 0x100; const int TTN_FIRST = -520; /// <summary> /// /// </summary> public const int TTN_SHOW = (TTN_FIRST - 1); /// <summary> /// /// </summary> public const int TTN_POP = (TTN_FIRST - 2); /// <summary> /// /// </summary> public const int TTN_LINKCLICK = (TTN_FIRST - 3); /// <summary> /// /// </summary> public const int TTN_GETDISPINFO = (TTN_FIRST - 10); const int TTDT_AUTOMATIC = 0; const int TTDT_RESHOW = 1; const int TTDT_AUTOPOP = 2; const int TTDT_INITIAL = 3; #endregion #region Properties /// <summary> /// Get or set if the style of the tooltip control /// </summary> internal int WindowStyle { get { return (int)NativeMethods.GetWindowLong(this.Handle, GWL_STYLE); } set { NativeMethods.SetWindowLong(this.Handle, GWL_STYLE, value); } } /// <summary> /// Get or set if the tooltip should be shown as a ballon /// </summary> public bool IsBalloon { get { return (this.WindowStyle & TTS_BALLOON) == TTS_BALLOON; } set { if (this.IsBalloon == value) return; int windowStyle = this.WindowStyle; if (value) { windowStyle |= (TTS_BALLOON | TTS_USEVISUALSTYLE); // On XP, a border makes the ballon look wrong if (!ObjectListView.IsVistaOrLater) windowStyle &= ~WS_BORDER; } else { windowStyle &= ~(TTS_BALLOON | TTS_USEVISUALSTYLE); if (!ObjectListView.IsVistaOrLater) { if (this.hasBorder) windowStyle |= WS_BORDER; else windowStyle &= ~WS_BORDER; } } this.WindowStyle = windowStyle; } } /// <summary> /// Get or set if the tooltip should be shown as a ballon /// </summary> public bool HasBorder { get { return this.hasBorder; } set { if (this.hasBorder == value) return; if (value) { this.WindowStyle |= WS_BORDER; } else { this.WindowStyle &= ~WS_BORDER; } } } private bool hasBorder = true; /// <summary> /// Get or set the background color of the tooltip /// </summary> public Color BackColor { get { int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPBKCOLOR, 0, 0); return ColorTranslator.FromWin32(color); } set { // For some reason, setting the color fails on Vista and messes up later ops. // So we don't even try to set it. if (!ObjectListView.IsVistaOrLater) { int color = ColorTranslator.ToWin32(value); NativeMethods.SendMessage(this.Handle, TTM_SETTIPBKCOLOR, color, 0); //int x2 = Marshal.GetLastWin32Error(); } } } /// <summary> /// Get or set the color of the text and border on the tooltip. /// </summary> public Color ForeColor { get { int color = (int)NativeMethods.SendMessage(this.Handle, TTM_GETTIPTEXTCOLOR, 0, 0); return ColorTranslator.FromWin32(color); } set { // For some reason, setting the color fails on Vista and messes up later ops. // So we don't even try to set it. if (!ObjectListView.IsVistaOrLater) { int color = ColorTranslator.ToWin32(value); NativeMethods.SendMessage(this.Handle, TTM_SETTIPTEXTCOLOR, color, 0); } } } /// <summary> /// Get or set the title that will be shown on the tooltip. /// </summary> public string Title { get { return this.title; } set { if (String.IsNullOrEmpty(value)) this.title = String.Empty; else if (value.Length >= 100) this.title = value.Substring(0, 99); else this.title = value; NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); } } private string title; /// <summary> /// Get or set the icon that will be shown on the tooltip. /// </summary> public StandardIcons StandardIcon { get { return this.standardIcon; } set { this.standardIcon = value; NativeMethods.SendMessageString(this.Handle, TTM_SETTITLE, (int)this.standardIcon, this.title); } } private StandardIcons standardIcon; /// <summary> /// Gets or sets the font that will be used to draw this control. /// is still. /// </summary> /// <remarks>Setting this to null reverts to the default font.</remarks> public Font Font { get { IntPtr hfont = NativeMethods.SendMessage(this.Handle, WM_GETFONT, 0, 0); if (hfont == IntPtr.Zero) return Control.DefaultFont; else return Font.FromHfont(hfont); } set { Font newFont = value ?? Control.DefaultFont; if (newFont == this.font) return; this.font = newFont; IntPtr hfont = this.font.ToHfont(); // THINK: When should we delete this hfont? NativeMethods.SendMessage(this.Handle, WM_SETFONT, hfont, 0); } } private Font font; /// <summary> /// Gets or sets how many milliseconds the tooltip will remain visible while the mouse /// is still. /// </summary> public int AutoPopDelay { get { return this.GetDelayTime(TTDT_AUTOPOP); } set { this.SetDelayTime(TTDT_AUTOPOP, value); } } /// <summary> /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown. /// </summary> public int InitialDelay { get { return this.GetDelayTime(TTDT_INITIAL); } set { this.SetDelayTime(TTDT_INITIAL, value); } } /// <summary> /// Gets or sets how many milliseconds the mouse must be still before the tooltip is shown again. /// </summary> public int ReshowDelay { get { return this.GetDelayTime(TTDT_RESHOW); } set { this.SetDelayTime(TTDT_RESHOW, value); } } private int GetDelayTime(int which) { return (int)NativeMethods.SendMessage(this.Handle, TTM_GETDELAYTIME, which, 0); } private void SetDelayTime(int which, int value) { NativeMethods.SendMessage(this.Handle, TTM_SETDELAYTIME, which, value); } #endregion #region Commands /// <summary> /// Create the underlying control. /// </summary> /// <param name="parentHandle">The parent of the tooltip</param> /// <remarks>This does nothing if the control has already been created</remarks> public void Create(IntPtr parentHandle) { if (this.Handle != IntPtr.Zero) return; CreateParams cp = new CreateParams(); cp.ClassName = "tooltips_class32"; cp.Style = TTS_NOPREFIX; cp.ExStyle = WS_EX_TOPMOST; cp.Parent = parentHandle; this.CreateHandle(cp); // Ensure that multiline tooltips work correctly this.SetMaxWidth(); } /// <summary> /// Take a copy of the current settings and restore them when the /// tooltip is poppped. /// </summary> /// <remarks> /// This call cannot be nested. Subsequent calls to this method will be ignored /// until PopSettings() is called. /// </remarks> public void PushSettings() { // Ignore any nested calls if (this.settings != null) return; this.settings = new Hashtable(); this.settings["IsBalloon"] = this.IsBalloon; this.settings["HasBorder"] = this.HasBorder; this.settings["BackColor"] = this.BackColor; this.settings["ForeColor"] = this.ForeColor; this.settings["Title"] = this.Title; this.settings["StandardIcon"] = this.StandardIcon; this.settings["AutoPopDelay"] = this.AutoPopDelay; this.settings["InitialDelay"] = this.InitialDelay; this.settings["ReshowDelay"] = this.ReshowDelay; this.settings["Font"] = this.Font; } private Hashtable settings; /// <summary> /// Restore the settings of the tooltip as they were when PushSettings() /// was last called. /// </summary> public void PopSettings() { if (this.settings == null) return; this.IsBalloon = (bool)this.settings["IsBalloon"]; this.HasBorder = (bool)this.settings["HasBorder"]; this.BackColor = (Color)this.settings["BackColor"]; this.ForeColor = (Color)this.settings["ForeColor"]; this.Title = (string)this.settings["Title"]; this.StandardIcon = (StandardIcons)this.settings["StandardIcon"]; this.AutoPopDelay = (int)this.settings["AutoPopDelay"]; this.InitialDelay = (int)this.settings["InitialDelay"]; this.ReshowDelay = (int)this.settings["ReshowDelay"]; this.Font = (Font)this.settings["Font"]; this.settings = null; } /// <summary> /// Add the given window to those for whom this tooltip will show tips /// </summary> /// <param name="window">The window</param> public void AddTool(IWin32Window window) { NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_ADDTOOL, 0, lParam); } /// <summary> /// Hide any currently visible tooltip /// </summary> /// <param name="window"></param> public void PopToolTip(IWin32Window window) { NativeMethods.SendMessage(this.Handle, TTM_POP, 0, 0); } //public void Munge() { // NativeMethods.TOOLINFO tool = new NativeMethods.TOOLINFO(); // IntPtr result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETCURRENTTOOL, 0, tool); // System.Diagnostics.Trace.WriteLine("-"); // System.Diagnostics.Trace.WriteLine(result); // result = NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_GETBUBBLESIZE, 0, tool); // System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", result.ToInt32() >> 16, result.ToInt32() & 0xFFFF)); // NativeMethods.ChangeSize(this, result.ToInt32() & 0xFFFF, result.ToInt32() >> 16); // //NativeMethods.RECT r = new NativeMethods.RECT(); // //r.right // //IntPtr x = NativeMethods.SendMessageRECT(this.Handle, TTM_ADJUSTRECT, true, ref r); // //System.Diagnostics.Trace.WriteLine(String.Format("{0} {1} {2} {3}", r.left, r.top, r.right, r.bottom)); //} /// <summary> /// Remove the given window from those managed by this tooltip /// </summary> /// <param name="window"></param> public void RemoveToolTip(IWin32Window window) { NativeMethods.TOOLINFO lParam = this.MakeToolInfoStruct(window); NativeMethods.SendMessageTOOLINFO(this.Handle, TTM_DELTOOL, 0, lParam); } /// <summary> /// Set the maximum width of a tooltip string. /// </summary> public void SetMaxWidth() { this.SetMaxWidth(SystemInformation.MaxWindowTrackSize.Width); } /// <summary> /// Set the maximum width of a tooltip string. /// </summary> /// <remarks>Setting this ensures that line breaks in the tooltip are honoured.</remarks> public void SetMaxWidth(int maxWidth) { NativeMethods.SendMessage(this.Handle, TTM_SETMAXTIPWIDTH, 0, maxWidth); } #endregion #region Implementation /// <summary> /// Make a TOOLINFO structure for the given window /// </summary> /// <param name="window"></param> /// <returns>A filled in TOOLINFO</returns> private NativeMethods.TOOLINFO MakeToolInfoStruct(IWin32Window window) { NativeMethods.TOOLINFO toolinfo_tooltip = new NativeMethods.TOOLINFO(); toolinfo_tooltip.hwnd = window.Handle; toolinfo_tooltip.uFlags = TTF_IDISHWND | TTF_SUBCLASS; toolinfo_tooltip.uId = window.Handle; toolinfo_tooltip.lpszText = (IntPtr)(-1); // LPSTR_TEXTCALLBACK return toolinfo_tooltip; } /// <summary> /// Handle a WmNotify message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> protected virtual bool HandleNotify(ref Message msg) { //THINK: What do we have to do here? Nothing it seems :) //NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); //System.Diagnostics.Trace.WriteLine("HandleNotify"); //System.Diagnostics.Trace.WriteLine(nmheader.nhdr.code); //switch (nmheader.nhdr.code) { //} return false; } /// <summary> /// Handle a get display info message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> public virtual bool HandleGetDispInfo(ref Message msg) { //System.Diagnostics.Trace.WriteLine("HandleGetDispInfo"); this.SetMaxWidth(); ToolTipShowingEventArgs args = new ToolTipShowingEventArgs(); args.ToolTipControl = this; this.OnShowing(args); if (String.IsNullOrEmpty(args.Text)) return false; this.ApplyEventFormatting(args); NativeMethods.NMTTDISPINFO dispInfo = (NativeMethods.NMTTDISPINFO)msg.GetLParam(typeof(NativeMethods.NMTTDISPINFO)); dispInfo.lpszText = args.Text; dispInfo.hinst = IntPtr.Zero; if (args.RightToLeft == RightToLeft.Yes) dispInfo.uFlags |= TTF_RTLREADING; Marshal.StructureToPtr(dispInfo, msg.LParam, false); return true; } private void ApplyEventFormatting(ToolTipShowingEventArgs args) { if (!args.IsBalloon.HasValue && !args.BackColor.HasValue && !args.ForeColor.HasValue && args.Title == null && !args.StandardIcon.HasValue && !args.AutoPopDelay.HasValue && args.Font == null) return; this.PushSettings(); if (args.IsBalloon.HasValue) this.IsBalloon = args.IsBalloon.Value; if (args.BackColor.HasValue) this.BackColor = args.BackColor.Value; if (args.ForeColor.HasValue) this.ForeColor = args.ForeColor.Value; if (args.StandardIcon.HasValue) this.StandardIcon = args.StandardIcon.Value; if (args.AutoPopDelay.HasValue) this.AutoPopDelay = args.AutoPopDelay.Value; if (args.Font != null) this.Font = args.Font; if (args.Title != null) this.Title = args.Title; } /// <summary> /// Handle a TTN_LINKCLICK message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> /// <remarks>This cannot call base.WndProc() since the msg may have come from another control.</remarks> public virtual bool HandleLinkClick(ref Message msg) { //System.Diagnostics.Trace.WriteLine("HandleLinkClick"); return false; } /// <summary> /// Handle a TTN_POP message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> /// <remarks>This cannot call base.WndProc() since the msg may have come from another control.</remarks> public virtual bool HandlePop(ref Message msg) { //System.Diagnostics.Trace.WriteLine("HandlePop"); this.PopSettings(); return true; } /// <summary> /// Handle a TTN_SHOW message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> /// <remarks>This cannot call base.WndProc() since the msg may have come from another control.</remarks> public virtual bool HandleShow(ref Message msg) { //System.Diagnostics.Trace.WriteLine("HandleShow"); return false; } /// <summary> /// Handle a reflected notify message /// </summary> /// <param name="msg">The msg</param> /// <returns>True if the message has been handled</returns> protected virtual bool HandleReflectNotify(ref Message msg) { NativeMethods.NMHEADER nmheader = (NativeMethods.NMHEADER)msg.GetLParam(typeof(NativeMethods.NMHEADER)); switch (nmheader.nhdr.code) { case TTN_SHOW: //System.Diagnostics.Trace.WriteLine("reflect TTN_SHOW"); if (this.HandleShow(ref msg)) return true; break; case TTN_POP: //System.Diagnostics.Trace.WriteLine("reflect TTN_POP"); if (this.HandlePop(ref msg)) return true; break; case TTN_LINKCLICK: //System.Diagnostics.Trace.WriteLine("reflect TTN_LINKCLICK"); if (this.HandleLinkClick(ref msg)) return true; break; case TTN_GETDISPINFO: //System.Diagnostics.Trace.WriteLine("reflect TTN_GETDISPINFO"); if (this.HandleGetDispInfo(ref msg)) return true; break; } return false; } /// <summary> /// Mess with the basic message pump of the tooltip /// </summary> /// <param name="msg"></param> override protected void WndProc(ref Message msg) { //System.Diagnostics.Trace.WriteLine(String.Format("xx {0:x}", msg.Msg)); switch (msg.Msg) { case 0x4E: // WM_NOTIFY if (!this.HandleNotify(ref msg)) return; break; case 0x204E: // WM_REFLECT_NOTIFY if (!this.HandleReflectNotify(ref msg)) return; break; } base.WndProc(ref msg); } #endregion #region Events /// <summary> /// Tell the world that a tooltip is about to show /// </summary> public event EventHandler<ToolTipShowingEventArgs> Showing; /// <summary> /// Tell the world that a tooltip is about to disappear /// </summary> public event EventHandler<EventArgs> Pop; /// <summary> /// /// </summary> /// <param name="e"></param> protected virtual void OnShowing(ToolTipShowingEventArgs e) { if (this.Showing != null) this.Showing(this, e); } /// <summary> /// /// </summary> /// <param name="e"></param> protected virtual void OnPop(EventArgs e) { if (this.Pop != null) this.Pop(this, e); } #endregion } }
//--------------------------------------------------------------------- // Author: jachymko // // Description: DsCrackNames structures and enums. Based on code // by Ryan Dunn. // // http://dunnry.com/blog/DsCrackNamesInNET.aspx // // Creation Date: Jan 31, 2007 //--------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace Pscx.Interop { partial class NativeMethods { [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DsCrackNames( SafeDsHandle hDS, DsNameFlags flags, DsNameFormat formatOffered, DsNameFormat formatDesired, int cNames, string[] rpNames, out IntPtr ppResult //pointer to pointer of DS_NAME_RESULT ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void DsFreeNameResult( IntPtr pResult //DS_NAME_RESULTW* ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DsBind( string DomainControllerName, string DnsDomainName, out SafeDsHandle phDS ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DsBindWithCred( string DomainControllerName, string DnsDomainName, SafeDsCredentialsHandle AuthIdentity, out SafeDsHandle phDS ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DsMakePasswordCredentials( string User, string Domain, string Password, out SafeDsCredentialsHandle pAuthIdentity ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern void DsFreePasswordCredentials( IntPtr AuthIdentity ); [DllImport(Dll.NtdsApi, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int DsUnBind( ref IntPtr phDS ); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DsNameResult { public Int32 cItems; public IntPtr rItems; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DsNameResultItem { public Int32 status; public String pDomain; public String pName; } public enum DsNameFormat { /// <summary> /// Unknown Name Type /// </summary> Unknown = 0, /// <summary> /// eg: CN=User Name,OU=Users,DC=Example,DC=Microsoft,DC=Com /// </summary> DistinguishedName = 1, /// <summary> /// eg: Example\UserN /// Domain-only version includes trailing '\\'. /// </summary> NTAccountName = 2, /// <summary> /// Taken from 'displayName' attribute in AD. /// e.g.: First Last or Last, First /// </summary> DisplayName = 3, /// <summary> /// Reported obsolete - returns SPN form /// e.g.: [email protected] /// </summary> [Obsolete] DomainSimpleName = 4, /// <summary> /// Reported obsolete - returns SPN form /// e.g.: [email protected] /// </summary> [Obsolete] EnterpriseSimpleName = 5, /// <summary> /// String-ized GUID as returned by IIDFromString(). /// eg: {4fa050f0-f561-11cf-bdd9-00aa003a77b6} /// </summary> UniqueIDName = 6, /// <summary> /// eg: example.microsoft.com/software/user name /// Domain-only version includes trailing '/'. /// </summary> CanonicalName = 7, /// <summary> /// SPN format of name (taken from userPrincipalName attrib) /// eg: [email protected] /// </summary> UserPrincipalName = 8, /// <summary> /// Same as DS_CANONICAL_NAME except that rightmost '/' is /// replaced with '\n' - even in domain-only case. /// eg: example.microsoft.com/software\nuser name /// </summary> CanonicalNameEx = 9, /// <summary> /// eg: www/[email protected] - generalized service principal /// names. /// </summary> ServicePrincipalName = 10, /// <summary> /// This is the string representation of a SID. Invalid for formatDesired. /// See sddl.h for SID binary <--> text conversion routines. /// eg: S-1-5-21-397955417-626881126-188441444-501 /// </summary> SidOrSidHistoryName = 11, /// <summary> /// Pseudo-name format so GetUserNameEx can return the DNS domain name to /// a caller. This level is not supported by the DS APIs. /// </summary> DnsDomainName = 12 } public enum DsNameError { None = 0, // Generic processing error. Resolving = 1, // Couldn't find the name at all - or perhaps caller doesn't have // rights to see it. NotFound = 2, // Input name mapped to more than one output name. NotUnique = 3, // Input name found, but not the associated output format. // Can happen if object doesn't have all the required attributes. NoMapping = 4, // Unable to resolve entire name, but was able to determine which // domain object resides in. Thus DS_NAME_RESULT_ITEM?.pDomain // is valid on return. DomainOnly = 5, // Unable to perform a purely syntactical mapping at the client // without going out on the wire. NoSyntacticalMapping = 6, // The name is from an external trusted forest. TrustReferral = 7 } [Flags] public enum DsNameFlags { None = 0x0, // Perform a syntactical mapping at the client (if possible) without // going out on the wire. Returns DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING // if a purely syntactical mapping is not possible. SyntacticalOnly = 0x1, // Force a trip to the DC for evaluation, even if this could be // locally cracked syntactically. EvalAtDC = 0x2, // The call fails if the DC is not a GC VerifyGC = 0x4, // Enable cross forest trust referral TrustReferral = 0x8 } public class SafeDsHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeDsHandle() : base(true) { } protected override bool ReleaseHandle() { return NativeMethods.DsUnBind(ref handle) == NativeMethods.SUCCESS; } } public class SafeDsCredentialsHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeDsCredentialsHandle() : base(true) { } protected override bool ReleaseHandle() { NativeMethods.DsFreePasswordCredentials(handle); return true; } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using ESRI.ArcLogistics.DomainObjects; using ESRI.ArcLogistics.Routing.Json; namespace ESRI.ArcLogistics.Routing { /// <summary> /// AssignOrdersParams class. /// </summary> internal class AssignOrdersParams { internal AssignOrdersParams(ICollection<Order> ordersToAssign, ICollection<Route> targetRoutes, int? targetSequence, bool keepViolatedOrdersUnassigned) { _ordersToAssign = ordersToAssign; _targetRoutes = targetRoutes; _targetSequence = targetSequence; _keepViolatedOrdersUnassigned = keepViolatedOrdersUnassigned; if (targetSequence != null && ordersToAssign.Count > 0 && targetRoutes.Count > 0) { var targetIndex = targetSequence.Value - 1; var sourceOrder = ordersToAssign.First(); var stops = CommonHelpers.GetSortedStops(_targetRoutes.First()); this.TargetOrderSequence = stops .Take(targetIndex) .Where(stop => stop.StopType == StopType.Order && stop.AssociatedObject != sourceOrder) .Count() + 1; } } public ICollection<Order> OrdersToAssign { get { return _ordersToAssign; } } public ICollection<Route> TargetRoutes { get { return _targetRoutes; } } public int? TargetSequence { get { return _targetSequence; } } /// <summary> /// Gets target order sequence number value for "assign order /// with sequence number within the same route" operation. /// </summary> public int? TargetOrderSequence { get; private set; } public bool KeepViolatedOrdersUnassigned { get { return _keepViolatedOrdersUnassigned; } } private ICollection<Order> _ordersToAssign; private ICollection<Route> _targetRoutes; private int? _targetSequence; private bool _keepViolatedOrdersUnassigned; } /// <summary> /// AssignOrdersOperation class. /// </summary> internal class AssignOrdersOperation : VrpOperation { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public AssignOrdersOperation(SolverContext context, Schedule schedule, AssignOrdersParams inputParams, SolveOptions options) : base(context, schedule, options) { Debug.Assert(inputParams != null); _inputParams = inputParams; } public AssignOrdersOperation(SolverContext context, Schedule schedule, AssignOrdersParams inputParams, SolveOptions options, SolveRequestData reqData, AssignOrdersReqBuilder reqBuilder, List<Violation> violations) : base(context, schedule, options) { Debug.Assert(inputParams != null); Debug.Assert(reqData != null); Debug.Assert(reqBuilder != null); Debug.Assert(violations != null); _inputParams = inputParams; _reqData = reqData; _reqBuilder = reqBuilder; _violations = violations; } #endregion constructors #region public overrides /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public override SolveOperationType OperationType { get { return SolveOperationType.AssignOrders; } } public override Object InputParams { get { return _inputParams; } } public override bool CanGetResultWithoutSolve { get { return AssignOrdersOperationHelper.CanGetResultWithoutSolve( SolverContext, Schedule); } } public override SolveResult CreateResultWithoutSolve() { return AssignOrdersOperationHelper.CreateResultWithoutSolve( SolverContext, this.RequestData, _violations); } #endregion public overrides #region protected overrides /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// protected override SolveRequestData RequestData { get { if (_reqData == null) _reqData = _BuildRequestData(); return _reqData; } } protected override VrpRequestBuilder RequestBuilder { get { if (_reqBuilder == null) { _reqBuilder = new AssignOrdersReqBuilder( SolverContext, _unlockedOrdersToAssign, _unlockedTargetRoutes, _hasSrcRoutesNotInTargetRoutes); } return _reqBuilder; } } protected override SubmitVrpJobRequest BuildRequest( SolveRequestData reqData) { SubmitVrpJobRequest req = base.BuildRequest(reqData); _AdjustRequestWithTargetSequence(req, _inputParams, _violations); _jobRequest = req; return req; } protected override VrpOperation CreateOperation(SolveRequestData reqData, List<Violation> violations) { return new AssignOrdersOperation(base.SolverContext, base.Schedule, _inputParams, base.Options, reqData, _reqBuilder, violations); } protected override SolveRequestOptions RequestOptions { get { SolveRequestOptions opt = base.RequestOptions; opt.ConvertUnassignedOrders = true; return opt; } } protected override bool IsSolveSucceeded(int solveHR) { // special cases if (solveHR == (int)NAError.E_NA_VRP_SOLVER_PREASSIGNED_INFEASIBLE_ROUTES || solveHR == (int)NAError.E_NA_VRP_SOLVER_NO_SOLUTION) { return true; } return base.IsSolveSucceeded(solveHR); } protected override VrpOperation GetNextStepOperation( IList<RouteResult> routeResults, List<Violation> violations) { bool isNextStepRequired = true; // check if we need next step if (!_hasSrcRoutesNotInTargetRoutes || // target routes include all source routes violations.Count == 0 || // there are no violations _inputParams.KeepViolatedOrdersUnassigned) { isNextStepRequired = false; } VrpOperation nextStep = null; if (isNextStepRequired) nextStep = _CreateNextStepOperation(routeResults, violations); return nextStep; } protected override List<Violation> GetViolations(VrpResult vrpResult) { List<Violation> violations = base.GetViolations(vrpResult); Order violatedOrder = null; Violation specViolation = null; foreach (Violation v in violations) { if (v.ViolationType == ViolationType.Specialties && v.ObjectType == ViolatedObjectType.Order) { violatedOrder = v.AssociatedObject as Order; specViolation = v; break; } } if (violatedOrder != null) { List<Guid> specIds = new List<Guid>(); foreach (DriverSpecialty spec in violatedOrder.DriverSpecialties) { if (spec.Id != AssignOrdersReqBuilder.ASSIGNMENT_SPEC_ID) specIds.Add(spec.Id); } foreach (VehicleSpecialty spec in violatedOrder.VehicleSpecialties) { if (spec.Id != AssignOrdersReqBuilder.ASSIGNMENT_SPEC_ID) specIds.Add(spec.Id); } bool removeSpecViolation = true; if (specIds.Count > 0) { foreach (Guid specId in specIds) { foreach (GPFeature feature in _jobRequest.Routes.Features) { if (!_IsSpecBelongToRoute(specId, feature)) { removeSpecViolation = false; break; } } if (!removeSpecViolation) break; } } if (removeSpecViolation) violations.Remove(specViolation); } if (_violations != null) violations.AddRange(_violations); return violations; } #endregion protected overrides #region private static methods private static List<Order> _GetOrdersToConvert( ICollection<Route> affectedRoutes, ICollection<Order> unlockedOrders) { List<Order> orders = new List<Order>(); foreach (Route route in affectedRoutes) { foreach (Stop stop in route.Stops) { if (stop.StopType == StopType.Order) { Order order = stop.AssociatedObject as Order; if (!unlockedOrders.Contains(order)) orders.Add(order); // TODO: (?) check duplicates } } } return orders; } private static bool _IsSpecBelongToRoute(Guid specId, GPFeature rtFeature) { Guid routeSpecId; return _AttrToObjectId(NAAttribute.SPECIALTY_NAMES, rtFeature.Attributes, out routeSpecId) && routeSpecId == specId; } private static bool _AttrToObjectId(string attrName, AttrDictionary attrs, out Guid id) { id = Guid.Empty; bool res = false; try { id = new Guid(attrs.Get<string>(attrName)); res = true; } catch { } return res; } #endregion #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private SolveRequestData _BuildRequestData() { // validate target sequence conditions if (_inputParams.TargetSequence != null) { if (_inputParams.TargetSequence < 1) throw new RouteException(Properties.Messages.Error_InvalidTargetSequence); if (_inputParams.OrdersToAssign.Count != 1) throw new RouteException(Properties.Messages.Error_InvalidOrdersToAssignCount); if (_inputParams.TargetRoutes.Count != 1) throw new RouteException(Properties.Messages.Error_InvalidTargetRoutesCount); } // get unlocked target routes List<Route> unlockedTargetRoutes = new List<Route>(); foreach (Route route in _inputParams.TargetRoutes) { // TODO: (?) check if route belongs to processing schedule if (!route.IsLocked) unlockedTargetRoutes.Add(route); } // check if we have at least one unlocked route if (unlockedTargetRoutes.Count == 0) throw new RouteException(Properties.Messages.Error_InvalidUnlockedTargetRoutesCount); // get unlocked orders List<Order> unlockedOrdersToAssign = new List<Order>(); foreach (Order order in _inputParams.OrdersToAssign) { if (!SolveHelper.IsOrderLocked(order, Schedule)) unlockedOrdersToAssign.Add(order); } // check if we have at least one unlocked order if (unlockedOrdersToAssign.Count == 0) throw new RouteException(Properties.Messages.Error_InvalidUnlockedOrdersToAssignCount); // get source routes: // routes planned on schedule's day where each route has at // least one order from UnlockedOrdersToAssign assigned to it List<Route> sourceRoutes = _GetSourceRoutes(Schedule.Routes, unlockedOrdersToAssign); // routes to convert: TargetRoutes and SourceRoutes List<Route> routes = new List<Route>(); routes.AddRange(_inputParams.TargetRoutes); routes.AddRange(sourceRoutes); // orders to convert: // orders assigned to converting routes and unassigned orders // from UnlockedOrdersToAssign List<Order> candidateOrders = _GetAssignedOrders(routes); candidateOrders.AddRange(unlockedOrdersToAssign); var orders = new List<Order>(); foreach (var order in candidateOrders) { if (order.IsGeocoded) orders.Add(order); else { var violation = new Violation() { ViolationType = ViolationType.Ungeocoded, AssociatedObject = order }; _violations.Add(violation); } } // check if SourceRoutes contains routes that are not contained in // UnlockedTargetRoutes if (_inputParams.TargetSequence == null) { foreach (Route srcRoute in sourceRoutes) { if (!unlockedTargetRoutes.Contains(srcRoute)) { _hasSrcRoutesNotInTargetRoutes = true; break; } } } // get barriers planned on schedule's date ICollection<Barrier> barriers = SolverContext.Project.Barriers.Search( (DateTime)Schedule.PlannedDate); _sourceRoutes = sourceRoutes; _unlockedOrdersToAssign = unlockedOrdersToAssign; _unlockedTargetRoutes = unlockedTargetRoutes; _barriers = barriers; SolveRequestData reqData = new SolveRequestData(); reqData.Routes = new List<Route>(routes.Distinct()); reqData.Orders = new List<Order>(orders.Distinct()); reqData.Barriers = barriers; return reqData; } private List<Order> _GetAssignedOrders( ICollection<Route> routes) { List<Order> orders = new List<Order>(); foreach (Route route in routes) orders.AddRange(SolveHelper.GetAssignedOrders(route)); return orders; } private List<Route> _GetSourceRoutes( ICollection<Route> dayRoutes, ICollection<Order> unlockedOrders) { List<Route> routes = new List<Route>(); foreach (Route route in dayRoutes) { foreach (Stop stop in route.Stops) { if (stop.StopType == StopType.Order) { Order order = stop.AssociatedObject as Order; if (unlockedOrders.Contains(order)) { routes.Add(route); break; } } } } return routes; } private List<Route> _GetRoutesToUpdate( ICollection<Route> sourceRoutes, ICollection<Order> violatedOrders) { List<Route> routes = new List<Route>(); foreach (Route route in sourceRoutes) { foreach (Stop stop in route.Stops) { if (stop.StopType == StopType.Order) { Order order = stop.AssociatedObject as Order; if (violatedOrders.Contains(order)) { routes.Add(route); break; } } } } return routes; } private VrpOperation _CreateNextStepOperation( IList<RouteResult> routeResults, IList<Violation> violations) { // get violated orders List<Order> violatedOrders = new List<Order>(); foreach (Violation violation in violations) { if (violation.ObjectType == ViolatedObjectType.Order) violatedOrders.Add(violation.AssociatedObject as Order); } // get routes to update: // routes subset from SourceRouts collection where each route // has at least one order from VilatedOrders assigned to it List<Route> routesToUpdate = _GetRoutesToUpdate(_sourceRoutes, violatedOrders); VrpOperation nextStep = null; if (routesToUpdate.Count > 0) { // get processed orders: // orders that were successfully assigned to their new target routes List<Order> processedOrders = new List<Order>(); foreach (Order order in _unlockedOrdersToAssign) { if (!violatedOrders.Contains(order)) processedOrders.Add(order); } // get orders assigned to RoutesToUpdate List<Order> assignedOrders = _GetAssignedOrders(routesToUpdate); // exclude processed orders List<Order> ordersToUpdate = new List<Order>(); foreach (Order order in assignedOrders) { if (!processedOrders.Contains(order)) ordersToUpdate.Add(order); } if (ordersToUpdate.Count > 0) { SolveRequestData reqData = new SolveRequestData(); reqData.Routes = routesToUpdate; reqData.Orders = ordersToUpdate; reqData.Barriers = _barriers; nextStep = new AssignOrdersStep2(SolverContext, Schedule, reqData, _inputParams, routeResults, violations, base.Options); } } return nextStep; } private void _ShiftSequence(GPFeatureRecordSetLayer orders, int targetSeq) { foreach (GPFeature feature in orders.Features) { int sequence; if (feature.Attributes.TryGet<int>(NAAttribute.SEQUENCE, out sequence) && sequence >= targetSeq) { feature.Attributes.Set(NAAttribute.SEQUENCE, sequence + 1); } } } private bool _HasSequence(GPFeatureRecordSetLayer orders, int targetSeq) { bool found = false; foreach (GPFeature feature in orders.Features) { int sequence; if (feature.Attributes.TryGet<int>(NAAttribute.SEQUENCE, out sequence) && sequence == targetSeq) { found = true; break; } } return found; } private bool _FindTargetFeature(GPFeatureRecordSetLayer orders, Order order, out GPFeature orderFeature) { orderFeature = null; bool found = false; foreach (GPFeature feature in orders.Features) { string idStr = null; if (feature.Attributes.TryGet<string>(NAAttribute.NAME, out idStr)) { Guid id = new Guid(idStr); if (id == order.Id) { orderFeature = feature; found = true; break; } } } return found; } /// <summary> /// Adjusts VRP job request for cases when target sequence parameter is set. /// Does nothing if <paramref name="parameters"/> have no target sequence /// or order to be assigned is a violated one. /// </summary> /// <param name="request">Request to be adjusted.</param> /// <param name="parameters">Assign orders operation parameters to be /// used for adjusting the request.</param> /// <param name="violations">Collection of violations to be checked.</param> /// <exception cref="T:ESRI.ArcLogistics.Routing.RouteException">when /// <paramref name="request"/> does not contain order from /// <paramref name="parameters"/>.</exception> private void _AdjustRequestWithTargetSequence( SubmitVrpJobRequest request, AssignOrdersParams parameters, IEnumerable<Violation> violations) { Debug.Assert(request != null); Debug.Assert(parameters != null); Debug.Assert(violations != null); if (!parameters.TargetSequence.HasValue) { return; } Debug.Assert(parameters.OrdersToAssign.Count == 1); // must contain a single order Debug.Assert(parameters.TargetRoutes.Count == 1); // must contain a single route var orderToAssign = parameters.OrdersToAssign.First(); Debug.Assert(orderToAssign != null); if (violations.Any(v => v.AssociatedObject == orderToAssign)) { return; } GPFeature targetFeature; if (!_FindTargetFeature(request.Orders, orderToAssign, out targetFeature)) { throw new RouteException(Properties.Messages.Error_InternalRouteError); } // free place for new order position var targetSequence = parameters.TargetSequence.Value; Debug.Assert(targetSequence > 0); if (_HasSequence(request.Orders, targetSequence)) _ShiftSequence(request.Orders, targetSequence); // set assignment attributes var targetRoute = parameters.TargetRoutes.First(); Debug.Assert(targetRoute != null); targetFeature.Attributes.Set(NAAttribute.SEQUENCE, targetSequence); targetFeature.Attributes.Set(NAAttribute.ROUTE_NAME, targetRoute.Id.ToString()); targetFeature.Attributes.Set(NAAttribute.ASSIGNMENT_RULE, (int)NAOrderAssignmentRule.esriNAOrderPreserveRouteAndRelativeSequence); } #endregion private methods #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private AssignOrdersParams _inputParams; private ICollection<Order> _unlockedOrdersToAssign; private List<Route> _sourceRoutes; private List<Route> _unlockedTargetRoutes = new List<Route>(); private ICollection<Barrier> _barriers; private bool _hasSrcRoutesNotInTargetRoutes = false; private SubmitVrpJobRequest _jobRequest; private SolveRequestData _reqData; private AssignOrdersReqBuilder _reqBuilder; private List<Violation> _violations = new List<Violation>(); #endregion private fields } }
// Copyright 2011, 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. // Author: [email protected] (Anash P. Oommen) using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml; namespace Google.Api.Ads.Common.Lib { /// <summary> /// Represents an Ads API user. /// </summary> public abstract class AdsUser : Configurable { /// <summary> /// The list of SOAP listeners. /// </summary> List<SoapListener> listeners = new List<SoapListener>(); /// <summary> /// The OAuth provider. /// </summary> AdsOAuthProvider oAuthProvider = null; /// <summary> /// The application configuration for this user. /// </summary> private AppConfig config; /// <summary> /// Stores all the registered services and their factories. /// </summary> private Dictionary<string, ServiceFactory> serviceFactoryMap = new Dictionary<string, ServiceFactory>(); /// <summary> /// Gets or sets the OAuth provider. /// </summary> public AdsOAuthProvider OAuthProvider { get { return oAuthProvider; } set { oAuthProvider = value; } } /// <summary> /// Gets or sets the application configuration for this user. /// </summary> public AppConfig Config { get { return config; } } /// <summary> /// Gets the listeners. /// </summary> public List<SoapListener> Listeners { get { return listeners; } } /// <summary> /// Protected constructor. Use this version from a derived class if you want /// the library to use all settings from App.config. /// </summary> protected AdsUser(AppConfigBase config) : this (config, null) { } /// <summary> /// Protected constructor. Use this version from a derived class if you want /// the library to use all settings from App.config. /// </summary> /// <remarks>This constructor exists for backward compatibility purposes. /// </remarks> protected AdsUser(AppConfigBase config, Dictionary<string, string> headers) { this.config = config; MergeValuesFromHeaders(config, headers); RegisterServices(GetServiceTypes()); listeners.AddRange(GetDefaultListeners()); SetHeadersFromConfig(); config.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "OAuth2Mode") { SetOAuthProvider(config); } }; SetOAuthProvider(config); } /// <summary> /// Sets the OAuth provider. /// </summary> /// <param name="config">The config.</param> private void SetOAuthProvider(AppConfigBase config) { if (config.OAuth2Mode == OAuth2Flow.APPLICATION) { this.OAuthProvider = new OAuth2ProviderForApplications(config); } else { this.OAuthProvider = new OAuth2ProviderForServiceAccounts(config); } } /// <summary> /// Merges the values from headers and config into config instance. /// </summary> /// <param name="config">The appication configuration to use.</param> /// <param name="headers">The configuration headers.</param> private void MergeValuesFromHeaders(AppConfigBase config, Dictionary<string, string> headers) { if (headers != null) { Type configType = config.GetType(); foreach (string key in headers.Keys) { PropertyInfo propInfo = configType.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propInfo != null && propInfo.PropertyType == typeof(string)) { propInfo.SetValue(config, headers[key], null); } } } } /// <summary> /// Registers a family of services against this user. /// </summary> /// <param name="servicesFamilies">The family of services that should be /// registered against this user.</param> /// <remarks> /// Every family of services that should be registered with an AdsUser /// should be like follows: /// /// <code> /// public class vX { /// /// Type of the factory that can create services of SomeService.vX /// public Type factoryType = typeof(SomeServiceVxFactory); /// /// /// Various services under vX. /// /// public readonly ServiceSignature Service1; /// public readonly ServiceSignature Service2; /// } /// </code> /// /// The method uses reflection to /// - Find all the fields of type ServiceSignature. /// - Extract the factory type from factoryType field. /// - Register each found service type with the user. /// /// </remarks> protected void RegisterServices(Type[] servicesFamilies) { if (servicesFamilies == null) { return; } foreach (Type serviceFamily in servicesFamilies) { FieldInfo fieldInfo = serviceFamily.GetField("factoryType", BindingFlags.Public | BindingFlags.Static); Type serviceFactoryType = null; if (fieldInfo != null) { serviceFactoryType = (Type) fieldInfo.GetValue(null); } else { throw new ArgumentException(string.Format(CommonErrorMessages.MissingFactoryType, serviceFactoryType.AssemblyQualifiedName)); } if (serviceFactoryType != null) { ServiceFactory serviceFactory = (ServiceFactory) Activator.CreateInstance(serviceFactoryType); FieldInfo[] fields = serviceFamily.GetFields(); foreach (FieldInfo field in fields) { ServiceSignature signature = field.GetValue(null) as ServiceSignature; if (signature != null) { RegisterService(signature.Id, serviceFactory); } } } } } /// <summary> /// Gets all the service types to be registered against this user. /// </summary> /// <returns>The type of all service classes to be registered.</returns> public abstract Type[] GetServiceTypes(); /// <summary> /// Gets the default listeners. /// </summary> /// <returns>A list of default listeners</returns> public abstract SoapListener[] GetDefaultListeners(); /// <summary> /// Set the user headers from App.config. /// </summary> protected void SetHeadersFromConfig() { List<ServiceFactory> uniqueFactories = GetUniqueFactories(); foreach (ServiceFactory uniqueFactory in uniqueFactories) { uniqueFactory.Config = config; } } /// <summary> /// Gets the unique set of factories from the list of registered factories. /// </summary> private List<ServiceFactory> GetUniqueFactories() { List<ServiceFactory> uniqueFactories = new List<ServiceFactory>(); foreach (string id in serviceFactoryMap.Keys) { ServiceFactory serviceFactory = serviceFactoryMap[id]; if (!uniqueFactories.Contains(serviceFactory)) { uniqueFactories.Add(serviceFactory); } } return uniqueFactories; } /// <summary> /// Register a service with AdsUser. /// </summary> /// <param name="serviceId">A unique id for the service being registered. /// </param> /// <param name="serviceFactory">The factory that will create this /// service.</param> public void RegisterService(string serviceId, ServiceFactory serviceFactory) { serviceFactoryMap[serviceId] = serviceFactory; } /// <summary> /// Gets the service factory for a service. /// </summary> /// <param name="serviceId">The service id.</param> /// <returns>The service factory instance, or null if the service is not /// yet registered.</returns> public ServiceFactory GetServiceFactory(string serviceId) { return (serviceFactoryMap.ContainsKey(serviceId)) ? serviceFactoryMap[serviceId] : null; } /// <summary> /// Creates an object of the requested type of service. /// </summary> /// <param name="serviceSignature">Signature of the service being requested. /// </param> /// <returns>An object of the requested type of service. The /// caller should cast this object to the desired type.</returns> public AdsClient GetService(ServiceSignature serviceSignature) { return GetService(serviceSignature, String.Empty); } /// <summary> /// Creates an object of the requested type of service. /// </summary> /// <param name="serviceSignature">Signature of the service being requested. /// </param> /// <param name="serverUrl">The server url for Ads service.</param> /// <returns>An object of the requested type of service. The /// caller should cast this object to the desired type.</returns> public AdsClient GetService(ServiceSignature serviceSignature, string serverUrl) { Uri uri = null; if (!string.IsNullOrEmpty(serverUrl)) { uri = new Uri(serverUrl); } return GetService(serviceSignature, uri); } /// <summary> /// Creates an object of the requested type of service. /// </summary> /// <param name="serviceSignature">Signature of the service being requested. /// </param> /// <param name="serverUrl">The server url for Ads service.</param> /// <returns>An object of the requested type of service. The /// caller should cast this object to the desired type.</returns> [MethodImpl(MethodImplOptions.Synchronized)] public AdsClient GetService(ServiceSignature serviceSignature, Uri serverUrl) { if (serviceSignature == null) { throw new ArgumentNullException("serviceSignature"); } else { ServiceFactory factory = GetServiceFactory(serviceSignature.Id); if (factory == null) { throw new ArgumentException(string.Format( CommonErrorMessages.UnregisteredServiceTypeRequested, serviceSignature.ServiceName)); } else { return factory.CreateService(serviceSignature, this, serverUrl); } } } /// <summary> /// Calls the SOAP listeners. /// </summary> /// <param name="document">The SOAP message as an xml document.</param> /// <param name="service">The service for which call is being made.</param> /// <param name="direction">The direction of SOAP message.</param> internal void CallListeners(XmlDocument document, AdsClient service, SoapMessageDirection direction) { foreach (SoapListener listener in listeners) { listener.HandleMessage(document, service, direction); } } /// <summary> /// Initialize the SOAP listeners before an API call. /// </summary> internal void InitListeners() { foreach (SoapListener listener in listeners) { listener.InitForCall(); } } /// <summary> /// Cleans up the SOAP listeners after an API call. /// </summary> internal void CleanupListeners() { foreach (SoapListener listener in listeners) { listener.CleanupAfterCall(); } } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Contains all of the properties of a given object that are contained in a generic collection of properties. /// </summary> [ComVisible(true)] public class OAProperties : EnvDTE.Properties { private NodeProperties target; private Dictionary<string, EnvDTE.Property> properties = new Dictionary<string, EnvDTE.Property>(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public OAProperties(NodeProperties target) { Utilities.ArgumentNotNull("target", target); this.target = target; this.AddPropertiesFromType(target.GetType()); } /// <summary> /// Defines the NodeProperties object that contains the defines the properties. /// </summary> public NodeProperties Target { get { return this.target; } } #region EnvDTE.Properties /// <summary> /// Microsoft Internal Use Only. /// </summary> public virtual object Application { get { return null; } } /// <summary> /// Gets a value indicating the number of objects in the collection. /// </summary> public int Count { get { return properties.Count; } } /// <summary> /// Gets the top-level extensibility object. /// </summary> public virtual EnvDTE.DTE DTE { get { if (this.target.HierarchyNode == null || this.target.HierarchyNode.ProjectMgr == null || this.target.HierarchyNode.ProjectMgr.IsClosed || this.target.HierarchyNode.ProjectMgr.Site == null) { throw new InvalidOperationException(); } return this.target.HierarchyNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; } } /// <summary> /// Gets an enumeration for items in a collection. /// </summary> /// <returns>An enumerator. </returns> public IEnumerator GetEnumerator() { if (this.properties.Count == 0) { yield return new OANullProperty(this); } IEnumerator enumerator = this.properties.Values.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } /// <summary> /// Returns an indexed member of a Properties collection. /// </summary> /// <param name="index">The index at which to return a mamber.</param> /// <returns>A Property object.</returns> public virtual EnvDTE.Property Item(object index) { if (index is string) { string indexAsString = (string)index; if (this.properties.ContainsKey(indexAsString)) { return (EnvDTE.Property)this.properties[indexAsString]; } } else if (index is int) { int realIndex = (int)index - 1; if (realIndex >= 0 && realIndex < this.properties.Count) { IEnumerator enumerator = this.properties.Values.GetEnumerator(); int i = 0; while (enumerator.MoveNext()) { if (i++ == realIndex) { return (EnvDTE.Property)enumerator.Current; } } } } throw new ArgumentException(SR.GetString(SR.InvalidParameter), "index"); } /// <summary> /// Gets the immediate parent object of a Properties collection. /// </summary> public virtual object Parent { get { return null; } } #endregion #region methods /// <summary> /// Add properties to the collection of properties filtering only those properties which are com-visible and AutomationBrowsable /// </summary> /// <param name="targetType">The type of NodeProperties the we should filter on</param> private void AddPropertiesFromType(Type targetType) { Utilities.ArgumentNotNull("targetType", targetType); // If the type is not COM visible, we do not expose any of the properties if (!IsComVisible(targetType)) { return; } // Add all properties being ComVisible and AutomationVisible PropertyInfo[] propertyInfos = targetType.GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { if (!IsInMap(propertyInfo) && IsComVisible(propertyInfo) && IsAutomationVisible(propertyInfo)) { AddProperty(propertyInfo); } } } #endregion #region virtual methods /// <summary> /// Creates a new OAProperty object and adds it to the current list of properties /// </summary> /// <param name="propertyInfo">The property to be associated with an OAProperty object</param> private void AddProperty(PropertyInfo propertyInfo) { var attrs = propertyInfo.GetCustomAttributes(typeof(PropertyNameAttribute), false); string name = propertyInfo.Name; if (attrs.Length > 0) { name = ((PropertyNameAttribute)attrs[0]).Name; } this.properties.Add(name, new OAProperty(this, propertyInfo)); } #endregion #region helper methods private bool IsInMap(PropertyInfo propertyInfo) { return this.properties.ContainsKey(propertyInfo.Name); } private static bool IsAutomationVisible(PropertyInfo propertyInfo) { object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(AutomationBrowsableAttribute), true); foreach (AutomationBrowsableAttribute attr in customAttributesOnProperty) { if (!attr.Browsable) { return false; } } return true; } private static bool IsComVisible(Type targetType) { object[] customAttributesOnProperty = targetType.GetCustomAttributes(typeof(ComVisibleAttribute), true); foreach (ComVisibleAttribute attr in customAttributesOnProperty) { if (!attr.Value) { return false; } } return true; } private static bool IsComVisible(PropertyInfo propertyInfo) { object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(ComVisibleAttribute), true); foreach (ComVisibleAttribute attr in customAttributesOnProperty) { if (!attr.Value) { return false; } } return true; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Text; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class will create a text file which will contain the build log for that node /// </summary> public class DistributedFileLogger : IForwardingLogger { #region Constructors /// <summary> /// Default constructor. /// </summary> public DistributedFileLogger() : base() { } #endregion #region Methods public void Initialize(IEventSource eventSource, int nodeCount) { Initialize(eventSource); } /// <summary> /// Parses out the logger parameters from the Parameters string. /// </summary> private void ParseFileLoggerParameters() { if (this.Parameters != null) { string[] parameterComponents; parameterComponents = this.Parameters.Split(fileLoggerParameterDelimiters); for (int param = 0; param < parameterComponents.Length; param++) { if (parameterComponents[param].Length > 0) { string[] parameterAndValue = parameterComponents[param].Split(fileLoggerParameterValueSplitCharacter); if (parameterAndValue.Length > 1) { ApplyFileLoggerParameter(parameterAndValue[0], parameterAndValue[1]); } else { ApplyFileLoggerParameter(parameterAndValue[0], null); } } } } } /// <summary> /// Apply a parameter /// </summary> private void ApplyFileLoggerParameter(string parameterName, string parameterValue) { if (String.Compare("LOGFILE", parameterName, StringComparison.OrdinalIgnoreCase) == 0) { if(string.IsNullOrEmpty(parameterValue)) { string message = ResourceUtilities.FormatResourceString("InvalidFileLoggerFile", string.Empty, ResourceUtilities.FormatResourceString("logfilePathNullOrEmpty")); throw new LoggerException(message); } // Set log file to the right half of the parameter string and then remove it as it is going to be replaced in Initialize this.logFile = parameterValue; int indexOfParameter = parameters.IndexOf(parameterName + fileLoggerParameterValueSplitCharacter[0] + parameterValue, 0, StringComparison.OrdinalIgnoreCase); int length = ((string)(parameterName + fileLoggerParameterValueSplitCharacter[0] + parameterValue)).Length; // Check to see if the next char is a ; if so remove that as well if ((indexOfParameter + length) < parameters.Length && parameters[indexOfParameter + length] == ';') { length++; } parameters = parameters.Remove(indexOfParameter, length); } } public void Initialize(IEventSource eventSource) { ErrorUtilities.VerifyThrowArgumentNull(eventSource, "eventSource"); ParseFileLoggerParameters(); string fileName = logFile; try { // Create a new file logger and pass it some parameters to make the build log very detailed nodeFileLogger = new FileLogger(); string extension = Path.GetExtension(logFile); // If there is no extension add a default of .log to it if (String.IsNullOrEmpty(extension)) { logFile += ".log"; extension = ".log"; } // Log 0-based node id's, where 0 is the parent. This is a little unnatural for the reader, // but avoids confusion by being consistent with the Engine and any error messages it may produce. fileName = logFile.Replace(extension, nodeId + extension); nodeFileLogger.Verbosity = LoggerVerbosity.Detailed; nodeFileLogger.Parameters = "ShowEventId;ShowCommandLine;logfile=" + fileName + ";" + parameters; } catch (ArgumentException e) // Catching Exception, but rethrowing unless it's a well-known exception. { if(nodeFileLogger != null) { nodeFileLogger.Shutdown(); } string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", fileName, e.Message); throw new LoggerException(message, e, errorCode, helpKeyword); } // Say we are operating on 2 processors so we can get the multiproc output nodeFileLogger.Initialize(eventSource, 2); } public void Shutdown() { if (nodeFileLogger != null) { nodeFileLogger.Shutdown(); } } #endregion #region Properties // Need to access this for testing purposes internal FileLogger InternalFilelogger { get { return nodeFileLogger; } } public IEventRedirector BuildEventRedirector { get { return buildEventRedirector; } set { buildEventRedirector = value; } } // Node Id of the node which the forwarding logger is attached to public int NodeId { get { return nodeId; } set { nodeId = value; } } // The verbosity for now is set at detailed public LoggerVerbosity Verbosity { get { ErrorUtilities.VerifyThrow(false, "Should not be getting verbosity from distributed file logger"); return LoggerVerbosity.Detailed; } set { // Dont really care about verbosity at this point, but dont want to throw exception as it is set for all distributed loggers } } public string Parameters { get { return parameters; } set { parameters = value; } } #endregion #region Data // The file logger which will do the actual logging of the node's build output private FileLogger nodeFileLogger; // Reference for the central logger private IEventRedirector buildEventRedirector; // The Id of the node the forwardingLogger is attached to int nodeId; // Directory to place the log files, by default this will be in the current directory when the node is created string logFile = "msbuild.log"; // Logger parameters string parameters; // File logger parameters delimiters. private static readonly char[] fileLoggerParameterDelimiters = { ';' }; // File logger parameter value split character. private static readonly char[] fileLoggerParameterValueSplitCharacter = { '=' }; #endregion } }
//------------------------------------------------------------------------------ // <copyright file="ComponentDispatcherThread.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using MS.Win32; using System.Globalization; using System.Security; using System.Security.Permissions; using MS.Internal.WindowsBase; namespace System.Windows.Interop { /// <summary> /// This is a class used to implement per-thread instance of the ComponentDispatcher. ///</summary> internal class ComponentDispatcherThread { /// <summary> /// Returns true if one or more components has gone modal. /// Although once one component is modal a 2nd shouldn't. ///</summary> public bool IsThreadModal { get { return (_modalCount > 0); } } /// <summary> /// Returns "current" message. More exactly the last MSG Raised. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth to avoid leaking message information /// </SecurityNote> public MSG CurrentKeyboardMessage { [SecurityCritical] get { return _currentKeyboardMSG; } [SecurityCritical] set { _currentKeyboardMSG = value; } } /// <summary> /// A component calls this to go modal. Current thread wide only. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth /// </SecurityNote> [SecurityCritical] public void PushModal() { _modalCount += 1; if(1 == _modalCount) { if(null != _enterThreadModal) _enterThreadModal(null, EventArgs.Empty); } } /// <summary> /// A component calls this to end being modal. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth to avoid tampering with input /// </SecurityNote> [SecurityCritical] public void PopModal() { _modalCount -= 1; if(0 == _modalCount) { if(null != _leaveThreadModal) _leaveThreadModal(null, EventArgs.Empty); } if(_modalCount < 0) _modalCount = 0; // Throwing is also good } /// <summary> /// The message loop pumper calls this when it is time to do idle processing. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth /// </SecurityNote> [SecurityCritical] public void RaiseIdle() { if(null != _threadIdle) _threadIdle(null, EventArgs.Empty); } /// <summary> /// The message loop pumper calls this for every keyboard message. /// </summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth to prevent message leakage /// </SecurityNote> [SecurityCritical] public bool RaiseThreadMessage(ref MSG msg) { bool handled = false; if (null != _threadFilterMessage) _threadFilterMessage(ref msg, ref handled); if (handled) return handled; if (null != _threadPreprocessMessage) _threadPreprocessMessage(ref msg, ref handled); return handled; } /// <summary> /// Components register delegates with this event to handle /// thread idle processing. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> public event EventHandler ThreadIdle { [SecurityCritical] add { _threadIdle += value; } [SecurityCritical] remove { _threadIdle -= value; } } /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> [method:SecurityCritical] private event EventHandler _threadIdle; /// <summary> /// Components register delegates with this event to handle /// Keyboard Messages (first chance processing). ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> public event ThreadMessageEventHandler ThreadFilterMessage { [SecurityCritical] add { _threadFilterMessage += value; } [SecurityCritical] remove { _threadFilterMessage -= value; } } /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> [method:SecurityCritical] private event ThreadMessageEventHandler _threadFilterMessage; /// <summary> /// Components register delegates with this event to handle /// Keyboard Messages (second chance processing). ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> public event ThreadMessageEventHandler ThreadPreprocessMessage { [SecurityCritical] add { _threadPreprocessMessage += value; } [SecurityCritical] remove { _threadPreprocessMessage -= value; } } /// <summary> /// Adds the specified handler to the front of the invocation list /// of the PreprocessMessage event. /// <summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used /// to transmit input related information /// </SecurityNote> [SecurityCritical] public void AddThreadPreprocessMessageHandlerFirst(ThreadMessageEventHandler handler) { _threadPreprocessMessage = (ThreadMessageEventHandler)Delegate.Combine(handler, _threadPreprocessMessage); } /// <summary> /// Removes the first occurance of the specified handler from the /// invocation list of the PreprocessMessage event. /// <summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used /// to transmit input related information /// </SecurityNote> [SecurityCritical] public void RemoveThreadPreprocessMessageHandlerFirst(ThreadMessageEventHandler handler) { if (_threadPreprocessMessage != null) { ThreadMessageEventHandler newHandler = null; foreach (ThreadMessageEventHandler testHandler in _threadPreprocessMessage.GetInvocationList()) { if (testHandler == handler) { // This is the handler to remove. We should not check // for any more occurances. handler = null; } else { newHandler += testHandler; } } _threadPreprocessMessage = newHandler; } } /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> [method:SecurityCritical] private event ThreadMessageEventHandler _threadPreprocessMessage; /// <summary> /// Components register delegates with this event to handle /// a component on this thread has "gone modal", when previously none were. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> public event EventHandler EnterThreadModal { [SecurityCritical] add { _enterThreadModal += value; } [SecurityCritical] remove { _enterThreadModal -= value; } } /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> [method:SecurityCritical] private event EventHandler _enterThreadModal; /// <summary> /// Components register delegates with this event to handle /// all components on this thread are done being modal. ///</summary> /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> public event EventHandler LeaveThreadModal { [SecurityCritical] add { _leaveThreadModal += value; } [SecurityCritical] remove { _leaveThreadModal -= value; } } /// <SecurityNote> /// Critical: This is blocked off as defense in depth and is used to transmit input related information /// </SecurityNote> [method:SecurityCritical] private event EventHandler _leaveThreadModal; private int _modalCount; /// <SecurityNote> /// Critical: This holds the last message that was recieved /// </SecurityNote> [SecurityCritical] private MSG _currentKeyboardMSG; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.ComponentModel; using System.Xml; using System.IO; using System.Globalization; using System.Text; namespace System.Xml.Schema { /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSchemaDatatype { /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ValueType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract Type ValueType { get; } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.TokenizedType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract XmlTokenizedType TokenizedType { get; } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ParseValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr); /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.Variety"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual XmlSchemaDatatypeVariety Variety { get { return XmlSchemaDatatypeVariety.Atomic; } } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ChangeType1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual object ChangeType(object value, Type targetType) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } return ValueConverter.ChangeType(value, targetType); } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.ChangeType2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual object ChangeType(object value, Type targetType, IXmlNamespaceResolver namespaceResolver) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } if (namespaceResolver == null) { throw new ArgumentNullException(nameof(namespaceResolver)); } return ValueConverter.ChangeType(value, targetType, namespaceResolver); } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.TypeCode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual XmlTypeCode TypeCode { get { return XmlTypeCode.None; } } /// <include file='doc\XmlSchemaDatatype.uex' path='docs/doc[@for="XmlSchemaDatatype.IsDerivedFrom"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool IsDerivedFrom(XmlSchemaDatatype datatype) { return false; } internal abstract bool HasLexicalFacets { get; } internal abstract bool HasValueFacets { get; } internal abstract XmlValueConverter ValueConverter { get; } internal abstract RestrictionFacets Restriction { get; set; } internal abstract int Compare(object value1, object value2); internal abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, bool createAtomicValue); internal abstract Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue); internal abstract Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue); internal abstract FacetsChecker FacetsChecker { get; } internal abstract XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get; } internal abstract XmlSchemaDatatype DeriveByRestriction(XmlSchemaObjectCollection facets, XmlNameTable nameTable, XmlSchemaType schemaType); internal abstract XmlSchemaDatatype DeriveByList(XmlSchemaType schemaType); internal abstract void VerifySchemaValid(XmlSchemaObjectTable notations, XmlSchemaObject caller); internal abstract bool IsEqual(object o1, object o2); internal abstract bool IsComparable(XmlSchemaDatatype dtype); //Error message helper internal string TypeCodeString { get { string typeCodeString = string.Empty; XmlTypeCode typeCode = this.TypeCode; switch (this.Variety) { case XmlSchemaDatatypeVariety.List: if (typeCode == XmlTypeCode.AnyAtomicType) { //List of union typeCodeString = "List of Union"; } else { typeCodeString = "List of " + TypeCodeToString(typeCode); } break; case XmlSchemaDatatypeVariety.Union: typeCodeString = "Union"; break; case XmlSchemaDatatypeVariety.Atomic: if (typeCode == XmlTypeCode.AnyAtomicType) { typeCodeString = "anySimpleType"; } else { typeCodeString = TypeCodeToString(typeCode); } break; } return typeCodeString; } } internal string TypeCodeToString(XmlTypeCode typeCode) { switch (typeCode) { case XmlTypeCode.None: return "None"; case XmlTypeCode.Item: return "AnyType"; case XmlTypeCode.AnyAtomicType: return "AnyAtomicType"; case XmlTypeCode.String: return "String"; case XmlTypeCode.Boolean: return "Boolean"; case XmlTypeCode.Decimal: return "Decimal"; case XmlTypeCode.Float: return "Float"; case XmlTypeCode.Double: return "Double"; case XmlTypeCode.Duration: return "Duration"; case XmlTypeCode.DateTime: return "DateTime"; case XmlTypeCode.Time: return "Time"; case XmlTypeCode.Date: return "Date"; case XmlTypeCode.GYearMonth: return "GYearMonth"; case XmlTypeCode.GYear: return "GYear"; case XmlTypeCode.GMonthDay: return "GMonthDay"; case XmlTypeCode.GDay: return "GDay"; case XmlTypeCode.GMonth: return "GMonth"; case XmlTypeCode.HexBinary: return "HexBinary"; case XmlTypeCode.Base64Binary: return "Base64Binary"; case XmlTypeCode.AnyUri: return "AnyUri"; case XmlTypeCode.QName: return "QName"; case XmlTypeCode.Notation: return "Notation"; case XmlTypeCode.NormalizedString: return "NormalizedString"; case XmlTypeCode.Token: return "Token"; case XmlTypeCode.Language: return "Language"; case XmlTypeCode.NmToken: return "NmToken"; case XmlTypeCode.Name: return "Name"; case XmlTypeCode.NCName: return "NCName"; case XmlTypeCode.Id: return "Id"; case XmlTypeCode.Idref: return "Idref"; case XmlTypeCode.Entity: return "Entity"; case XmlTypeCode.Integer: return "Integer"; case XmlTypeCode.NonPositiveInteger: return "NonPositiveInteger"; case XmlTypeCode.NegativeInteger: return "NegativeInteger"; case XmlTypeCode.Long: return "Long"; case XmlTypeCode.Int: return "Int"; case XmlTypeCode.Short: return "Short"; case XmlTypeCode.Byte: return "Byte"; case XmlTypeCode.NonNegativeInteger: return "NonNegativeInteger"; case XmlTypeCode.UnsignedLong: return "UnsignedLong"; case XmlTypeCode.UnsignedInt: return "UnsignedInt"; case XmlTypeCode.UnsignedShort: return "UnsignedShort"; case XmlTypeCode.UnsignedByte: return "UnsignedByte"; case XmlTypeCode.PositiveInteger: return "PositiveInteger"; default: return typeCode.ToString(); } } internal static string ConcatenatedToString(object value) { Type t = value.GetType(); string stringValue = string.Empty; if (t == typeof(IEnumerable) && t != typeof(System.String)) { StringBuilder bldr = new StringBuilder(); IEnumerator enumerator = (value as IEnumerable).GetEnumerator(); if (enumerator.MoveNext()) { bldr.Append("{"); Object cur = enumerator.Current; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); } else { bldr.Append(cur.ToString()); } while (enumerator.MoveNext()) { bldr.Append(" , "); cur = enumerator.Current; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); } else { bldr.Append(cur.ToString()); } } bldr.Append("}"); stringValue = bldr.ToString(); } } else if (value is IFormattable) { stringValue = ((IFormattable)value).ToString("", CultureInfo.InvariantCulture); } else { stringValue = value.ToString(); } return stringValue; } internal static XmlSchemaDatatype FromXmlTokenizedType(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedType(token); } internal static XmlSchemaDatatype FromXmlTokenizedTypeXsd(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedTypeXsd(token); } internal static XmlSchemaDatatype FromXdrName(string name) { return DatatypeImplementation.FromXdrName(name); } internal static XmlSchemaDatatype DeriveByUnion(XmlSchemaSimpleType[] types, XmlSchemaType schemaType) { return DatatypeImplementation.DeriveByUnion(types, schemaType); } internal static string XdrCanonizeUri(string uri, XmlNameTable nameTable, SchemaNames schemaNames) { string canonicalUri; int offset = 5; bool convert = false; if (uri.Length > 5 && uri.StartsWith("uuid:", StringComparison.Ordinal)) { convert = true; } else if (uri.Length > 9 && uri.StartsWith("urn:uuid:", StringComparison.Ordinal)) { convert = true; offset = 9; } if (convert) { canonicalUri = nameTable.Add(uri.Substring(0, offset) + CultureInfo.InvariantCulture.TextInfo.ToUpper(uri.Substring(offset, uri.Length - offset))); } else { canonicalUri = uri; } if ( Ref.Equal(schemaNames.NsDataTypeAlias, canonicalUri) || Ref.Equal(schemaNames.NsDataTypeOld, canonicalUri) ) { canonicalUri = schemaNames.NsDataType; } else if (Ref.Equal(schemaNames.NsXdrAlias, canonicalUri)) { canonicalUri = schemaNames.NsXdr; } return canonicalUri; } #if PRIYAL private bool CanConvert(object value, System.Type inputType, System.Type defaultType, out string resId) { resId = null; decimal decimalValue; //TypeCode defaultTypeCode = Type.GetTypeCode(defaultType); if (IsIntegralType(this.TypeCode)){ switch (Type.GetTypeCode(inputType)) { case System.TypeCode.Single: case System.TypeCode.Double: decimalValue = new Decimal((double)value); goto case System.TypeCode.Decimal; case System.TypeCode.Decimal: decimalValue = (decimal)value; if (decimal.Truncate(decimalValue) != decimalValue) { //HasFractionDigits resId = SR.Sch_XmlTypeHasFraction; return false; } break; default: return true; } } else if (this.TypeCode == XmlTypeCode.Boolean) { if (IsNumericType(inputType)) { decimalValue = (decimal)value; if (decimalValue == 0 || decimalValue == 1) { return true; } resId = SR.Sch_InvalidBoolean; return false; } } return true; } private bool IsIntegralType(XmlTypeCode defaultTypeCode) { switch (defaultTypeCode) { case XmlTypeCode.Integer: case XmlTypeCode.NegativeInteger: case XmlTypeCode.NonNegativeInteger: case XmlTypeCode.NonPositiveInteger: case XmlTypeCode.PositiveInteger: case XmlTypeCode.Long: case XmlTypeCode.Int: case XmlTypeCode.Short: case XmlTypeCode.Byte: case XmlTypeCode.UnsignedLong: case XmlTypeCode.UnsignedInt: case XmlTypeCode.UnsignedShort: case XmlTypeCode.UnsignedByte: return true; default: return false; } } private bool IsNumericType(System.Type inputType) { switch (Type.GetTypeCode(inputType)) { case System.TypeCode.Decimal: case System.TypeCode.Double: case System.TypeCode.Single: case System.TypeCode.SByte: case System.TypeCode.Byte: case System.TypeCode.Int16: case System.TypeCode.Int32: case System.TypeCode.Int64: case System.TypeCode.UInt16: case System.TypeCode.UInt32: case System.TypeCode.UInt64: return true; default: return false; } } #endif } }
/* This is free software distributed under the terms of the MIT license, reproduced below. It may be used for any purpose, including commercial purposes, at absolutely no cost. No paperwork, no royalties, no GNU-like "copyleft" restrictions. Just download and enjoy. Copyright (c) 2014 Chimera Software, LLC 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 UnityEngine; using UnityEngine.UI; using System.Reflection; using System.Text.RegularExpressions; using System.Xml; using System.Collections; using TMPro; public class PUTMProInputField : PUTMPro { public string onValueChanged; public string placeholder; public int? characterLimit; public char? asteriskChar; public PlanetUnity2.InputFieldContentType? contentType; public PlanetUnity2.InputFieldLineType? lineType; public Color? selectionColor; public TMP_InputField field; public PUTMPro placeholderText; public PUGameObject inputField; public PUGameObject text; public PUGameObject textArea; private string regexValidation = null; public string GetValue() { if (field.text.Length > 0) { return field.text; } if (placeholderText != null && placeholderText.textGUI.text.Length > 0) { return placeholderText.textGUI.text; } return ""; } public override void gaxb_final(TB.TBXMLElement element, object _parent, Hashtable args) { base.gaxb_final (element, _parent, args); string attr; if (element != null) { attr = element.GetAttribute ("regexValidation"); if (attr != null) { regexValidation = attr; } attr = element.GetAttribute("onValueChanged"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { onValueChanged = (attr); } attr = element.GetAttribute("placeholder"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { placeholder = (attr); } attr = element.GetAttribute("characterLimit"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { characterLimit = (int)float.Parse(attr); } attr = element.GetAttribute("asteriskChar"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { asteriskChar = char.Parse(attr); } attr = element.GetAttribute("contentType"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { contentType = (PlanetUnity2.InputFieldContentType)System.Enum.Parse(typeof(PlanetUnity2.InputFieldContentType), attr); } attr = element.GetAttribute("lineType"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { lineType = (PlanetUnity2.InputFieldLineType)System.Enum.Parse(typeof(PlanetUnity2.InputFieldLineType), attr); } attr = element.GetAttribute("selectionColor"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { selectionColor = new Color().PUParse(attr); } } } // This is required for application-level subclasses public override void gaxb_init () { base.gaxb_init (); gaxb_addToParent(); } public override void gaxb_complete () { base.gaxb_complete (); // At this point, our gameObject is our "text" game object. We want to maneuver things around // until its like: // --> TMPro - Input Field // --> Text Area // --> Placeholder // --> Text // 0) first, swap out our TMPro text and replace our gameObject with one with the text field GameObject textGameObject = gameObject; // Next, we create a new gameObject, and put the Text-created gameObject inside me gameObject = new GameObject ("<TMP_InputField/>", typeof(RectTransform)); gameObject.transform.SetParent (textGameObject.transform.parent, false); UpdateRectTransform (); // 0.5) Create a game object for the field inputField = new PUGameObject(); inputField.title = "TMP_InputField"; inputField.SetFrame (0, 0, 0, 0, 0, 0, "stretch,stretch"); inputField.LoadIntoPUGameObject (this); // 1) create the hierarchy of stuff under me textArea = new PUGameObject(); textArea.title = "Text Area"; textArea.SetFrame (0, 0, 0, 0, 0, 0, "stretch,stretch"); textArea.LoadIntoPUGameObject (inputField); // 2) placeholder if (placeholder != null) { placeholderText = new PUTMPro (); placeholderText.title = "Placeholder"; placeholderText.value = this.placeholder; placeholderText.LoadIntoPUGameObject (textArea); placeholderText.textGUI.overflowMode = this.textGUI.overflowMode; placeholderText.textGUI.alignment = this.textGUI.alignment; placeholderText.textGUI.font = this.textGUI.font; placeholderText.textGUI.fontSize = this.textGUI.fontSize; placeholderText.textGUI.fontStyle = this.textGUI.fontStyle; placeholderText.textGUI.color = this.textGUI.color - new Color(0,0,0,0.5f); placeholderText.textGUI.lineSpacing = this.textGUI.lineSpacing; placeholderText.gameObject.FillParentUI (); } // 3) text text = new PUGameObject(); text.SetFrame (0, 0, 0, 0, 0, 0, "stretch,stretch"); text.LoadIntoPUGameObject (textArea); GameObject.Destroy (text.gameObject); text.gameObject = textGameObject; // Move the text to be the child of the input field textGameObject.name = "Text"; textGameObject.transform.SetParent (textArea.rectTransform, false); textGameObject.FillParentUI (); (textGameObject.transform as RectTransform).pivot = Vector2.zero; // now that we have the hierarchy, fille out the input field field = inputField.gameObject.AddComponent<TMP_InputField> (); field.transition = Selectable.Transition.None; field.targetGraphic = inputField.gameObject.AddComponent<InvisibleHitGraphic> (); field.textViewport = textArea.rectTransform; field.textComponent = textGUI; if (asteriskChar != null) { field.asteriskChar = asteriskChar.Value; } if (contentType == PlanetUnity2.InputFieldContentType.standard) { field.contentType = TMP_InputField.ContentType.Standard; } else if (contentType == PlanetUnity2.InputFieldContentType.autocorrected) { field.contentType = TMP_InputField.ContentType.Autocorrected; } else if (contentType == PlanetUnity2.InputFieldContentType.integer) { field.contentType = TMP_InputField.ContentType.IntegerNumber; } else if (contentType == PlanetUnity2.InputFieldContentType.number) { field.contentType = TMP_InputField.ContentType.DecimalNumber; } else if (contentType == PlanetUnity2.InputFieldContentType.alphanumeric) { field.contentType = TMP_InputField.ContentType.Alphanumeric; } else if (contentType == PlanetUnity2.InputFieldContentType.name) { field.contentType = TMP_InputField.ContentType.Name; } else if (contentType == PlanetUnity2.InputFieldContentType.email) { field.contentType = TMP_InputField.ContentType.EmailAddress; } else if (contentType == PlanetUnity2.InputFieldContentType.password) { field.contentType = TMP_InputField.ContentType.Password; field.inputType = TMP_InputField.InputType.Password; } else if (contentType == PlanetUnity2.InputFieldContentType.pin) { field.contentType = TMP_InputField.ContentType.Pin; } else if (contentType == PlanetUnity2.InputFieldContentType.custom) { field.contentType = TMP_InputField.ContentType.Custom; field.onValidateInput += ValidateInput; } if (lineType == PlanetUnity2.InputFieldLineType.single) { field.lineType = TMP_InputField.LineType.SingleLine; } else if (lineType == PlanetUnity2.InputFieldLineType.multiSubmit) { field.lineType = TMP_InputField.LineType.MultiLineSubmit; } else if (lineType == PlanetUnity2.InputFieldLineType.multiNewline) { field.lineType = TMP_InputField.LineType.MultiLineNewline; } if (characterLimit != null) { field.characterLimit = (int)characterLimit; } if (selectionColor != null) { field.selectionColor = selectionColor.Value; } // This is probably not the best way to do this, but 4.60.f1 removed the onSubmit event field.onEndEdit.AddListener ((value) => { if(onValueChanged != null){ NotificationCenter.postNotification (Scope (), this.onValueChanged, NotificationCenter.Args("sender", this)); } }); foreach (Object obj in gameObject.GetComponentsInChildren<DetectTextClickTMPro>()) { GameObject.Destroy (obj); } if (this.value == null) { this.value = ""; } field.text = this.value; if (placeholder != null) { field.placeholder = placeholderText.textGUI; } } // only allow what FanDuel server supports private char ValidateInput(string text, int charIndex, char addedChar) { // if we don't have a regex then we'll allow any char // if we do then check the added char against the specified regex if (regexValidation == null || Regex.IsMatch(""+addedChar, regexValidation)) return addedChar; return '\0'; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Threading; namespace System.Management { /// <summary> /// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.ObjectReady'/> event.</para> /// </summary> public delegate void ObjectReadyEventHandler(object sender, ObjectReadyEventArgs e); /// <summary> /// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.Completed'/> event.</para> /// </summary> public delegate void CompletedEventHandler(object sender, CompletedEventArgs e); /// <summary> /// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.Progress'/> event.</para> /// </summary> public delegate void ProgressEventHandler(object sender, ProgressEventArgs e); /// <summary> /// <para>Represents the method that will handle the <see cref='System.Management.ManagementOperationObserver.ObjectPut'/> event.</para> /// </summary> public delegate void ObjectPutEventHandler(object sender, ObjectPutEventArgs e); /// <summary> /// <para>Used to manage asynchronous operations and handle management information and events received asynchronously.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This sample demonstrates how to read a ManagementObject asychronously /// // using the ManagementOperationObserver object. /// /// class Sample_ManagementOperationObserver { /// public static int Main(string[] args) { /// /// //Set up a handler for the asynchronous callback /// ManagementOperationObserver observer = new ManagementOperationObserver(); /// MyHandler completionHandler = new MyHandler(); /// observer.Completed += new CompletedEventHandler(completionHandler.Done); /// /// //Invoke the asynchronous read of the object /// ManagementObject disk = new ManagementObject("Win32_logicaldisk='C:'"); /// disk.Get(observer); /// /// //For the purpose of this sample, we keep the main /// // thread alive until the asynchronous operation is completed. /// /// while (!completionHandler.IsComplete) { /// System.Threading.Thread.Sleep(500); /// } /// /// Console.WriteLine("Size= " + disk["Size"] + " bytes."); /// /// return 0; /// } /// /// public class MyHandler /// { /// private bool isComplete = false; /// /// public void Done(object sender, CompletedEventArgs e) { /// isComplete = true; /// } /// /// public bool IsComplete { /// get { /// return isComplete; /// } /// } /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to read a ManagementObject asychronously /// ' using the ManagementOperationObserver object. /// /// Class Sample_ManagementOperationObserver /// Overloads Public Shared Function Main(args() As String) As Integer /// /// 'Set up a handler for the asynchronous callback /// Dim observer As New ManagementOperationObserver() /// Dim completionHandler As New MyHandler() /// AddHandler observer.Completed, AddressOf completionHandler.Done /// /// ' Invoke the object read asynchronously /// Dim disk As New ManagementObject("Win32_logicaldisk='C:'") /// disk.Get(observer) /// /// ' For the purpose of this sample, we keep the main /// ' thread alive until the asynchronous operation is finished. /// While Not completionHandler.IsComplete Then /// System.Threading.Thread.Sleep(500) /// End While /// /// Console.WriteLine("Size = " + disk("Size").ToString() &amp; " bytes") /// /// Return 0 /// End Function /// /// Public Class MyHandler /// Private _isComplete As Boolean = False /// /// Public Sub Done(sender As Object, e As CompletedEventArgs) /// _isComplete = True /// End Sub 'Done /// /// Public ReadOnly Property IsComplete() As Boolean /// Get /// Return _isComplete /// End Get /// End Property /// End Class /// End Class /// </code> /// </example> public class ManagementOperationObserver { private readonly Hashtable m_sinkCollection; private readonly WmiDelegateInvoker delegateInvoker; /// <summary> /// <para> Occurs when a new object is available.</para> /// </summary> public event ObjectReadyEventHandler ObjectReady; /// <summary> /// <para> Occurs when an operation has completed.</para> /// </summary> public event CompletedEventHandler Completed; /// <summary> /// <para> Occurs to indicate the progress of an ongoing operation.</para> /// </summary> public event ProgressEventHandler Progress; /// <summary> /// <para> Occurs when an object has been successfully committed.</para> /// </summary> public event ObjectPutEventHandler ObjectPut; /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementOperationObserver'/> class. This is the default constructor.</para> /// </summary> public ManagementOperationObserver() { // We make our sink collection synchronized m_sinkCollection = new Hashtable(); delegateInvoker = new WmiDelegateInvoker(this); } /// <summary> /// <para> Cancels all outstanding operations.</para> /// </summary> public void Cancel() { // Cancel all the sinks we have - make a copy to avoid things // changing under our feet Hashtable copiedSinkTable = new Hashtable(); lock (m_sinkCollection) { IDictionaryEnumerator sinkEnum = m_sinkCollection.GetEnumerator(); try { sinkEnum.Reset(); while (sinkEnum.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)sinkEnum.Current; copiedSinkTable.Add(entry.Key, entry.Value); } } catch { } } // Now step through the copy and cancel everything try { IDictionaryEnumerator copiedSinkEnum = copiedSinkTable.GetEnumerator(); copiedSinkEnum.Reset(); while (copiedSinkEnum.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)copiedSinkEnum.Current; WmiEventSink eventSink = (WmiEventSink)entry.Value; try { eventSink.Cancel(); } catch { } } } catch { } } internal WmiEventSink GetNewSink( ManagementScope scope, object context) { try { WmiEventSink eventSink = WmiEventSink.GetWmiEventSink(this, context, scope, null, null); // Add it to our collection lock (m_sinkCollection) { m_sinkCollection.Add(eventSink.GetHashCode(), eventSink); } return eventSink; } catch { return null; } } internal bool HaveListenersForProgress { get { bool result = false; try { if (Progress != null) result = ((Progress.GetInvocationList()).Length > 0); } catch { } return result; } } internal WmiEventSink GetNewPutSink( ManagementScope scope, object context, string path, string className) { try { WmiEventSink eventSink = WmiEventSink.GetWmiEventSink(this, context, scope, path, className); // Add it to our collection lock (m_sinkCollection) { m_sinkCollection.Add(eventSink.GetHashCode(), eventSink); } return eventSink; } catch { return null; } } internal WmiGetEventSink GetNewGetSink( ManagementScope scope, object context, ManagementObject managementObject) { try { WmiGetEventSink eventSink = WmiGetEventSink.GetWmiGetEventSink(this, context, scope, managementObject); // Add it to our collection lock (m_sinkCollection) { m_sinkCollection.Add(eventSink.GetHashCode(), eventSink); } return eventSink; } catch { return null; } } internal void RemoveSink(WmiEventSink eventSink) { try { lock (m_sinkCollection) { m_sinkCollection.Remove(eventSink.GetHashCode()); } // Release the stub as we are now disconnected eventSink.ReleaseStub(); } catch { } } /// <summary> /// Fires the ObjectReady event to whomsoever is listening /// </summary> /// <param name="args"> </param> internal void FireObjectReady(ObjectReadyEventArgs args) { try { delegateInvoker.FireEventToDelegates(ObjectReady, args); } catch { } } internal void FireCompleted(CompletedEventArgs args) { try { delegateInvoker.FireEventToDelegates(Completed, args); } catch { } } internal void FireProgress(ProgressEventArgs args) { try { delegateInvoker.FireEventToDelegates(Progress, args); } catch { } } internal void FireObjectPut(ObjectPutEventArgs args) { try { delegateInvoker.FireEventToDelegates(ObjectPut, args); } catch { } } } internal class WmiEventState { private readonly Delegate d; private readonly ManagementEventArgs args; private readonly AutoResetEvent h; internal WmiEventState(Delegate d, ManagementEventArgs args, AutoResetEvent h) { this.d = d; this.args = args; this.h = h; } public Delegate Delegate { get { return d; } } public ManagementEventArgs Args { get { return args; } } public AutoResetEvent AutoResetEvent { get { return h; } } } /// <summary> /// This class handles the posting of events to delegates. For each event /// it queues a set of requests (one per target delegate) to the thread pool /// to handle the event. It ensures that no single delegate can throw /// an exception that prevents the event from reaching any other delegates. /// It also ensures that the sender does not signal the processing of the /// WMI event as "done" until all target delegates have signalled that they are /// done. /// </summary> internal class WmiDelegateInvoker { internal object sender; internal WmiDelegateInvoker(object sender) { this.sender = sender; } /// <summary> /// Custom handler for firing a WMI event to a list of delegates. We use /// the process thread pool to handle the firing. /// </summary> /// <param name="md">The MulticastDelegate representing the collection /// of targets for the event</param> /// <param name="args">The accompanying event arguments</param> internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args) { try { if (null != md) { foreach (Delegate d in md.GetInvocationList()) { try { d.DynamicInvoke(new object[] { this.sender, args }); } catch { } } } } catch { } } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class DeclaredAssets : SimObject { public DeclaredAssets() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.DeclaredAssetsCreateInstance()); } public DeclaredAssets(uint pId) : base(pId) { } public DeclaredAssets(string pName) : base(pName) { } public DeclaredAssets(IntPtr pObjPtr) : base(pObjPtr) { } public DeclaredAssets(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public DeclaredAssets(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _DeclaredAssetsGetPath(IntPtr assets); private static _DeclaredAssetsGetPath _DeclaredAssetsGetPathFunc; internal static IntPtr DeclaredAssetsGetPath(IntPtr assets) { if (_DeclaredAssetsGetPathFunc == null) { _DeclaredAssetsGetPathFunc = (_DeclaredAssetsGetPath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsGetPath"), typeof(_DeclaredAssetsGetPath)); } return _DeclaredAssetsGetPathFunc(assets); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _DeclaredAssetsSetPath(IntPtr assets, string path); private static _DeclaredAssetsSetPath _DeclaredAssetsSetPathFunc; internal static void DeclaredAssetsSetPath(IntPtr assets, string path) { if (_DeclaredAssetsSetPathFunc == null) { _DeclaredAssetsSetPathFunc = (_DeclaredAssetsSetPath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsSetPath"), typeof(_DeclaredAssetsSetPath)); } _DeclaredAssetsSetPathFunc(assets, path); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _DeclaredAssetsGetExtension(IntPtr assets); private static _DeclaredAssetsGetExtension _DeclaredAssetsGetExtensionFunc; internal static IntPtr DeclaredAssetsGetExtension(IntPtr assets) { if (_DeclaredAssetsGetExtensionFunc == null) { _DeclaredAssetsGetExtensionFunc = (_DeclaredAssetsGetExtension)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsGetExtension"), typeof(_DeclaredAssetsGetExtension)); } return _DeclaredAssetsGetExtensionFunc(assets); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _DeclaredAssetsSetExtension(IntPtr assets, string path); private static _DeclaredAssetsSetExtension _DeclaredAssetsSetExtensionFunc; internal static void DeclaredAssetsSetExtension(IntPtr assets, string path) { if (_DeclaredAssetsSetExtensionFunc == null) { _DeclaredAssetsSetExtensionFunc = (_DeclaredAssetsSetExtension)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsSetExtension"), typeof(_DeclaredAssetsSetExtension)); } _DeclaredAssetsSetExtensionFunc(assets, path); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _DeclaredAssetsGetRecurse(IntPtr assets); private static _DeclaredAssetsGetRecurse _DeclaredAssetsGetRecurseFunc; internal static bool DeclaredAssetsGetRecurse(IntPtr assets) { if (_DeclaredAssetsGetRecurseFunc == null) { _DeclaredAssetsGetRecurseFunc = (_DeclaredAssetsGetRecurse)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsGetRecurse"), typeof(_DeclaredAssetsGetRecurse)); } return _DeclaredAssetsGetRecurseFunc(assets); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _DeclaredAssetsSetRecurse(IntPtr assets, bool value); private static _DeclaredAssetsSetRecurse _DeclaredAssetsSetRecurseFunc; internal static void DeclaredAssetsSetRecurse(IntPtr assets, bool value) { if (_DeclaredAssetsSetRecurseFunc == null) { _DeclaredAssetsSetRecurseFunc = (_DeclaredAssetsSetRecurse)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsSetRecurse"), typeof(_DeclaredAssetsSetRecurse)); } _DeclaredAssetsSetRecurseFunc(assets, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _DeclaredAssetsCreateInstance(); private static _DeclaredAssetsCreateInstance _DeclaredAssetsCreateInstanceFunc; internal static IntPtr DeclaredAssetsCreateInstance() { if (_DeclaredAssetsCreateInstanceFunc == null) { _DeclaredAssetsCreateInstanceFunc = (_DeclaredAssetsCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "DeclaredAssetsCreateInstance"), typeof(_DeclaredAssetsCreateInstance)); } return _DeclaredAssetsCreateInstanceFunc(); } } #endregion #region Properties public string Path { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.DeclaredAssetsGetPath(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.DeclaredAssetsSetPath(ObjectPtr->ObjPtr, value); } } public string Extension { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.DeclaredAssetsGetExtension(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.DeclaredAssetsSetExtension(ObjectPtr->ObjPtr, value); } } public bool Recurse { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.DeclaredAssetsGetRecurse(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.DeclaredAssetsSetRecurse(ObjectPtr->ObjPtr, value); } } #endregion #region Methods #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // 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 NUnit.Framework; namespace NUnit.TestData.ExpectedExceptionData { [TestFixture] public class BaseException { [Test] [ExpectedException(typeof(ArgumentException))] public void BaseExceptionTest() { throw new Exception(); } } [TestFixture] public class DerivedException { [Test] [ExpectedException(typeof(Exception))] public void DerivedExceptionTest() { throw new ArgumentException(); } } [TestFixture] public class MismatchedException { [Test] [ExpectedException(typeof(ArgumentException))] public void MismatchedExceptionType() { throw new ArgumentOutOfRangeException(); } [Test] [ExpectedException(ExpectedException=typeof(ArgumentException))] public void MismatchedExceptionTypeAsNamedParameter() { throw new ArgumentOutOfRangeException(); } [Test] [ExpectedException(typeof(ArgumentException), UserMessage="custom message")] public void MismatchedExceptionTypeWithUserMessage() { throw new ArgumentOutOfRangeException(); } [Test] [ExpectedException("System.ArgumentException")] public void MismatchedExceptionName() { throw new ArgumentOutOfRangeException(); } [Test] [ExpectedException("System.ArgumentException", UserMessage="custom message")] public void MismatchedExceptionNameWithUserMessage() { throw new ArgumentOutOfRangeException(); } } [TestFixture] public class SetUpExceptionTests { [SetUp] public void Init() { throw new ArgumentException("SetUp Exception"); } [Test] [ExpectedException(typeof(ArgumentException))] public void Test() { } } [TestFixture] public class TearDownExceptionTests { [TearDown] public void CleanUp() { throw new ArgumentException("TearDown Exception"); } [Test] [ExpectedException(typeof(ArgumentException))] public void Test() {} } [TestFixture] public class TestThrowsExceptionFixture { [Test] public void TestThrow() { throw new Exception(); } } [TestFixture] public class TestDoesNotThrowExceptionFixture { [Test, ExpectedException("System.ArgumentException")] public void TestDoesNotThrowExceptionName() { } [Test, ExpectedException("System.ArgumentException", UserMessage="custom message")] public void TestDoesNotThrowExceptionNameWithUserMessage() { } [Test, ExpectedException( typeof( System.ArgumentException ) )] public void TestDoesNotThrowExceptionType() { } [Test, ExpectedException( typeof( System.ArgumentException ), UserMessage="custom message" )] public void TestDoesNotThrowExceptionTypeWithUserMessage() { } [Test, ExpectedException] public void TestDoesNotThrowUnspecifiedException() { } [Test, ExpectedException( UserMessage="custom message" )] public void TestDoesNotThrowUnspecifiedExceptionWithUserMessage() { } } [TestFixture] public class TestThrowsExceptionWithRightMessage { [Test] [ExpectedException(typeof(Exception), ExpectedMessage="the message")] public void TestThrow() { throw new Exception("the message"); } } [TestFixture] public class TestThrowsArgumentOutOfRangeException { [Test] [ExpectedException(typeof(ArgumentOutOfRangeException)) ] public void TestThrow() { #if NETCF || SILVERLIGHT throw new ArgumentOutOfRangeException("param", "the message"); #else throw new ArgumentOutOfRangeException("param", "actual value", "the message"); #endif } } [TestFixture] public class TestThrowsExceptionWithWrongMessage { [Test] [ExpectedException(typeof(Exception), ExpectedMessage="not the message")] public void TestThrow() { throw new Exception("the message"); } [Test] [ExpectedException( typeof(Exception), ExpectedMessage="not the message", UserMessage="custom message" )] public void TestThrowWithUserMessage() { throw new Exception("the message"); } } [TestFixture] public class TestAssertsBeforeThrowingException { [Test] [ExpectedException(typeof(Exception))] public void TestAssertFail() { Assert.Fail( "private message" ); } } public class ExceptionHandlerCalledClass : IExpectException { public bool HandlerCalled = false; public bool AlternateHandlerCalled = false; [Test, ExpectedException(typeof(ArgumentException))] public void ThrowsArgumentException() { throw new ArgumentException(); } [Test, ExpectedException(typeof(ArgumentException))] public void ThrowsCustomException() { throw new CustomException(); } class CustomException : Exception { } [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] public void ThrowsArgumentException_AlternateHandler() { throw new ArgumentException(); } [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] public void ThrowsCustomException_AlternateHandler() { throw new CustomException(); } [Test, ExpectedException(typeof(ArgumentException))] public void ThrowsSystemException() { throw new Exception(); } [Test, ExpectedException(typeof(ArgumentException), Handler = "AlternateExceptionHandler")] public void ThrowsSystemException_AlternateHandler() { throw new Exception(); } [Test, ExpectedException(typeof(ArgumentException), Handler = "DeliberatelyMissingHandler")] public void MethodWithBadHandler() { throw new ArgumentException(); } public void HandleException(Exception ex) { HandlerCalled = true; } public void AlternateExceptionHandler(Exception ex) { AlternateHandlerCalled = true; } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudio.Project { /// <summary> /// Defines an abstract class implementing IVsUpdateSolutionEvents interfaces. /// </summary> [CLSCompliant(false)] public abstract class UpdateSolutionEventsListener : IVsUpdateSolutionEvents3, IVsUpdateSolutionEvents2, IDisposable { #region fields /// <summary> /// The cookie associated to the the events based IVsUpdateSolutionEvents2. /// </summary> private uint solutionEvents2Cookie; /// <summary> /// The cookie associated to the theIVsUpdateSolutionEvents3 events. /// </summary> private uint solutionEvents3Cookie; /// <summary> /// The IVsSolutionBuildManager2 object controlling the update solution events. /// </summary> private IVsSolutionBuildManager2 solutionBuildManager; /// <summary> /// The associated service provider. /// </summary> private IServiceProvider serviceProvider; /// <summary> /// Flag determining if the object has been disposed. /// </summary> private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors /// <summary> /// Overloaded constructor. /// </summary> /// <param name="serviceProvider">A service provider.</param> protected UpdateSolutionEventsListener(IServiceProvider serviceProvider) { if(serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } this.serviceProvider = serviceProvider; this.solutionBuildManager = this.serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2; if(this.solutionBuildManager == null) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.solutionBuildManager.AdviseUpdateSolutionEvents(this, out this.solutionEvents2Cookie)); Debug.Assert(this.solutionBuildManager is IVsSolutionBuildManager3, "The solution build manager object implementing IVsSolutionBuildManager2 does not implement IVsSolutionBuildManager3"); ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.AdviseUpdateSolutionEvents3(this, out this.solutionEvents3Cookie)); } #endregion #region properties /// <summary> /// The associated service provider. /// </summary> protected IServiceProvider ServiceProvider { get { return this.serviceProvider; } } /// <summary> /// The solution build manager object controlling the solution events. /// </summary> protected IVsSolutionBuildManager2 SolutionBuildManager2 { get { return this.solutionBuildManager; } } /// <summary> /// The solution build manager object controlling the solution events. /// </summary> protected IVsSolutionBuildManager3 SolutionBuildManager3 { get { return (IVsSolutionBuildManager3)this.solutionBuildManager; } } #endregion #region IVsUpdateSolutionEvents3 Members /// <summary> /// Fired after the active solution config is changed (pOldActiveSlnCfg can be NULL). /// </summary> /// <param name="oldActiveSlnCfg">Old configuration.</param> /// <param name="newActiveSlnCfg">New configuration.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnAfterActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg) { return VSConstants.E_NOTIMPL; } /// <summary> /// Fired before the active solution config is changed (pOldActiveSlnCfg can be NULL /// </summary> /// <param name="oldActiveSlnCfg">Old configuration.</param> /// <param name="newActiveSlnCfg">New configuration.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnBeforeActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg) { return VSConstants.E_NOTIMPL; } #endregion #region IVsUpdateSolutionEvents2 Members /// <summary> /// Called when the active project configuration for a project in the solution has changed. /// </summary> /// <param name="hierarchy">The project whose configuration has changed.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnActiveProjectCfgChange(IVsHierarchy hierarchy) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called right before a project configuration begins to build. /// </summary> /// <param name="hierarchy">The project that is to be build.</param> /// <param name="configProject">A configuration project object.</param> /// <param name="configSolution">A configuration solution object.</param> /// <param name="action">The action taken.</param> /// <param name="cancel">A flag indicating cancel.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> /// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks> public int UpdateProjectCfg_Begin(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, ref int cancel) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called right after a project configuration is finished building. /// </summary> /// <param name="hierarchy">The project that has finished building.</param> /// <param name="configProject">A configuration project object.</param> /// <param name="configSolution">A configuration solution object.</param> /// <param name="action">The action taken.</param> /// <param name="success">Flag indicating success.</param> /// <param name="cancel">Flag indicating cancel.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> /// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks> public virtual int UpdateProjectCfg_Done(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, int success, int cancel) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called before any build actions have begun. This is the last chance to cancel the build before any building begins. /// </summary> /// <param name="cancelUpdate">Flag indicating cancel update.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Begin(ref int cancelUpdate) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called when a build is being cancelled. /// </summary> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Cancel() { return VSConstants.E_NOTIMPL; } /// <summary> /// Called when a build is completed. /// </summary> /// <param name="succeeded">true if no update actions failed.</param> /// <param name="modified">true if any update action succeeded.</param> /// <param name="cancelCommand">true if update actions were canceled.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called before the first project configuration is about to be built. /// </summary> /// <param name="cancelUpdate">A flag indicating cancel update.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_StartUpdate(ref int cancelUpdate) { return VSConstants.E_NOTIMPL; } #endregion #region IDisposable Members /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #region methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing">true if called from IDispose.Dispose; false if called from Finalizer.</param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if(!this.isDisposed) { // Synchronize calls to the Dispose simultaniously. lock(Mutex) { if(this.solutionEvents2Cookie != (uint)ShellConstants.VSCOOKIE_NIL) { ErrorHandler.ThrowOnFailure(this.solutionBuildManager.UnadviseUpdateSolutionEvents(this.solutionEvents2Cookie)); this.solutionEvents2Cookie = (uint)ShellConstants.VSCOOKIE_NIL; } if(this.solutionEvents3Cookie != (uint)ShellConstants.VSCOOKIE_NIL) { ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.UnadviseUpdateSolutionEvents3(this.solutionEvents3Cookie)); this.solutionEvents3Cookie = (uint)ShellConstants.VSCOOKIE_NIL; } this.isDisposed = true; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLoption = Interop.Http.CURLoption; using CurlProtocols = Interop.Http.CurlProtocols; using CURLProxyType = Interop.Http.curl_proxytype; using SafeCurlHandle = Interop.Http.SafeCurlHandle; using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle; using SafeCallbackHandle = Interop.Http.SafeCallbackHandle; using SeekCallback = Interop.Http.SeekCallback; using ReadWriteCallback = Interop.Http.ReadWriteCallback; using ReadWriteFunction = Interop.Http.ReadWriteFunction; using SslCtxCallback = Interop.Http.SslCtxCallback; using DebugCallback = Interop.Http.DebugCallback; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { /// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary> private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage> { /// <summary>Maximum content length where we'll use COPYPOSTFIELDS to let libcurl dup the content.</summary> private const int InMemoryPostContentLimit = 32 * 1024; // arbitrary limit; could be tweaked in the future based on experimentation /// <summary>Debugging flag used to enable CURLOPT_VERBOSE to dump to stderr when not redirecting it to the event source.</summary> private static readonly bool s_curlDebugLogging = Environment.GetEnvironmentVariable("CURLHANDLER_DEBUG_VERBOSE") == "true"; internal readonly CurlHandler _handler; internal readonly MultiAgent _associatedMultiAgent; internal readonly HttpRequestMessage _requestMessage; internal readonly CurlResponseMessage _responseMessage; internal readonly CancellationToken _cancellationToken; internal Stream _requestContentStream; internal long? _requestContentStreamStartingPosition; internal bool _inMemoryPostContent; internal SafeCurlHandle _easyHandle; private SafeCurlSListHandle _requestHeaders; internal SendTransferState _sendTransferState; internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference; private SafeCallbackHandle _callbackHandle; public EasyRequest(CurlHandler handler, MultiAgent agent, HttpRequestMessage requestMessage, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(handler != null, $"Expected non-null {nameof(handler)}"); Debug.Assert(agent != null, $"Expected non-null {nameof(agent)}"); Debug.Assert(requestMessage != null, $"Expected non-null {nameof(requestMessage)}"); _handler = handler; _associatedMultiAgent = agent; _requestMessage = requestMessage; _cancellationToken = cancellationToken; _responseMessage = new CurlResponseMessage(this); } /// <summary> /// Initialize the underlying libcurl support for this EasyRequest. /// This is separated out of the constructor so that we can take into account /// any additional configuration needed based on the request message /// after the EasyRequest is configured and so that error handling /// can be better handled in the caller. /// </summary> internal void InitializeCurl() { // Create the underlying easy handle SafeCurlHandle easyHandle = Interop.Http.EasyCreate(); if (easyHandle.IsInvalid) { throw new OutOfMemoryException(); } _easyHandle = easyHandle; // Before setting any other options, turn on curl's debug tracing // if desired. CURLOPT_VERBOSE may also be set subsequently if // EventSource tracing is enabled. if (s_curlDebugLogging) { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); } // Configure the handle SetUrl(); SetNetworkingOptions(); SetMultithreading(); SetTimeouts(); SetRedirection(); SetVerb(); SetVersion(); SetDecompressionOptions(); SetProxyOptions(_requestMessage.RequestUri); SetCredentialsOptions(_handler.GetCredentials(_requestMessage.RequestUri)); SetCookieOption(_requestMessage.RequestUri); SetRequestHeaders(); SetSslOptions(); } public void EnsureResponseMessagePublished() { // If the response message hasn't been published yet, do any final processing of it before it is. if (!Task.IsCompleted) { EventSourceTrace("Publishing response message"); // On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length // headers are removed from the response. Do the same thing here. DecompressionMethods dm = _handler.AutomaticDecompression; if (dm != DecompressionMethods.None) { HttpContentHeaders contentHeaders = _responseMessage.Content.Headers; IEnumerable<string> encodings; if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings)) { foreach (string encoding in encodings) { if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) || ((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase))) { contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding); contentHeaders.Remove(HttpKnownHeaderNames.ContentLength); break; } } } } } // Now ensure it's published. bool completedTask = TrySetResult(_responseMessage); Debug.Assert(completedTask || Task.Status == TaskStatus.RanToCompletion, "If the task was already completed, it should have been completed successfully; " + "we shouldn't be completing as successful after already completing as failed."); // If we successfully transitioned it to be completed, we also handed off lifetime ownership // of the response to the owner of the task. Transition our reference on the EasyRequest // to be weak instead of strong, so that we don't forcibly keep it alive. if (completedTask) { Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper"); _selfStrongToWeakReference.MakeWeak(); } } public void CleanupAndFailRequest(Exception error) { try { Cleanup(); } catch (Exception exc) { // This would only happen in an aggregious case, such as a Stream failing to seek when // it claims to be able to, but in case something goes very wrong, make sure we don't // lose the exception information. error = new AggregateException(error, exc); } finally { FailRequest(error); } } public void FailRequest(Exception error) { Debug.Assert(error != null, "Expected non-null exception"); EventSourceTrace("Failing request: {0}", error); var oce = error as OperationCanceledException; if (oce != null) { TrySetCanceled(oce.CancellationToken); } else { if (error is IOException || error is CurlException || error == null) { error = CreateHttpRequestException(error); } TrySetException(error); } // There's not much we can reasonably assert here about the result of TrySet*. // It's possible that the task wasn't yet completed (e.g. a failure while initiating the request), // it's possible that the task was already completed as success (e.g. a failure sending back the response), // and it's possible that the task was already completed as failure (e.g. we handled the exception and // faulted the task, but then tried to fault it again while finishing processing in the main loop). // Make sure the exception is available on the response stream so that it's propagated // from any attempts to read from the stream. _responseMessage.ResponseStream.SignalComplete(error); } public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up { // Don't dispose of the ResponseMessage.ResponseStream as it may still be in use // by code reading data stored in the stream. Also don't dispose of the request content // stream; that'll be handled by the disposal of the request content by the HttpClient, // and doing it here prevents reuse by an intermediate handler sitting between the client // and this handler. // However, if we got an original position for the request stream, we seek back to that position, // for the corner case where the stream does get reused before it's disposed by the HttpClient // (if the same request object is used multiple times from an intermediate handler, we'll be using // ReadAsStreamAsync, which on the same request object will return the same stream object, which // we've already advanced). if (_requestContentStream != null && _requestContentStream.CanSeek) { Debug.Assert(_requestContentStreamStartingPosition.HasValue, "The stream is seekable, but we don't have a starting position?"); _requestContentStream.Position = _requestContentStreamStartingPosition.GetValueOrDefault(); } // Dispose of the underlying easy handle. We're no longer processing it. _easyHandle?.Dispose(); // Dispose of the request headers if we had any. We had to keep this handle // alive as long as the easy handle was using it. We didn't need to do any // ref counting on the safe handle, though, as the only processing happens // in Process, which ensures the handle will be rooted while libcurl is // doing any processing that assumes it's valid. _requestHeaders?.Dispose(); // Dispose native callback resources _callbackHandle?.Dispose(); // Release any send transfer state, which will return its buffer to the pool _sendTransferState?.Dispose(); } private void SetUrl() { Uri requestUri = _requestMessage.RequestUri; long scopeId; if (IsLinkLocal(requestUri, out scopeId)) { // Uri.AbsoluteUri doesn't include the ScopeId/ZoneID, so if it is link-local, // we separately pass the scope to libcurl. EventSourceTrace("ScopeId: {0}", scopeId); SetCurlOption(CURLoption.CURLOPT_ADDRESS_SCOPE, scopeId); } EventSourceTrace("Url: {0}", requestUri); string idnHost = requestUri.IdnHost; string url = requestUri.Host == idnHost ? requestUri.AbsoluteUri : new UriBuilder(requestUri) { Host = idnHost }.Uri.AbsoluteUri; SetCurlOption(CURLoption.CURLOPT_URL, url); SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS)); } private static bool IsLinkLocal(Uri url, out long scopeId) { IPAddress ip; if (IPAddress.TryParse(url.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal) { scopeId = ip.ScopeId; return true; } scopeId = 0; return false; } private void SetNetworkingOptions() { // Disable the TCP Nagle algorithm. It's disabled by default starting with libcurl 7.50.2, // and when enabled has a measurably negative impact on latency in key scenarios // (e.g. POST'ing small-ish data). SetCurlOption(CURLoption.CURLOPT_TCP_NODELAY, 1L); } private void SetMultithreading() { SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L); } private void SetTimeouts() { // Set timeout limit on the connect phase. SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, int.MaxValue); // Override the default DNS cache timeout. libcurl defaults to a 1 minute // timeout, but we extend that to match the Windows timeout of 10 minutes. const int DnsCacheTimeoutSeconds = 10 * 60; SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds); } private void SetRedirection() { if (!_handler._automaticRedirection) { return; } SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L); CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ? CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols); SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections); EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections); } /// <summary> /// When a Location header is received along with a 3xx status code, it's an indication /// that we're likely to redirect. Prepare the easy handle in case we do. /// </summary> internal void SetPossibleRedirectForLocationHeader(string location) { // Reset cookies in case we redirect. Below we'll set new cookies for the // new location if we have any. if (_handler._useCookie) { SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero); } // Parse the location string into a relative or absolute Uri, then combine that // with the current request Uri to get the new location. var updatedCredentials = default(KeyValuePair<NetworkCredential, CURLAUTH>); Uri newUri; if (Uri.TryCreate(_requestMessage.RequestUri, location.Trim(), out newUri)) { // Just as with WinHttpHandler, for security reasons, we drop the server credential if it is // anything other than a CredentialCache. We allow credentials in a CredentialCache since they // are specifically tied to URIs. updatedCredentials = GetCredentials(newUri, _handler.Credentials as CredentialCache, s_orderedAuthTypes); // Reset proxy - it is possible that the proxy has different credentials for the new URI SetProxyOptions(newUri); // Set up new cookies if (_handler._useCookie) { SetCookieOption(newUri); } } // Set up the new credentials, either for the new Uri if we were able to get it, // or to empty creds if we couldn't. SetCredentialsOptions(updatedCredentials); // Set the headers again. This is a workaround for libcurl's limitation in handling // headers with empty values. SetRequestHeaders(); } private void SetContentLength(CURLoption lengthOption) { Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE); if (_requestMessage.Content == null) { // Tell libcurl there's no data to be sent. SetCurlOption(lengthOption, 0L); return; } long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength; if (contentLengthOpt != null) { long contentLength = contentLengthOpt.GetValueOrDefault(); if (contentLength <= int.MaxValue) { // Tell libcurl how much data we expect to send. SetCurlOption(lengthOption, contentLength); } else { // Similarly, tell libcurl how much data we expect to send. However, // as the amount is larger than a 32-bit value, switch to the "_LARGE" // equivalent libcurl options. SetCurlOption( lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE, contentLength); } EventSourceTrace("Set content length: {0}", contentLength); return; } // There is content but we couldn't determine its size. Don't set anything. } private void SetVerb() { EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method); if (_requestMessage.Method == HttpMethod.Put) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); SetContentLength(CURLoption.CURLOPT_INFILESIZE); } else if (_requestMessage.Method == HttpMethod.Head) { SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else if (_requestMessage.Method == HttpMethod.Post) { SetCurlOption(CURLoption.CURLOPT_POST, 1L); // Set the content length if we have one available. We must set POSTFIELDSIZE before setting // COPYPOSTFIELDS, as the setting of COPYPOSTFIELDS uses the size to know how much data to read // out; if POSTFIELDSIZE is not done before, COPYPOSTFIELDS will look for a null terminator, and // we don't necessarily have one. SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE); // For most content types and most HTTP methods, we use a callback that lets libcurl // get data from us if/when it wants it. However, as an optimization, for POSTs that // use content already known to be entirely in memory, we hand that data off to libcurl // ahead of time. This not only saves on costs associated with all of the async transfer // between the content and libcurl, it also lets libcurl do larger writes that can, for // example, enable fewer packets to be sent on the wire. var inMemContent = _requestMessage.Content as ByteArrayContent; ArraySegment<byte> contentSegment; if (inMemContent != null && inMemContent.TryGetBuffer(out contentSegment) && contentSegment.Count <= InMemoryPostContentLimit) // skip if we'd be forcing libcurl to allocate/copy a large buffer { // Only pre-provide the content if the content still has its ContentLength // and if that length matches the segment. If it doesn't, something has been overridden, // and we should rely on reading from the content stream to get the data. long? contentLength = inMemContent.Headers.ContentLength; if (contentLength.HasValue && contentLength.GetValueOrDefault() == contentSegment.Count) { _inMemoryPostContent = true; // Debug double-check array segment; this should all have been validated by the ByteArrayContent Debug.Assert(contentSegment.Array != null, "Expected non-null byte content array"); Debug.Assert(contentSegment.Count >= 0, $"Expected non-negative byte content count {contentSegment.Count}"); Debug.Assert(contentSegment.Offset >= 0, $"Expected non-negative byte content offset {contentSegment.Offset}"); Debug.Assert(contentSegment.Array.Length - contentSegment.Offset >= contentSegment.Count, $"Expected offset {contentSegment.Offset} + count {contentSegment.Count} to be within array length {contentSegment.Array.Length}"); // Hand the data off to libcurl with COPYPOSTFIELDS for it to copy out the data. (The alternative // is to use POSTFIELDS, which would mean we'd need to pin the array in the ByteArrayContent for the // duration of the request. Often with a ByteArrayContent, the data will be small and the copy cheap.) unsafe { fixed (byte* inMemContentPtr = contentSegment.Array) { SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, new IntPtr(inMemContentPtr + contentSegment.Offset)); EventSourceTrace("Set post fields rather than using send content callback"); } } } } } else if (_requestMessage.Method == HttpMethod.Trace) { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); if (_requestMessage.Content != null) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); SetContentLength(CURLoption.CURLOPT_INFILESIZE); } } } private void SetVersion() { Version v = _requestMessage.Version; if (v != null) { // Try to use the requested version, if a known version was explicitly requested. // If an unknown version was requested, we simply use libcurl's default. var curlVersion = (v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 : (v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 : (v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 : Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE; if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE) { // Ask libcurl to use the specified version if possible. CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion); if (c == CURLcode.CURLE_OK) { // Success. The requested version will be used. EventSourceTrace("HTTP version: {0}", v); } else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL) { // The requested version is unsupported. Fall back to using the default version chosen by libcurl. EventSourceTrace("Unsupported protocol: {0}", v); } else { // Some other error. Fail. ThrowIfCURLEError(c); } } } } private void SetDecompressionOptions() { if (!_handler.SupportsAutomaticDecompression) { return; } DecompressionMethods autoDecompression = _handler.AutomaticDecompression; bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0; bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0; if (gzip || deflate) { string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate : gzip ? EncodingNameGzip : EncodingNameDeflate; SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding); EventSourceTrace<string>("Encoding: {0}", encoding); } } internal void SetProxyOptions(Uri requestUri) { if (!_handler._useProxy) { // Explicitly disable the use of a proxy. This will prevent libcurl from using // any proxy, including ones set via environment variable. SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("UseProxy false, disabling proxy"); return; } if (_handler.Proxy == null) { // UseProxy was true, but Proxy was null. Let libcurl do its default handling, // which includes checking the http_proxy environment variable. EventSourceTrace("UseProxy true, Proxy null, using default proxy"); // Since that proxy set in an environment variable might require a username and password, // use the default proxy credentials if there are any. Currently only NetworkCredentials // are used, as we can't query by the proxy Uri, since we don't know it. SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential); return; } // Custom proxy specified. Uri proxyUri; try { // Should we bypass a proxy for this URI? if (_handler.Proxy.IsBypassed(requestUri)) { SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy"); return; } // Get the proxy Uri for this request. proxyUri = _handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { EventSourceTrace("GetProxy returned null, using default."); return; } } catch (PlatformNotSupportedException) { // WebRequest.DefaultWebProxy throws PlatformNotSupportedException, // in which case we should use the default rather than the custom proxy. EventSourceTrace("PlatformNotSupportedException from proxy, using default"); return; } // Configure libcurl with the gathered proxy information // uri.AbsoluteUri/ToString() omit IPv6 scope IDs. SerializationInfoString ensures these details // are included, but does not properly handle international hosts. As a workaround we check whether // the host is a link-local IP address, and based on that either return the SerializationInfoString // or the AbsoluteUri. (When setting the request Uri itself, we instead use CURLOPT_ADDRESS_SCOPE to // set the scope id and the url separately, avoiding these issues and supporting versions of libcurl // prior to v7.37 that don't support parsing scope IDs out of the url's host. As similar feature // doesn't exist for proxies.) IPAddress ip; string proxyUrl = IPAddress.TryParse(proxyUri.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal ? proxyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped) : proxyUri.AbsoluteUri; EventSourceTrace<string>("Proxy: {0}", proxyUrl); SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP); SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUrl); SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials( proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes); SetProxyCredentials(credentialScheme.Key); } private void SetProxyCredentials(NetworkCredential credentials) { if (credentials == CredentialCache.DefaultCredentials) { // No "default credentials" on Unix; nop just like UseDefaultCredentials. EventSourceTrace("DefaultCredentials set for proxy. Skipping."); } else if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } // Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode // them in order to allow, for example, a colon in the username. string credentialText = string.IsNullOrEmpty(credentials.Domain) ? WebUtility.UrlEncode(credentials.UserName) + ":" + WebUtility.UrlEncode(credentials.Password) : string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain)); EventSourceTrace("Proxy credentials set."); SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair) { if (credentialSchemePair.Key == null) { EventSourceTrace("Credentials cleared."); SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero); SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero); return; } NetworkCredential credentials = credentialSchemePair.Key; CURLAUTH authScheme = credentialSchemePair.Value; string userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : credentials.Domain + "\\" + credentials.UserName; SetCurlOption(CURLoption.CURLOPT_USERNAME, userName); SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme); if (credentials.Password != null) { SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password); } EventSourceTrace("Credentials set."); } internal void SetCookieOption(Uri uri) { if (!_handler._useCookie) { return; } string cookieValues = _handler.CookieContainer.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookieValues)) { SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues); EventSourceTrace<string>("Cookies: {0}", cookieValues); } } internal void SetRequestHeaders() { var slist = new SafeCurlSListHandle(); // Add content request headers if (_requestMessage.Content != null) { SetChunkedModeForSend(_requestMessage); AddRequestHeaders(_requestMessage.Content.Headers, slist); if (_requestMessage.Content.Headers.ContentType == null) { // Remove the Content-Type header libcurl adds by default. ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType)); } } // Add request headers AddRequestHeaders(_requestMessage.Headers, slist); // Since libcurl always adds a Transfer-Encoding header, we need to explicitly block // it if caller specifically does not want to set the header if (_requestMessage.Headers.TransferEncodingChunked.HasValue && !_requestMessage.Headers.TransferEncodingChunked.Value) { ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding)); } // Since libcurl adds an Expect header if it sees enough post data, we need to explicitly block // it if caller specifically does not want to set the header if (_requestMessage.Headers.ExpectContinue.HasValue && !_requestMessage.Headers.ExpectContinue.Value) { ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoExpect)); } if (!slist.IsInvalid) { SafeCurlSListHandle prevList = _requestHeaders; _requestHeaders = slist; SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist); prevList?.Dispose(); } else { slist.Dispose(); } } private void SetSslOptions() { // SSL Options should be set regardless of the type of the original request, // in case an http->https redirection occurs. // // While this does slow down the theoretical best path of the request the code // to decide that we need to register the callback is more complicated than, and // potentially more expensive than, just always setting the callback. SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions); } internal void SetCurlCallbacks( IntPtr easyGCHandle, ReadWriteCallback receiveHeadersCallback, ReadWriteCallback sendCallback, SeekCallback seekCallback, ReadWriteCallback receiveBodyCallback, DebugCallback debugCallback) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } // Add callback for processing headers Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Header, receiveHeadersCallback, easyGCHandle, ref _callbackHandle); ThrowOOMIfInvalid(_callbackHandle); // If we're sending data as part of the request and it wasn't already added as // in-memory data, add callbacks for sending request data. if (!_inMemoryPostContent && _requestMessage.Content != null) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Read, sendCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); Interop.Http.RegisterSeekCallback( _easyHandle, seekCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); } // If we're expecting any data in response, add a callback for receiving body data if (_requestMessage.Method != HttpMethod.Head) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Write, receiveBodyCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); } if (NetEventSource.IsEnabled) { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); CURLcode curlResult = Interop.Http.RegisterDebugCallback( _easyHandle, debugCallback, easyGCHandle, ref _callbackHandle); Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers"); if (curlResult != CURLcode.CURLE_OK) { EventSourceTrace("Failed to register debug callback."); } } } internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } return Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle); } private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle) { foreach (KeyValuePair<string, IEnumerable<string>> header in headers) { if (string.Equals(header.Key, HttpKnownHeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase)) { // avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE continue; } string headerKeyAndValue; string[] values = header.Value as string[]; Debug.Assert(values != null, "Implementation detail, but expected Value to be a string[]"); if (values != null && values.Length < 2) { // 0 or 1 values headerKeyAndValue = values.Length == 0 || string.IsNullOrEmpty(values[0]) ? header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent header.Key + ": " + values[0]; } else { // Either Values wasn't a string[], or it had 2 or more items. Both are handled by GetHeaderString. string headerValue = headers.GetHeaderString(header.Key); headerKeyAndValue = string.IsNullOrEmpty(headerValue) ? header.Key + ";" : // semicolon needed by libcurl; see above header.Key + ": " + headerValue; } ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue)); } } internal void SetCurlOption(CURLoption option, string value) { ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, long value) { ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, IntPtr value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, SafeHandle value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } private static void ThrowOOMIfFalse(bool appendResult) { if (!appendResult) { ThrowOOM(); } } private static void ThrowOOMIfInvalid(SafeHandle handle) { if (handle.IsInvalid) { ThrowOOM(); } } private static void ThrowOOM() { throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false)); } internal sealed class SendTransferState : IDisposable { internal byte[] Buffer { get; private set; } internal int Offset { get; set; } internal int Count { get; set; } internal Task<int> Task { get; private set; } public SendTransferState(int bufferLength) { Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}"); Buffer = ArrayPool<byte>.Shared.Rent(bufferLength); } public void Dispose() { byte[] b = Buffer; if (b != null) { Buffer = null; ArrayPool<byte>.Shared.Return(b); } } public void SetTaskOffsetCount(Task<int> task, int offset, int count) { Debug.Assert(offset >= 0, "Offset should never be negative"); Debug.Assert(count >= 0, "Count should never be negative"); Debug.Assert(offset <= count, "Offset should never be greater than count"); Task = task; Offset = offset; Count = count; } } internal void StoreLastEffectiveUri() { IntPtr urlCharPtr; // do not free; will point to libcurl private memory CURLcode urlResult = Interop.Http.EasyGetInfoPointer(_easyHandle, Interop.Http.CURLINFO.CURLINFO_EFFECTIVE_URL, out urlCharPtr); if (urlResult == CURLcode.CURLE_OK && urlCharPtr != IntPtr.Zero) { string url = Marshal.PtrToStringAnsi(urlCharPtr); if (url != _requestMessage.RequestUri.OriginalString) { Uri finalUri; if (Uri.TryCreate(url, UriKind.Absolute, out finalUri)) { _requestMessage.RequestUri = finalUri; } } return; } Debug.Fail("Expected to be able to get the last effective Uri from libcurl"); } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName); } } } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit { using System; using System.Threading; using System.Threading.Tasks; using GreenPipes; using Util; public static class EndpointConventionExtensions { /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, T message, CancellationToken cancellationToken = default(CancellationToken)) where T : class { Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, T message, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, T message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send(this ISendEndpointProvider provider, object message, CancellationToken cancellationToken = default(CancellationToken)) { if (message == null) throw new ArgumentNullException(nameof(message)); var messageType = message.GetType(); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="messageType"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send(this ISendEndpointProvider provider, object message, Type messageType, CancellationToken cancellationToken = default(CancellationToken)) { Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, messageType, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="messageType"></param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send(this ISendEndpointProvider provider, object message, Type messageType, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) { if (message == null) throw new ArgumentNullException(nameof(message)); if (messageType == null) throw new ArgumentNullException(nameof(messageType)); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, messageType, pipe, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <param name="provider"></param> /// <param name="message">The message</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send(this ISendEndpointProvider provider, object message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) { if (message == null) throw new ArgumentNullException(nameof(message)); var messageType = message.GetType(); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="values"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, object values, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var message = TypeMetadataCache<T>.InitializeFromObject(values); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send<T>(values, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="values"></param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, object values, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var message = TypeMetadataCache<T>.InitializeFromObject(values); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send(values, pipe, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="provider"></param> /// <param name="values"></param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static async Task Send<T>(this ISendEndpointProvider provider, object values, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var message = TypeMetadataCache<T>.InitializeFromObject(values); Uri destinationAddress; if (!EndpointConvention.TryGetDestinationAddress(message, out destinationAddress)) { throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found"); } var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false); await endpoint.Send<T>(values, pipe, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class Goto : GotoExpressionTests { [Theory] [PerCompilationType(nameof(ConstantValueData))] public void JustGotoValue(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Goto(target, Expression.Constant(value)), Expression.Label(target, Expression.Default(type)) ); Expression equals = Expression.Equal(Expression.Constant(value), block); Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void GotoToMiddle(bool useInterpreter) { // The behaviour is that return jumps to a label, but does not necessarily leave a block. LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Goto(target, Expression.Constant(1)), Expression.Label(target, Expression.Constant(2)), Expression.Constant(3) ); Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void GotoJumps(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Goto(target, Expression.Constant(value)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetGotoHasNoValue(Type type) { LabelTarget target = Expression.Label(type); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(target)); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetGotoHasNoValueTypeExplicit(Type type) { LabelTarget target = Expression.Label(type); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(target, type)); } [Theory] [ClassData(typeof(CompilationTypes))] public void GotoVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Goto(target), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [ClassData(typeof(CompilationTypes))] public void GotoExplicitVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Goto(target, typeof(void)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(TypesData))] public void NullValueOnNonVoidGoto(Type type) { AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type))); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type), default(Expression))); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(type), null, type)); } [Theory] [MemberData(nameof(ConstantValueData))] public void ExplicitNullTypeWithValue(object value) { AssertExtensions.Throws<ArgumentException>("target", () => Expression.Goto(Expression.Label(value.GetType()), default(Type))); } [Fact] public void UnreadableLabel() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); LabelTarget target = Expression.Label(typeof(string)); AssertExtensions.Throws<ArgumentException>("value", () => Expression.Goto(target, value)); AssertExtensions.Throws<ArgumentException>("value", () => Expression.Goto(target, value, typeof(string))); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void CanAssignAnythingToVoid(object value, bool useInterpreter) { LabelTarget target = Expression.Label(); BlockExpression block = Expression.Block( Expression.Goto(target, Expression.Constant(value)), Expression.Label(target) ); Assert.Equal(typeof(void), block.Type); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(NonObjectAssignableConstantValueData))] public void CannotAssignValueTypesToObject(object value) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Goto(Expression.Label(typeof(object)), Expression.Constant(value))); } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValueData))] public void ExplicitTypeAssigned(object value, bool useInterpreter) { LabelTarget target = Expression.Label(typeof(object)); BlockExpression block = Expression.Block( Expression.Goto(target, Expression.Constant(value), typeof(object)), Expression.Label(target, Expression.Default(typeof(object))) ); Assert.Equal(typeof(object), block.Type); Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)()); } [Fact] public void GotoQuotesIfNecessary() { LabelTarget target = Expression.Label(typeof(Expression<Func<int>>)); BlockExpression block = Expression.Block( Expression.Goto(target, Expression.Lambda<Func<int>>(Expression.Constant(0))), Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>))) ); Assert.Equal(typeof(Expression<Func<int>>), block.Type); } [Fact] public void UpdateSameIsSame() { LabelTarget target = Expression.Label(typeof(int)); Expression value = Expression.Constant(0); GotoExpression ret = Expression.Goto(target, value); Assert.Same(ret, ret.Update(target, value)); Assert.Same(ret, NoOpVisitor.Instance.Visit(ret)); } [Fact] public void UpdateDiferentValueIsDifferent() { LabelTarget target = Expression.Label(typeof(int)); GotoExpression ret = Expression.Goto(target, Expression.Constant(0)); Assert.NotSame(ret, ret.Update(target, Expression.Constant(0))); } [Fact] public void UpdateDifferentTargetIsDifferent() { Expression value = Expression.Constant(0); GotoExpression ret = Expression.Goto(Expression.Label(typeof(int)), value); Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value)); } [Fact] public void OpenGenericType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>))); } [Fact] public static void TypeContainsGenericParameters() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>.Enumerator))); AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>)))); } [Fact] public void PointerType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(int).MakePointerType())); } [Fact] public void ByRefType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Goto(Expression.Label(typeof(void)), typeof(int).MakeByRefType())); } [Theory, ClassData(typeof(CompilationTypes))] public void UndefinedLabel(bool useInterpreter) { Expression<Action> goNowhere = Expression.Lambda<Action>(Expression.Goto(Expression.Label())); Assert.Throws<InvalidOperationException>(() => goNowhere.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void AmbiguousJump(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Action> exp = Expression.Lambda<Action>( Expression.Block( Expression.Goto(target), Expression.Block(Expression.Label(target)), Expression.Block(Expression.Label(target)) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void MultipleDefinitionsInSeparateBlocks(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Func<int> add = Expression.Lambda<Func<int>>( Expression.Add( Expression.Add( Expression.Block( Expression.Goto(target, Expression.Constant(6)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ), Expression.Block( Expression.Goto(target, Expression.Constant(4)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ), Expression.Block( Expression.Goto(target, Expression.Constant(5)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ) ).Compile(useInterpreter); Assert.Equal(15, add()); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpIntoExpression(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Func<bool>> isInt = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Goto(target), Expression.TypeIs(Expression.Label(target), typeof(int)) ) ); Assert.Throws<InvalidOperationException>(() => isInt.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpInWithValue(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Expression<Func<int>> exp = Expression.Lambda<Func<int>>( Expression.Block( Expression.Goto(target, Expression.Constant(2)), Expression.Block( Expression.Label(target, Expression.Constant(3))) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } } }
//============================================================================= // // Copyright (c) Microsoft Corporation All Rights Reserved. // //============================================================================= namespace SAPI51Samples { using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Diagnostics; using SpeechLib; /// <summary> /// SpeechListBox is a speech enabled listbox control. It inherits /// from the standard System.Windows.Forms.ListBox, and thus exposes /// all the standard properties, methods and events. A few new methods /// are added to provide speech specific functionalities. /// </summary> public class SpeechListBox : System.Windows.Forms.ListBox { private const int grammarId = 10; private bool speechEnabled = false; private bool speechInitialized = false; private String PreCommandString = "Select"; private SpeechLib.SpSharedRecoContext objRecoContext; private SpeechLib.ISpeechRecoGrammar grammar; private SpeechLib.ISpeechGrammarRule ruleTopLevel; private SpeechLib.ISpeechGrammarRule ruleListItems; /// <summary> /// AddItem is used to add a newitem to the list item collection. /// It will automatically update the grammar. It's equivalent to /// calling ListBox.Items.Add() followed by BuildGrammar(). /// </summary> /// <param name="newItem"> /// The new item to be added to the list. /// </param> /// <returns> /// The index of the newly added item. /// </returns> public int AddItem(object newItem) { // Since we can't add the same word to the same transition in // the grammar, we don't allow same string to be added // multiple times. So do nothing if Item is already in the list. // Some level of error message may be helpful. The sample chooses // to silently ignore to keep code simple. // The leading and trailing spaces are not needed, trim it before // inserting. SAPI will return error in AddWordTransition if two // phrases differ only in spaces. A program needs to handle this // error if random phrase is added to a rule. // Note: In this sample, we only trim leading and trailing spaces. // Internal spaces will need to be handled as well. string strItem; int index = -1; strItem = newItem.ToString().Trim(); // only add it if trimmed phrase is not empty if( strItem.Length > 0 ) { index = this.FindString(strItem); if( index < 0 ) { // if it doesn't exist yet, add it to the list index = this.Items.Add(strItem); // if speech is enabled, we need to update grammar with the change if( speechEnabled ) RebuildGrammar(); } } return index; } /// <summary> /// RemoveItem will remove the item with the given index and then /// call BuildGrammar() to update grammar. It's equivalent to /// calling ListBox.Items.RemoveAt() followed by BuildGrammar(). /// </summary> /// <param name="index"> /// Index of the item to be removed from the list. /// </param> public void RemoveItem(int index) { this.Items.RemoveAt(index); if( speechEnabled ) RebuildGrammar(); } /// <summary> /// Property SpeechEnabled is read/write-able. When it's set to /// true, speech recognition will be started. When it's set to /// false, speech recognition will be stopped. /// </summary> public bool SpeechEnabled { get { return speechEnabled; } set { if( speechEnabled != value ) { speechEnabled = value ; if(this.DesignMode) return; if (speechEnabled) { EnableSpeech(); } else { DisableSpeech(); } } } } /// <summary> /// RecoContext_Hypothesis is the event handler function for /// SpSharedRecoContext object's Hypothesis event. /// </summary> /// <param name="StreamNumber"></param> /// <param name="StreamPosition"></param> /// <param name="Result"></param> /// <remarks> /// See EnableSpeech() for how to hook up this function with the /// event. /// </remarks> public void RecoContext_Hypothesis(int StreamNumber, object StreamPosition, ISpeechRecoResult Result) { Debug.WriteLine("Hypothesis: " + Result.PhraseInfo.GetText(0, -1, true) + ", " + StreamNumber + ", " + StreamPosition); } /// <summary> /// RecoContext_Hypothesis is the event handler function for /// SpSharedRecoContext object's Recognition event. /// </summary> /// <param name="StreamNumber"></param> /// <param name="StreamPosition"></param> /// <param name="RecognitionType"></param> /// <param name="Result"></param> /// <remarks> /// See EnableSpeech() for how to hook up this function with the /// event. /// </remarks> public void RecoContext_Recognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result) { Debug.WriteLine("Recognition: " + Result.PhraseInfo.GetText(0, -1, true) + ", " + StreamNumber + ", " + StreamPosition); int index; ISpeechPhraseProperty oItem; // oItem will be the property of the second part in the recognized // phase. For example, if the top level rule matchs // "select Seattle". Then the ListItemsRule matches "Seattle" part. // The following code will get the property of the "Seattle" // phrase, which is set when the word "Seattle" is added to the // ruleListItems in RebuildGrammar. oItem = Result.PhraseInfo.Properties.Item(0).Children.Item(0); index = oItem.Id; if ((System.Decimal)Result.PhraseInfo.GrammarId == grammarId) { // Check to see if the item at the same position in the list // still has the same text. // This is to prevent the rare case that the user keeps // talking while the list is being added or removed. By the // time this event is fired and handled, the list box may have // already changed. if( oItem.Name.CompareTo(this.Items[index].ToString())==0 ) { this.SelectedIndex = index; } } } /// <summary> /// This function will create the main SpSharedRecoContext object /// and other required objects like Grammar and rules. /// In this sample, we are building grammar dynamically since /// listbox content can change from time to time. /// If your grammar is static, you can write your grammar file /// and ask SAPI to load it during run time. This can reduce the /// complexity of your code. /// </summary> private void InitializeSpeech() { Debug.WriteLine("Initializing SAPI objects..."); try { // First of all, let's create the main reco context object. // In this sample, we are using shared reco context. Inproc reco // context is also available. Please see the document to decide // which is best for your application. objRecoContext = new SpeechLib.SpSharedRecoContext(); // Then, let's set up the event handler. We only care about // Hypothesis and Recognition events in this sample. objRecoContext.Hypothesis += new _ISpeechRecoContextEvents_HypothesisEventHandler( RecoContext_Hypothesis); objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler( RecoContext_Recognition); // Now let's build the grammar. // The top level rule consists of two parts: "select <items>". // So we first add a word transition for the "select" part, then // a rule transition for the "<items>" part, which is dynamically // built as items are added or removed from the listbox. grammar = objRecoContext.CreateGrammar(grammarId); ruleTopLevel = grammar.Rules.Add("TopLevelRule", SpeechRuleAttributes.SRATopLevel | SpeechRuleAttributes.SRADynamic, 1); ruleListItems = grammar.Rules.Add("ListItemsRule", SpeechRuleAttributes.SRADynamic, 2); SpeechLib.ISpeechGrammarRuleState stateAfterSelect; stateAfterSelect = ruleTopLevel.AddState(); object PropValue = ""; ruleTopLevel.InitialState.AddWordTransition(stateAfterSelect, PreCommandString, " ", SpeechGrammarWordType.SGLexical, "", 0, ref PropValue, 1.0F ); PropValue = ""; stateAfterSelect.AddRuleTransition(null, ruleListItems, "", 1, ref PropValue, 0F); // Now add existing list items to the ruleListItems RebuildGrammar(); // Now we can activate the top level rule. In this sample, only // the top level rule needs to activated. The ListItemsRule is // referenced by the top level rule. grammar.CmdSetRuleState("TopLevelRule", SpeechRuleState.SGDSActive); speechInitialized = true; } catch(Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when initializing SAPI." + " This application may not run correctly.\r\n\r\n" + e.ToString(), "Error"); } } /// <summary> /// EnableSpeech will initialize all speech objects on first time, /// then rebuild grammar and start speech recognition. /// </summary> /// <returns> /// true if speech is enabled and grammar updated. /// false otherwise, which happens if we are in design mode. /// </returns> /// <remarks> /// This is a private function. /// </remarks> private bool EnableSpeech() { Debug.Assert(speechEnabled, "speechEnabled must be true in EnableSpeech"); if (this.DesignMode) return false; if (speechInitialized == false) { InitializeSpeech(); } else { RebuildGrammar(); } objRecoContext.State = SpeechRecoContextState.SRCS_Enabled; return true; } /// <summary> /// RebuildGrammar() will update grammar object with current list /// items. It is called automatically by AddItem and RemoveItem. /// </summary> /// <returns> /// true if grammar is updated. /// false if grammar is not updated, which can happen if speech is /// not enabled or if it's in design mode. /// </returns> /// <remarks> /// RebuildGrammar should be called every time after the list item /// has changed. AddItem and RemoveItem methods are provided as a /// way to update list item and the grammar object automatically. /// Don't forget to call RebuildGrammar if the list is changed /// through ListBox.Items collection. Otherwise speech engine will /// continue to recognize old list items. /// </remarks> public bool RebuildGrammar() { if( !speechEnabled || this.DesignMode ) { return false; } // In this funtion, we are only rebuilding the ruleListItems, as // this is the only part that's really changing dynamically in // this sample. However, you still have to call // Grammar.Rules.Commit to commit the grammar. int i, count; String word; object propValue = ""; try { ruleListItems.Clear(); count = this.Items.Count; for(i=0; i<count; i++) { word = this.Items[i].ToString(); // Note: if the same word is added more than once to the same // rule state, SAPI will return error. In this sample, we // don't allow identical items in the list box so no need for // the checking, otherwise special checking for identical words // would have to be done here. ruleListItems.InitialState.AddWordTransition(null, word, " ", SpeechGrammarWordType.SGLexical, word, i, ref propValue, 1F); } grammar.Rules.Commit(); } catch(Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } return true; } /// <summary> /// This is a private function that stops speech recognition. /// </summary> /// <returns></returns> private bool DisableSpeech() { if (this.DesignMode) return false; Debug.Assert(speechInitialized, "speech must be initialized in DisableSpeech"); if( speechInitialized ) { // Putting the recognition context to disabled state will // stop speech recognition. Changing the state to enabled // will start recognition again. objRecoContext.State = SpeechRecoContextState.SRCS_Disabled; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; // Do not remove. This is necessary for netstandard, since this file is mirrored into corefx #if !netstandard using Internal.Runtime.CompilerServices; #endif namespace System { internal static partial class SpanHelpers // .T { public static int IndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return 0; // A zero-length sequence is always treated as "found" at the start of the search space. T valueHead = value; ref T valueTail = ref Unsafe.Add(ref value, 1); int valueTailLength = valueLength - 1; int index = 0; for (; ; ) { Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength". int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength; if (remainingSearchSpaceLength <= 0) break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there. // Do a quick search for the first element of "value". int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength); if (relativeIndex == -1) break; index += relativeIndex; // Found the first element of "value". See if the tail matches. if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength)) return index; // The tail matched. Return a successful find. index++; } return -1; } // Adapted from IndexOf(...) public unsafe static bool Contains<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || value.Equals(Unsafe.Add(ref searchSpace, index + 3)) || value.Equals(Unsafe.Add(ref searchSpace, index + 4)) || value.Equals(Unsafe.Add(ref searchSpace, index + 5)) || value.Equals(Unsafe.Add(ref searchSpace, index + 6)) || value.Equals(Unsafe.Add(ref searchSpace, index + 7))) { goto Found; } index += 8; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || value.Equals(Unsafe.Add(ref searchSpace, index + 3))) { goto Found; } index += 4; } while (length > 0) { length -= 1; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; index += 1; } } else { byte* len = (byte*)length; for (index = (IntPtr)0; index.ToPointer() < len; index += 1) { if ((object)Unsafe.Add(ref searchSpace, index) is null) { goto Found; } } } return false; Found: return true; } public static unsafe int IndexOf<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; if (value.Equals(Unsafe.Add(ref searchSpace, index + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, index + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, index + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, index + 4))) goto Found4; if (value.Equals(Unsafe.Add(ref searchSpace, index + 5))) goto Found5; if (value.Equals(Unsafe.Add(ref searchSpace, index + 6))) goto Found6; if (value.Equals(Unsafe.Add(ref searchSpace, index + 7))) goto Found7; index += 8; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; if (value.Equals(Unsafe.Add(ref searchSpace, index + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, index + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, index + 3))) goto Found3; index += 4; } while (length > 0) { if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; index += 1; length--; } } else { byte* len = (byte*)length; for (index = (IntPtr)0; index.ToPointer() < len; index += 1) { if ((object)Unsafe.Add(ref searchSpace, index) is null) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; Found1: return (int)(byte*)(index + 1); Found2: return (int)(byte*)(index + 2); Found3: return (int)(byte*)(index + 3); Found4: return (int)(byte*)(index + 4); Found5: return (int)(byte*)(index + 5); Found6: return (int)(byte*)(index + 6); Found7: return (int)(byte*)(index + 7); } public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; int index = 0; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while ((length - index) >= 8) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, index + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, index + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, index + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, index + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found7; index += 8; } if ((length - index) >= 4) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; index += 4; } while (index < length) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; index++; } } else { for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; Found1: return index + 1; Found2: return index + 2; Found3: return index + 3; Found4: return index + 4; Found5: return index + 5; Found6: return index + 6; Found7: return index + 7; } public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; int index = 0; if (default(T)! != null || ((object)value0 != null && (object)value1 != null && (object)value2 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while ((length - index) >= 8) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, index + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, index + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, index + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, index + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found7; index += 8; } if ((length - index) >= 4) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; index += 4; } while (index < length) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; index++; } } else { for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; Found1: return index + 1; Found2: return index + 2; Found3: return index + 3; Found4: return index + 4; Found5: return index + 5; Found6: return index + 6; Found7: return index + 7; } public static int IndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return -1; // A zero-length set of values is always treated as "not found". int index = -1; for (int i = 0; i < valueLength; i++) { var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)tempIndex < (uint)index) { index = tempIndex; // Reduce space for search, cause we don't care if we find the search value after the index of a previously found value searchSpaceLength = tempIndex; if (index == 0) break; } } return index; } public static int LastIndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return 0; // A zero-length sequence is always treated as "found" at the start of the search space. T valueHead = value; ref T valueTail = ref Unsafe.Add(ref value, 1); int valueTailLength = valueLength - 1; int index = 0; for (; ; ) { Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength". int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength; if (remainingSearchSpaceLength <= 0) break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there. // Do a quick search for the first element of "value". int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength); if (relativeIndex == -1) break; // Found the first element of "value". See if the tail matches. if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength)) return relativeIndex; // The tail matched. Return a successful find. index += remainingSearchSpaceLength - relativeIndex; } return -1; } public static int LastIndexOf<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, length + 7))) goto Found7; if (value.Equals(Unsafe.Add(ref searchSpace, length + 6))) goto Found6; if (value.Equals(Unsafe.Add(ref searchSpace, length + 5))) goto Found5; if (value.Equals(Unsafe.Add(ref searchSpace, length + 4))) goto Found4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } while (length > 0) { length--; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } } else { for (length--; length >= 0; length--) { if ((object)Unsafe.Add(ref searchSpace, length) is null) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; lookUp = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found7; lookUp = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } if (length >= 4) { length -= 4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } while (length > 0) { length--; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } } else { for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; lookUp = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found7; lookUp = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } if (length >= 4) { length -= 4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } while (length > 0) { length--; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } } else { for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return -1; // A zero-length set of values is always treated as "not found". int index = -1; for (int i = 0; i < valueLength; i++) { var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (tempIndex > index) index = tempIndex; } return index; } public static bool SequenceEqual<T>(ref T first, ref T second, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); if (Unsafe.AreSame(ref first, ref second)) goto Equal; IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations T lookUp0; T lookUp1; while (length >= 8) { length -= 8; lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 4); lookUp1 = Unsafe.Add(ref second, index + 4); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 5); lookUp1 = Unsafe.Add(ref second, index + 5); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 6); lookUp1 = Unsafe.Add(ref second, index + 6); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 7); lookUp1 = Unsafe.Add(ref second, index + 7); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 8; } if (length >= 4) { length -= 4; lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 4; } while (length > 0) { lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 1; length--; } Equal: return true; NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return false; } public static int SequenceCompareTo<T>(ref T first, int firstLength, ref T second, int secondLength) where T : IComparable<T> { Debug.Assert(firstLength >= 0); Debug.Assert(secondLength >= 0); var minLength = firstLength; if (minLength > secondLength) minLength = secondLength; for (int i = 0; i < minLength; i++) { T lookUp = Unsafe.Add(ref second, i); int result = (Unsafe.Add(ref first, i)?.CompareTo(lookUp) ?? (((object?)lookUp is null) ? 0 : -1)); if (result != 0) return result; } return firstLength.CompareTo(secondLength); } } }
using System; using System.Globalization; using System.Xml; using JetBrains.Annotations; using Orchard.Comments.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.Aspects; using Orchard.Services; using Orchard.Localization; using Orchard.Comments.Services; using Orchard.UI.Notify; namespace Orchard.Comments.Drivers { [UsedImplicitly] public class CommentPartDriver : ContentPartDriver<CommentPart> { private readonly IContentManager _contentManager; private readonly IWorkContextAccessor _workContextAccessor; private readonly IClock _clock; private readonly ICommentService _commentService; private readonly IOrchardServices _orchardServices; protected override string Prefix { get { return "Comments"; } } public Localizer T { get; set; } public CommentPartDriver( IContentManager contentManager, IWorkContextAccessor workContextAccessor, IClock clock, ICommentService commentService, IOrchardServices orchardServices) { _contentManager = contentManager; _workContextAccessor = workContextAccessor; _clock = clock; _commentService = commentService; _orchardServices = orchardServices; T = NullLocalizer.Instance; } protected override DriverResult Display(CommentPart part, string displayType, dynamic shapeHelper) { return Combined( ContentShape("Parts_Comment", () => shapeHelper.Parts_Comment()), ContentShape("Parts_Comment_SummaryAdmin", () => shapeHelper.Parts_Comment_SummaryAdmin()) ); } // GET protected override DriverResult Editor(CommentPart part, dynamic shapeHelper) { if (UI.Admin.AdminFilter.IsApplied(_workContextAccessor.GetContext().HttpContext.Request.RequestContext)) { return ContentShape("Parts_Comment_AdminEdit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment.AdminEdit", Model: part, Prefix: Prefix)); } else { return ContentShape("Parts_Comment_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Comment", Model: part, Prefix: Prefix)); } } // POST protected override DriverResult Editor(CommentPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); var workContext = _workContextAccessor.GetContext(); // applying moderate/approve actions var httpContext = workContext.HttpContext; var name = httpContext.Request.Form["submit.Save"]; if (!string.IsNullOrEmpty(name) && String.Equals(name, "moderate", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) { _commentService.UnapproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully moderated.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "approve", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) { _commentService.ApproveComment(part.Id); _orchardServices.Notifier.Information(T("Comment approved.")); return Editor(part, shapeHelper); } } if (!string.IsNullOrEmpty(name) && String.Equals(name, "delete", StringComparison.OrdinalIgnoreCase)) { if (_orchardServices.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) { _commentService.DeleteComment(part.Id); _orchardServices.Notifier.Information(T("Comment successfully deleted.")); return Editor(part, shapeHelper); } } // if editing from the admin, don't update the owner or the status if (!string.IsNullOrEmpty(name) && String.Equals(name, "save", StringComparison.OrdinalIgnoreCase)) { _orchardServices.Notifier.Information(T("Comment saved.")); return Editor(part, shapeHelper); } part.CommentDateUtc = _clock.UtcNow; if (!String.IsNullOrEmpty(part.SiteName) && !part.SiteName.StartsWith("http://") && !part.SiteName.StartsWith("https://")) { part.SiteName = "http://" + part.SiteName; } var currentUser = workContext.CurrentUser; part.UserName = (currentUser != null ? currentUser.UserName : null); if (currentUser != null) part.Author = currentUser.UserName; else if (string.IsNullOrWhiteSpace(part.Author)) { updater.AddModelError("Comments.Author", T("Name is mandatory")); } var moderateComments = workContext.CurrentSite.As<CommentSettingsPart>().ModerateComments; part.Status = moderateComments ? CommentStatus.Pending : CommentStatus.Approved; var commentedOn = _contentManager.Get<ICommonPart>(part.CommentedOn); // prevent users from commenting on a closed thread by hijacking the commentedOn property var commentsPart = commentedOn.As<CommentsPart>(); if (!commentsPart.CommentsActive) { _orchardServices.TransactionManager.Cancel(); return Editor(part, shapeHelper); } if (commentedOn != null && commentedOn.Container != null) { part.CommentedOnContainer = commentedOn.Container.ContentItem.Id; } commentsPart.Record.CommentPartRecords.Add(part.Record); return Editor(part, shapeHelper); } protected override void Importing(CommentPart part, ContentManagement.Handlers.ImportContentContext context) { var author = context.Attribute(part.PartDefinition.Name, "Author"); if (author != null) { part.Record.Author = author; } var siteName = context.Attribute(part.PartDefinition.Name, "SiteName"); if (siteName != null) { part.Record.SiteName = siteName; } var userName = context.Attribute(part.PartDefinition.Name, "UserName"); if (userName != null) { part.Record.UserName = userName; } var email = context.Attribute(part.PartDefinition.Name, "Email"); if (email != null) { part.Record.Email = email; } var position = context.Attribute(part.PartDefinition.Name, "Position"); if (position != null) { part.Record.Position = decimal.Parse(position, CultureInfo.InvariantCulture); } var status = context.Attribute(part.PartDefinition.Name, "Status"); if (status != null) { part.Record.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), status); } var commentDate = context.Attribute(part.PartDefinition.Name, "CommentDateUtc"); if (commentDate != null) { part.Record.CommentDateUtc = XmlConvert.ToDateTime(commentDate, XmlDateTimeSerializationMode.Utc); } var text = context.Attribute(part.PartDefinition.Name, "CommentText"); if (text != null) { part.Record.CommentText = text; } var commentedOn = context.Attribute(part.PartDefinition.Name, "CommentedOn"); if (commentedOn != null) { var contentItem = context.GetItemFromSession(commentedOn); if (contentItem != null) { part.Record.CommentedOn = contentItem.Id; } contentItem.As<CommentsPart>().Record.CommentPartRecords.Add(part.Record); } var repliedOn = context.Attribute(part.PartDefinition.Name, "RepliedOn"); if (repliedOn != null) { var contentItem = context.GetItemFromSession(repliedOn); if (contentItem != null) { part.Record.RepliedOn = contentItem.Id; } } var commentedOnContainer = context.Attribute(part.PartDefinition.Name, "CommentedOnContainer"); if (commentedOnContainer != null) { var container = context.GetItemFromSession(commentedOnContainer); if (container != null) { part.Record.CommentedOnContainer = container.Id; } } } protected override void Exporting(CommentPart part, ContentManagement.Handlers.ExportContentContext context) { context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Record.Author); context.Element(part.PartDefinition.Name).SetAttributeValue("SiteName", part.Record.SiteName); context.Element(part.PartDefinition.Name).SetAttributeValue("UserName", part.Record.UserName); context.Element(part.PartDefinition.Name).SetAttributeValue("Email", part.Record.Email); context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Record.Position.ToString(CultureInfo.InvariantCulture)); context.Element(part.PartDefinition.Name).SetAttributeValue("Status", part.Record.Status.ToString()); if (part.Record.CommentDateUtc != null) { context.Element(part.PartDefinition.Name) .SetAttributeValue("CommentDateUtc", XmlConvert.ToString(part.Record.CommentDateUtc.Value, XmlDateTimeSerializationMode.Utc)); } context.Element(part.PartDefinition.Name).SetAttributeValue("CommentText", part.Record.CommentText); var commentedOn = _contentManager.Get(part.Record.CommentedOn); if (commentedOn != null) { var commentedOnIdentity = _contentManager.GetItemMetadata(commentedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOn", commentedOnIdentity.ToString()); } var commentedOnContainer = _contentManager.Get(part.Record.CommentedOnContainer); if (commentedOnContainer != null) { var commentedOnContainerIdentity = _contentManager.GetItemMetadata(commentedOnContainer).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("CommentedOnContainer", commentedOnContainerIdentity.ToString()); } if (part.Record.RepliedOn.HasValue) { var repliedOn = _contentManager.Get(part.Record.RepliedOn.Value); if (repliedOn != null) { var repliedOnIdentity = _contentManager.GetItemMetadata(repliedOn).Identity; context.Element(part.PartDefinition.Name).SetAttributeValue("RepliedOn", repliedOnIdentity.ToString()); } } } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// Array functions available through the object 'array' in scriban. /// </summary> public partial class ArrayFunctions : ScriptObject { /// <summary> /// Adds a value to the input list. /// </summary> /// <param name="list">The input list</param> /// <param name="value">The value to add at the end of the list</param> /// <returns>A new list with the value added</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.add 4 }} /// ``` /// ```html /// [1, 2, 3, 4] /// ``` /// </remarks> public static IEnumerable Add(IEnumerable list, object value) { if (list == null) { return new ScriptRange { value }; } return list is IList ? (IEnumerable)new ScriptArray(list) {value} : new ScriptRange(list) {value}; } /// <summary> /// Concatenates two lists. /// </summary> /// <param name="list1">The 1st input list</param> /// <param name="list2">The 2nd input list</param> /// <returns>The concatenation of the two input lists</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.concat [4, 5] }} /// ``` /// ```html /// [1, 2, 3, 4, 5] /// ``` /// </remarks> public static IEnumerable AddRange(IEnumerable list1, IEnumerable list2) { return Concat(list1, list2); } /// <summary> /// Removes any non-null values from the input list. /// </summary> /// <param name="list">An input list</param> /// <returns>Returns a list with null value removed</returns> /// <remarks> /// ```scriban-html /// {{ [1, null, 3] | array.compact }} /// ``` /// ```html /// [1, 3] /// ``` /// </remarks> public static IEnumerable Compact(IEnumerable list) { return ScriptRange.Compact(list); } /// <summary> /// Concatenates two lists. /// </summary> /// <param name="list1">The 1st input list</param> /// <param name="list2">The 2nd input list</param> /// <returns>The concatenation of the two input lists</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.concat [4, 5] }} /// ``` /// ```html /// [1, 2, 3, 4, 5] /// ``` /// </remarks> public static IEnumerable Concat(IEnumerable list1, IEnumerable list2) { return ScriptRange.Concat(list1, list2); } /// <summary> /// Loops through a group of strings and outputs them in the order that they were passed as parameters. Each time cycle is called, the next string that was passed as a parameter is output. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">An input list</param> /// <param name="group">The group used. Default is `null`</param> /// <returns>Returns a list with null value removed</returns> /// <remarks> /// ```scriban-html /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// {{ array.cycle ['one', 'two', 'three'] }} /// ``` /// ```html /// one /// two /// three /// one /// ``` /// `cycle` accepts a parameter called cycle group in cases where you need multiple cycle blocks in one template. /// If no name is supplied for the cycle group, then it is assumed that multiple calls with the same parameters are one group. /// </remarks> public static object Cycle(TemplateContext context, SourceSpan span, IList list, object group = null) { if (list == null) { return null; } var strGroup = group == null ? Join(context, span, list, ",") : context.ObjectToString(@group); // We create a cycle variable that is dependent on the exact AST context. // So we allow to have multiple cycle running in the same loop var cycleKey = new CycleKey(strGroup); object cycleValue; var currentTags = context.Tags; if (!currentTags.TryGetValue(cycleKey, out cycleValue) || !(cycleValue is int)) { cycleValue = 0; } var cycleIndex = (int) cycleValue; cycleIndex = list.Count == 0 ? 0 : cycleIndex % list.Count; object result = null; if (list.Count > 0) { result = list[cycleIndex]; cycleIndex++; } currentTags[cycleKey] = cycleIndex; return result; } /// <summary> /// Returns the first element of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>The first element of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.first }} /// ``` /// ```html /// 4 /// ``` /// </remarks> public static object First(IEnumerable list) { if (list == null) { return null; } var realList = list as IList; if (realList != null) { return realList.Count > 0 ? realList[0] : null; } foreach (var item in list) { return item; } return null; } /// <summary> /// Inserts a `value` at the specified index in the input `list`. /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index in the list where to insert the element</param> /// <param name="value">The value to insert</param> /// <returns>A new list with the element inserted.</returns> /// <remarks> /// ```scriban-html /// {{ ["a", "b", "c"] | array.insert_at 2 "Yo" }} /// ``` /// ```html /// ["a", "b", "Yo", "c"] /// ``` /// </remarks> public static IEnumerable InsertAt(IEnumerable list, int index, object value) { if (index < 0) { index = 0; } var array = list == null ? new ScriptArray() : new ScriptArray(list); // Make sure that the list has already inserted elements before the index for (int i = array.Count; i < index; i++) { array.Add(null); } array.Insert(index, value); return array; } /// <summary> /// Joins the element of a list separated by a delimiter string and return the concatenated string. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="delimiter">The delimiter string to use to separate elements in the output string</param> /// <returns>A new list with the element inserted.</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3] | array.join "|" }} /// ``` /// ```html /// 1|2|3 /// ``` /// </remarks> public static string Join(TemplateContext context, SourceSpan span, IEnumerable list, string delimiter) { if (list == null) { return string.Empty; } var text = new StringBuilder(); bool afterFirst = false; foreach (var obj in list) { if (afterFirst) { text.Append(delimiter); } text.Append(context.ObjectToString(obj)); afterFirst = true; } return text.ToString(); } /// <summary> /// Returns the last element of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>The last element of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.last }} /// ``` /// ```html /// 6 /// ``` /// </remarks> public static object Last(IEnumerable list) { if (list == null) { return null; } var readList = list as IList; if (readList != null) { return readList.Count > 0 ? readList[readList.Count - 1] : null; } // Slow path, go through the whole list return list.Cast<object>().LastOrDefault(); } /// <summary> /// Returns a limited number of elments from the input list /// </summary> /// <param name="list">The input list</param> /// <param name="count">The number of elements to return from the input list</param> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.limit 2 }} /// ``` /// ```html /// [4, 5] /// ``` /// </remarks> public static IEnumerable Limit(IEnumerable list, int count) { return ScriptRange.Limit(list, count); } /// <summary> /// Accepts an array element's attribute as a parameter and creates an array out of each array element's value. /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="member">The member to extract the value from</param> /// <remarks> /// ```scriban-html /// {{ /// products = [{title: "orange", type: "fruit"}, {title: "computer", type: "electronics"}, {title: "sofa", type: "furniture"}] /// products | array.map "type" | array.uniq | array.sort }} /// ``` /// ```html /// ["electronics", "fruit", "furniture"] /// ``` /// </remarks> public static IEnumerable Map(TemplateContext context, SourceSpan span, object list, string member) { return new ScriptRange(MapImpl(context, span, list, member)); } private static IEnumerable MapImpl(TemplateContext context, SourceSpan span, object list, string member) { if (list == null || member == null) { yield break; } var enumerable = list as IEnumerable; var realList = enumerable?.Cast<object>().ToList() ?? new List<object>(1) { list }; if (realList.Count == 0) { yield break; } foreach (var item in realList) { var itemAccessor = context.GetMemberAccessor(item); if (itemAccessor.HasMember(context, span, item, member)) { itemAccessor.TryGetValue(context, span, item, member, out object value); yield return value; } } } /// <summary> /// Returns the remaining of the list after the specified offset /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index of a list to return elements</param> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.offset 2 }} /// ``` /// ```html /// [6, 7, 8] /// ``` /// </remarks> public static IEnumerable Offset(IEnumerable list, int index) { return ScriptRange.Offset(list, index); } /// <summary> /// Removes an element at the specified `index` from the input `list` /// </summary> /// <param name="list">The input list</param> /// <param name="index">The index of a list to return elements</param> /// <returns>A new list with the element removed. If index is negative, remove at the end of the list.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.remove_at 2 }} /// ``` /// ```html /// [4, 5, 7, 8] /// ``` /// If the `index` is negative, removes at the end of the list (notice that we need to put -1 in parenthesis to avoid confusing the parser with a binary `-` operation): /// ```scriban-html /// {{ [4, 5, 6, 7, 8] | array.remove_at (-1) }} /// ``` /// ```html /// [4, 5, 6, 7] /// ``` /// </remarks> public static IList RemoveAt(IList list, int index) { if (list == null) { return new ScriptArray(); } list = new ScriptArray(list); // If index is negative, start from the end if (index < 0) { index = list.Count + index; } if (index >= 0 && index < list.Count) { list.RemoveAt(index); } return list; } /// <summary> /// Reverses the input `list` /// </summary> /// <param name="list">The input list</param> /// <returns>A new list in reversed order.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6, 7] | array.reverse }} /// ``` /// ```html /// [7, 6, 5, 4] /// ``` /// </remarks> public static IEnumerable Reverse(IEnumerable list) { return ScriptRange.Reverse(list); } /// <summary> /// Returns the number of elements in the input `list` /// </summary> /// <param name="list">The input list</param> /// <returns>A number of elements in the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [4, 5, 6] | array.size }} /// ``` /// ```html /// 3 /// ``` /// </remarks> public static int Size(IEnumerable list) { if (list == null) { return 0; } var collection = list as ICollection; if (collection != null) { return collection.Count; } // Slow path, go through the whole list return list.Cast<object>().Count(); } /// <summary> /// Sorts the elements of the input `list` according to the value of each element or the value of the specified `member` of each element /// </summary> /// <param name="context">The template context</param> /// <param name="span">The source span</param> /// <param name="list">The input list</param> /// <param name="member">The member name to sort according to its value. Null by default, meaning that the element's value are used instead.</param> /// <returns>A list sorted according to the value of each element or the value of the specified `member` of each element.</returns> /// <remarks> /// Sorts by element's value: /// ```scriban-html /// {{ [10, 2, 6] | array.sort }} /// ``` /// ```html /// [2, 6, 10] /// ``` /// Sorts by elements member's value: /// ```scriban-html /// {{ /// products = [{title: "orange", type: "fruit"}, {title: "computer", type: "electronics"}, {title: "sofa", type: "furniture"}] /// products | array.sort "title" | array.map "title" /// }} /// ``` /// ```html /// ["computer", "orange", "sofa"] /// ``` /// </remarks> public static IEnumerable Sort(TemplateContext context, SourceSpan span, object list, string member = null) { if (list == null) { return new ScriptRange(); } var enumerable = list as IEnumerable; if (enumerable == null) { return new ScriptArray(1) {list}; } var realList = enumerable.Cast<object>().ToList(); if (realList.Count == 0) return new ScriptArray(); if (string.IsNullOrEmpty(member)) { realList.Sort(); } else { realList.Sort((a, b) => { var leftAccessor = context.GetMemberAccessor(a); var rightAccessor = context.GetMemberAccessor(b); object leftValue = null; object rightValue = null; if (!leftAccessor.TryGetValue(context, span, a, member, out leftValue)) { context.TryGetMember?.Invoke(context, span, a, member, out leftValue); } if (!rightAccessor.TryGetValue(context, span, b, member, out rightValue)) { context.TryGetMember?.Invoke(context, span, b, member, out rightValue); } return Comparer<object>.Default.Compare(leftValue, rightValue); }); } return new ScriptArray(realList); } /// <summary> /// Returns the unique elements of the input `list`. /// </summary> /// <param name="list">The input list</param> /// <returns>A list of unique elements of the input `list`.</returns> /// <remarks> /// ```scriban-html /// {{ [1, 1, 4, 5, 8, 8] | array.uniq }} /// ``` /// ```html /// [1, 4, 5, 8] /// ``` /// </remarks> public static IEnumerable Uniq(IEnumerable list) { return ScriptRange.Uniq(list); } /// <summary> /// Returns if an `list` contains an specifique element /// </summary> /// <param name="list">the input list</param> /// <param name="item">the input item</param> /// <returns>**true** if element is in `list`; otherwise **false**</returns> /// <remarks> /// ```scriban-html /// {{ [1, 2, 3, 4] | array.contains 4 }} /// ``` /// ```html /// true /// ``` /// </remarks> public static bool Contains(IEnumerable list, object item) { foreach (var element in list) if (element == item || (element != null && element.Equals(item))) return true; return false; } private class CycleKey : IEquatable<CycleKey> { public readonly string Group; public CycleKey(string @group) { Group = @group; } public bool Equals(CycleKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(Group, other.Group); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((CycleKey) obj); } public override int GetHashCode() { return (Group != null ? Group.GetHashCode() : 0); } public override string ToString() { return $"cycle {Group}"; } } } }
// 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.Collections; using System.IO; using System.Globalization; using System.Diagnostics; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using Microsoft.CSharp; namespace System.Xml.Serialization { /// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal static class CodeIdentifier { internal static CodeDomProvider csharp = new CSharpCodeProvider(); internal const int MaxIdentifierLength = 511; /// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier.MakePascal"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakePascal(string identifier) { identifier = MakeValid(identifier); if (identifier.Length <= 2) return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier); else if (char.IsLower(identifier[0])) return char.ToUpperInvariant(identifier[0]) + identifier.Substring(1); else return identifier; } /// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier.MakeValid"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakeValid(string identifier) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++) { char c = identifier[i]; if (IsValid(c)) { if (builder.Length == 0 && !IsValidStart(c)) { builder.Append("Item"); } builder.Append(c); } } if (builder.Length == 0) return "Item"; return builder.ToString(); } internal static string MakeValidInternal(string identifier) { if (identifier.Length > 30) { return "Item"; } return MakeValid(identifier); } private static bool IsValidStart(char c) { // the given char is already a valid name character #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (!IsValid(c)) throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString(CultureInfo.InvariantCulture)), "c"); #endif // First char cannot be a number if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber) return false; return true; } private static bool IsValid(char c) { UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c); // each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc // switch (uc) { case UnicodeCategory.UppercaseLetter: // Lu case UnicodeCategory.LowercaseLetter: // Ll case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.OtherLetter: // Lo case UnicodeCategory.DecimalDigitNumber: // Nd case UnicodeCategory.NonSpacingMark: // Mn case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc break; case UnicodeCategory.LetterNumber: case UnicodeCategory.OtherNumber: case UnicodeCategory.EnclosingMark: case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Control: case UnicodeCategory.Format: case UnicodeCategory.Surrogate: case UnicodeCategory.PrivateUse: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: case UnicodeCategory.MathSymbol: case UnicodeCategory.CurrencySymbol: case UnicodeCategory.ModifierSymbol: case UnicodeCategory.OtherSymbol: case UnicodeCategory.OtherNotAssigned: return false; default: #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Unhandled category " + uc), "c"); #else return false; #endif } return true; } internal static void CheckValidIdentifier(string ident) { if (!Globals.IsValidLanguageIndependentIdentifier(ident)) throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident)); } internal static string GetCSharpName(string name) { return EscapeKeywords(name.Replace('+', '.'), csharp); } private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb) { if (t.DeclaringType != null && t.DeclaringType != t) { index = GetCSharpName(t.DeclaringType, parameters, index, sb); sb.Append("."); } string name = t.Name; int nameEnd = name.IndexOf('`'); if (nameEnd < 0) { nameEnd = name.IndexOf('!'); } if (nameEnd > 0) { EscapeKeywords(name.Substring(0, nameEnd), csharp, sb); sb.Append("<"); int arguments = Int32.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index; for (; index < arguments; index++) { sb.Append(GetCSharpName(parameters[index])); if (index < arguments - 1) { sb.Append(","); } } sb.Append(">"); } else { EscapeKeywords(name, csharp, sb); } return index; } internal static string GetCSharpName(Type t) { int rank = 0; while (t.IsArray) { t = t.GetElementType(); rank++; } StringBuilder sb = new StringBuilder(); sb.Append("global::"); string ns = t.Namespace; if (ns != null && ns.Length > 0) { string[] parts = ns.Split(new char[] { '.' }); for (int i = 0; i < parts.Length; i++) { EscapeKeywords(parts[i], csharp, sb); sb.Append("."); } } Type[] arguments = t.GetTypeInfo().IsGenericType || t.GetTypeInfo().ContainsGenericParameters ? t.GetGenericArguments() : Array.Empty<Type>(); GetCSharpName(t, arguments, 0, sb); for (int i = 0; i < rank; i++) { sb.Append("[]"); } return sb.ToString(); } /* internal static string GetTypeName(string name, CodeDomProvider codeProvider) { return codeProvider.GetTypeOutput(new CodeTypeReference(name)); } */ private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb) { if (identifier == null || identifier.Length == 0) return; int arrayCount = 0; while (identifier.EndsWith("[]", StringComparison.Ordinal)) { arrayCount++; identifier = identifier.Substring(0, identifier.Length - 2); } if (identifier.Length > 0) { CheckValidIdentifier(identifier); identifier = codeProvider.CreateEscapedIdentifier(identifier); sb.Append(identifier); } for (int i = 0; i < arrayCount; i++) { sb.Append("[]"); } } private static string EscapeKeywords(string identifier, CodeDomProvider codeProvider) { if (identifier == null || identifier.Length == 0) return identifier; string originalIdentifier = identifier; string[] names = identifier.Split(new char[] { '.', ',', '<', '>' }); StringBuilder sb = new StringBuilder(); int separator = -1; for (int i = 0; i < names.Length; i++) { if (separator >= 0) { sb.Append(originalIdentifier.Substring(separator, 1)); } separator++; separator += names[i].Length; string escapedName = names[i].Trim(); EscapeKeywords(escapedName, codeProvider, sb); } if (sb.Length != originalIdentifier.Length) return sb.ToString(); return originalIdentifier; } } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System.Collections.Generic; using UnityEngine; namespace TouchScript.Debugging { /// <summary> /// Visual debugger to show touches as GUI elements. /// </summary> [AddComponentMenu("TouchScript/Touch Debugger")] public class TouchDebugger : MonoBehaviour { #region Public properties /// <summary> /// Show touch id near touch circles. /// </summary> public bool ShowTouchId { get { return showTouchId; } set { showTouchId = value; } } /// <summary> /// Show tag list near touch circles. /// </summary> public bool ShowTags { get { return showTags; } set { showTags = value; } } /// <summary>Gets or sets the texture to use.</summary> public Texture2D TouchTexture { get { return texture; } set { texture = value; update(); } } /// <summary>Gets or sets whether <see cref="TouchDebugger"/> is using DPI to scale touch cursors.</summary> /// <value><c>true</c> if dpi value is used; otherwise, <c>false</c>.</value> public bool UseDPI { get { return useDPI; } set { useDPI = value; update(); } } /// <summary>Gets or sets the size of touch cursors in cm.</summary> /// <value>The size of touch cursors in cm.</value> public float TouchSize { get { return touchSize; } set { touchSize = value; update(); } } /// <summary>Gets or sets font color for touch ids.</summary> public Color FontColor { get { return fontColor; } set { fontColor = value; } } #endregion #region Private variables [SerializeField] private bool showTouchId = true; [SerializeField] private bool showTags = false; [SerializeField] private Texture2D texture; [SerializeField] private bool useDPI = true; [SerializeField] private float touchSize = 1f; [SerializeField] private Color fontColor = new Color(0, 1, 1, 1); private Dictionary<int, ITouch> dummies = new Dictionary<int, ITouch>(10); private Dictionary<int, string> tags = new Dictionary<int, string>(10); private float textureDPI, scale, dpi, shadowOffset; private int textureWidth, textureHeight, halfTextureWidth, halfTextureHeight, xOffset, yOffset, labelWidth, labelHeight, fontSize; private GUIStyle style; #endregion #region Unity methods private void OnEnable() { if (TouchTexture == null) { Debug.LogError("Touch Debugger doesn't have touch texture assigned!"); return; } update(); if (TouchManager.Instance != null) { TouchManager.Instance.TouchesBegan += touchesBeganHandler; TouchManager.Instance.TouchesEnded += touchesEndedHandler; TouchManager.Instance.TouchesMoved += touchesMovedHandler; TouchManager.Instance.TouchesCancelled += touchesCancelledHandler; } } private void OnDisable() { if (TouchManager.Instance != null) { TouchManager.Instance.TouchesBegan -= touchesBeganHandler; TouchManager.Instance.TouchesEnded -= touchesEndedHandler; TouchManager.Instance.TouchesMoved -= touchesMovedHandler; TouchManager.Instance.TouchesCancelled -= touchesCancelledHandler; } } private void OnGUI() { if (TouchTexture == null) return; if (style == null) style = new GUIStyle(GUI.skin.label); checkDPI(); style.fontSize = fontSize; foreach (KeyValuePair<int, ITouch> dummy in dummies) { var x = dummy.Value.Position.x; var y = Screen.height - dummy.Value.Position.y; GUI.DrawTexture(new Rect(x - halfTextureWidth, y - halfTextureHeight, textureWidth, textureHeight), TouchTexture, ScaleMode.ScaleToFit); string text; int id = dummy.Value.Id; int line = 0; if (ShowTouchId) { text = "id: " + id; GUI.color = Color.black; GUI.Label(new Rect(x + xOffset + shadowOffset, y + yOffset + shadowOffset, labelWidth, labelHeight), text, style); GUI.color = fontColor; GUI.Label(new Rect(x + xOffset, y + yOffset, labelWidth, labelHeight), text, style); line++; } if (ShowTags && tags.ContainsKey(id)) { text = "tags: " + tags[id]; GUI.color = Color.black; GUI.Label(new Rect(x + xOffset + shadowOffset, y + yOffset + fontSize * line + shadowOffset, labelWidth, labelHeight), text, style); GUI.color = fontColor; GUI.Label(new Rect(x + xOffset, y + yOffset + fontSize * line, labelWidth, labelHeight), text, style); } } } #endregion #region Private functions private void checkDPI() { if (useDPI && !Mathf.Approximately(dpi, TouchManager.Instance.DPI)) update(); } private void update() { if (useDPI) { dpi = TouchManager.Instance.DPI; textureDPI = texture.width * TouchManager.INCH_TO_CM / touchSize; scale = dpi / textureDPI; textureWidth = (int)(texture.width * scale); textureHeight = (int)(texture.height * scale); computeConsts(); } else { textureWidth = 32; textureHeight = 32; scale = 1 / 4f; computeConsts(); } } private void computeConsts() { halfTextureWidth = textureWidth / 2; halfTextureHeight = textureHeight / 2; xOffset = (int)(textureWidth * .35f); yOffset = (int)(textureHeight * .35f); fontSize = (int)(32 * scale); shadowOffset = 2 * scale; labelWidth = 20 * fontSize; labelHeight = 2 * fontSize; } private void updateDummy(ITouch dummy) { dummies[dummy.Id] = dummy; } #endregion #region Event handlers private void touchesBeganHandler(object sender, TouchEventArgs e) { var count = e.Touches.Count; for (var i = 0; i < count; i++) { var touch = e.Touches[i]; dummies.Add(touch.Id, touch); if (touch.Tags.Count > 0) { tags.Add(touch.Id, touch.Tags.ToString()); } } } private void touchesMovedHandler(object sender, TouchEventArgs e) { var count = e.Touches.Count; for (var i = 0; i < count; i++) { var touch = e.Touches[i]; ITouch dummy; if (!dummies.TryGetValue(touch.Id, out dummy)) return; updateDummy(touch); } } private void touchesEndedHandler(object sender, TouchEventArgs e) { var count = e.Touches.Count; for (var i = 0; i < count; i++) { var touch = e.Touches[i]; ITouch dummy; if (!dummies.TryGetValue(touch.Id, out dummy)) return; dummies.Remove(touch.Id); } } private void touchesCancelledHandler(object sender, TouchEventArgs e) { touchesEndedHandler(sender, e); } #endregion } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using IdentityModel.Client; using IdentityServer.IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Xunit; namespace IdentityServer.IntegrationTests.Clients { public class RefreshTokenClient { private const string TokenEndpoint = "https://server/connect/token"; private const string RevocationEndpoint = "https://server/connect/revocation"; private readonly HttpClient _client; public RefreshTokenClient() { var builder = new WebHostBuilder() .UseStartup<Startup>(); var server = new TestServer(builder); _client = server.CreateClient(); } [Fact] public async Task Requesting_a_refresh_token_without_identity_scopes_should_return_expected_results() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = response.RefreshToken }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); } [Fact] public async Task Requesting_a_refresh_token_with_identity_scopes_should_return_expected_results() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = response.RefreshToken }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().NotBeNull(); response.RefreshToken.Should().NotBeNull(); } [Fact] public async Task Refreshing_a_refresh_token_with_reuse_should_return_same_refresh_token() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient.reuse", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var rt1 = response.RefreshToken; response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient.reuse", ClientSecret = "secret", RefreshToken = response.RefreshToken }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().NotBeNull(); response.RefreshToken.Should().NotBeNull(); var rt2 = response.RefreshToken; rt1.Should().BeEquivalentTo(rt2); } [Fact] public async Task Refreshing_a_refresh_token_with_one_time_only_should_return_different_refresh_token() { var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var rt1 = response.RefreshToken; response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = response.RefreshToken }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().NotBeNull(); response.RefreshToken.Should().NotBeNull(); var rt2 = response.RefreshToken; rt1.Should().NotBeEquivalentTo(rt2); } [Fact] public async Task Replaying_a_rotated_token_should_fail() { // request initial token var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var rt1 = response.RefreshToken; // refresh token response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = response.RefreshToken }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().NotBeNull(); response.RefreshToken.Should().NotBeNull(); // refresh token (again) response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = rt1 }); response.IsError.Should().BeTrue(); response.Error.Should().Be("invalid_grant"); } [Fact] public async Task Using_a_valid_refresh_token_should_succeed() { // request initial token var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var rt1 = response.RefreshToken; // refresh token response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = rt1 }); response.IsError.Should().BeFalse(); } [Fact] public async Task Using_a_revoked_refresh_token_should_fail() { // request initial token var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", Scope = "openid api1 offline_access", UserName = "bob", Password = "bob" }); response.IsError.Should().BeFalse(); response.ExpiresIn.Should().Be(3600); response.TokenType.Should().Be("Bearer"); response.IdentityToken.Should().BeNull(); response.RefreshToken.Should().NotBeNull(); var rt1 = response.RefreshToken; // revoke refresh token var revocationResponse = await _client.RevokeTokenAsync(new TokenRevocationRequest { Address = RevocationEndpoint, ClientId = "roclient", ClientSecret = "secret", Token = rt1, TokenTypeHint = "refresh_token" }); revocationResponse.IsError.Should().Be(false); // refresh token response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { Address = TokenEndpoint, ClientId = "roclient", ClientSecret = "secret", RefreshToken = rt1 }); response.IsError.Should().BeTrue(); response.Error.Should().Be("invalid_grant"); } } }
// // TestInt32Extensions.cs // // Author: // Craig Fowler <[email protected]> // // Copyright (c) 2015 CSF Software Limited // // 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 NUnit.Framework; using CSF; using System.Collections.Generic; using System.Linq; namespace Test.CSF { [TestFixture] public class TestInt32Extensions { #region test code for generating references [Test] public void TestGenerateAlphabeticReferenceZeroBased() { Dictionary<int, string> expectedValues = GetExpectedReferencesZeroBased(); foreach(int integer in expectedValues.Keys) { Assert.AreEqual(expectedValues[integer], Int32Extensions.GenerateAlphabeticReference(integer, true), String.Format("Test generation of reference for {0}", integer)); } } [Test] public void TestGenerateAlphabeticReferenceNonZeroBased() { Dictionary<int, string> expectedValues = GetExpectedReferencesNonZeroBased(); foreach(int integer in expectedValues.Keys) { Assert.AreEqual(expectedValues[integer], Int32Extensions.GenerateAlphabeticReference(integer, false), String.Format("Test generation of reference for {0}", integer)); } } [Test] public void TestGenerateAlphabeticReferenceException() { Assert.That(() => Int32Extensions.GenerateAlphabeticReference(-1, true), Throws.InstanceOf<ArgumentException>()); } #endregion #region test code for parsing references [Test] public void TestParseAlphabeticReferenceZeroBased() { Dictionary<int, string> expectedValues = GetExpectedReferencesZeroBased(); foreach(int integer in expectedValues.Keys) { Assert.AreEqual(integer, Int32Extensions.ParseAlphabeticReference(expectedValues[integer], true), String.Format("Test parsing of reference for {0}", integer)); } } [Test] public void TestParseAlphabeticReferenceNonZeroBased() { Dictionary<int, string> expectedValues = GetExpectedReferencesNonZeroBased(); foreach(int integer in expectedValues.Keys) { Assert.AreEqual(integer, Int32Extensions.ParseAlphabeticReference(expectedValues[integer], false), String.Format("Test parsing of reference for {0}", integer)); } } [Test] public void TestParseAlphabeticReferenceNull() { Assert.That(() => Int32Extensions.ParseAlphabeticReference(null, true), Throws.InstanceOf<ArgumentNullException>()); } [Test] public void TestParseAlphabeticReferenceEmptyString() { Assert.That(() => Int32Extensions.ParseAlphabeticReference(String.Empty, true), Throws.InstanceOf<FormatException>()); } [Test] public void TestParseAlphabeticReferenceInvalid() { ; Assert.That(() => Int32Extensions.ParseAlphabeticReference("a6c", true), Throws.InstanceOf<FormatException>()); } [Test] public void TestToAlphabeticReference() { Dictionary<int, string> zeroBased = this.GetExpectedReferencesZeroBased(), nonZeroBased = this.GetExpectedReferencesNonZeroBased(); foreach(int number in zeroBased.Keys) { Assert.AreEqual(zeroBased[number], number.ToAlphabeticReference(), "Correct reference"); } foreach(int number in nonZeroBased.Keys) { Assert.AreEqual(nonZeroBased[number], number.ToAlphabeticReference(false), "Correct reference"); } } #endregion #region other tests [Test] public void TestToBitNumbers() { IList<int> result; result = (45).ToBitNumbers(); Assert.IsTrue(result.Contains(1), "Contains value 1"); Assert.IsTrue(result.Contains(4), "Contains value 4"); Assert.IsTrue(result.Contains(8), "Contains value 8"); Assert.IsTrue(result.Contains(32), "Contains value 32"); Assert.AreEqual(4, result.Count, "Correct count"); result = (-46).ToBitNumbers(); Assert.IsTrue(result.Contains(-2), "Contains value -2"); Assert.IsTrue(result.Contains(-4), "Contains value -4"); Assert.IsTrue(result.Contains(-8), "Contains value -8"); Assert.IsTrue(result.Contains(-32), "Contains value -32"); Assert.AreEqual(4, result.Count, "Correct count"); } #endregion #region test values private Dictionary<int, string> GetExpectedReferencesZeroBased() { Dictionary<int, string> output = new Dictionary<int, string>(); output.Add( 0, "a"); output.Add( 2, "c"); output.Add( 20, "u"); output.Add( 25, "z"); output.Add( 26, "aa"); output.Add( 27, "ab"); output.Add( 51, "az"); output.Add( 52, "ba"); output.Add( 53, "bb"); output.Add( 500, "sg"); output.Add( 600, "wc"); return output; } private Dictionary<int, string> GetExpectedReferencesNonZeroBased() { Dictionary<int, string> output = new Dictionary<int, string>(); output.Add( 0, ""); output.Add( 2, "b"); output.Add( 20, "t"); output.Add( 26, "z"); output.Add( 27, "aa"); output.Add( 28, "ab"); output.Add( 52, "az"); output.Add( 53, "ba"); output.Add( 54, "bb"); output.Add( 500, "sf"); output.Add( 600, "wb"); output.Add( -2, "-b"); output.Add( -20, "-t"); output.Add( -26, "-z"); output.Add( -27, "-aa"); output.Add( -28, "-ab"); output.Add( -52, "-az"); output.Add( -53, "-ba"); output.Add( -54, "-bb"); output.Add(-500, "-sf"); output.Add(-600, "-wb"); return output; } #endregion } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class GoTweenConfig { private List<AbstractTweenProperty> _tweenProperties = new List<AbstractTweenProperty>( 2 ); public List<AbstractTweenProperty> tweenProperties { get { return _tweenProperties; } } public int id; // id for finding the Tween at a later time. multiple Tweens can have the same id public float delay; // how long should we delay before starting the Tween public int iterations = 1; // number of times to iterate. -1 will loop indefinitely public float timeScale = 1.0f; public GoLoopType loopType = Go.defaultLoopType; public GoEaseType easeType = Go.defaultEaseType; public AnimationCurve easeCurve; public bool isPaused; public GoUpdateType propertyUpdateType = Go.defaultUpdateType; public bool isFrom; public Action<AbstractGoTween> onInitHandler; public Action<AbstractGoTween> onBeginHandler; public Action<AbstractGoTween> onIterationStartHandler; public Action<AbstractGoTween> onUpdateHandler; public Action<AbstractGoTween> onIterationEndHandler; public Action<AbstractGoTween> onCompleteHandler; #region TweenProperty adders /// <summary> /// position tween /// </summary> public GoTweenConfig position( Vector3 endValue, bool isRelative = false ) { var prop = new PositionTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localPosition tween /// </summary> public GoTweenConfig localPosition( Vector3 endValue, bool isRelative = false ) { var prop = new PositionTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// position path tween /// </summary> public GoTweenConfig positionPath( GoSpline path, bool isRelative = false, GoLookAtType lookAtType = GoLookAtType.None, Transform lookTarget = null ) { var prop = new PositionPathTweenProperty( path, isRelative, false, lookAtType, lookTarget ); _tweenProperties.Add( prop ); return this; } /// <summary> /// uniform scale tween (x, y and z scale to the same value) /// </summary> public GoTweenConfig scale( float endValue, bool isRelative = false ) { return this.scale( new Vector3( endValue, endValue, endValue ), isRelative ); } /// <summary> /// scale tween /// </summary> public GoTweenConfig scale( Vector3 endValue, bool isRelative = false ) { var prop = new ScaleTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// scale through a series of Vector3s /// </summary> public GoTweenConfig scalePath( GoSpline path, bool isRelative = false ) { var prop = new ScalePathTweenProperty( path, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// eulerAngle tween /// </summary> public GoTweenConfig eulerAngles( Vector3 endValue, bool isRelative = false ) { var prop = new EulerAnglesTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// local eulerAngle tween /// </summary> public GoTweenConfig localEulerAngles( Vector3 endValue, bool isRelative = false ) { var prop = new EulerAnglesTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// rotation tween /// </summary> public GoTweenConfig rotation( Vector3 endValue, bool isRelative = false ) { var prop = new RotationTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localRotation tween /// </summary> public GoTweenConfig localRotation( Vector3 endValue, bool isRelative = false ) { var prop = new RotationTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// rotation tween as Quaternion /// </summary> public GoTweenConfig rotation( Quaternion endValue, bool isRelative = false ) { var prop = new RotationQuaternionTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// localRotation tween as Quaternion /// </summary> public GoTweenConfig localRotation( Quaternion endValue, bool isRelative = false ) { var prop = new RotationQuaternionTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// anchoredPosition tween /// </summary> public GoTweenConfig anchoredPosition( Vector2 endValue, bool isRelative = false ) { var prop = new AnchoredPositionTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// anchoredPosition3D tween /// </summary> public GoTweenConfig anchoredPosition3D( Vector3 endValue, bool isRelative = false ) { var prop = new AnchoredPosition3DTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// anchorMax tween /// </summary> public GoTweenConfig anchorMax( Vector2 endValue, bool isRelative = false ) { var prop = new AnchorMaxTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// anchorMin tween /// </summary> public GoTweenConfig anchorMin( Vector2 endValue, bool isRelative = false ) { var prop = new AnchorMinTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// offsetMax tween /// </summary> public GoTweenConfig offsetMax( Vector2 endValue, bool isRelative = false ) { var prop = new OffsetTweenProperty( endValue, isRelative, true ); _tweenProperties.Add( prop ); return this; } /// <summary> /// offsetMin tween /// </summary> public GoTweenConfig offsetMin( Vector2 endValue, bool isRelative = false ) { var prop = new OffsetTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// pivot tween /// </summary> public GoTweenConfig pivot( Vector2 endValue, bool isRelative = false ) { var prop = new PivotTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// sizeDelta tween /// </summary> public GoTweenConfig sizeDelta( Vector2 endValue, bool isRelative = false ) { var prop = new SizeDeltaTweenProperty( endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// material color tween /// </summary> public GoTweenConfig materialColor( Color endValue, string colorName = "_Color", bool isRelative = false ) { var prop = new MaterialColorTweenProperty( endValue, colorName, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// material vector tween /// </summary> public GoTweenConfig materialVector( Vector4 endValue, string propertyName, bool isRelative = false) { var prop = new MaterialVectorTweenProperty(endValue, propertyName, isRelative); _tweenProperties.Add(prop); return this; } /// <summary> /// material float tween /// </summary> public GoTweenConfig materialFloat( float endValue, string propertyName, bool isRelative = false ) { var prop = new MaterialFloatTweenProperty(endValue, propertyName, isRelative); _tweenProperties.Add(prop); return this; } /// <summary> /// shake tween /// </summary> public GoTweenConfig shake( Vector3 shakeMagnitude, GoShakeType shakeType = GoShakeType.Position, int frameMod = 1, bool useLocalProperties = false ) { var prop = new ShakeTweenProperty( shakeMagnitude, shakeType, frameMod, useLocalProperties ); _tweenProperties.Add( prop ); return this; } #region generic properties /// <summary> /// generic vector2 tween /// </summary> public GoTweenConfig vector2Prop( string propertyName, Vector2 endValue, bool isRelative = false ) { var prop = new Vector2TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3 tween /// </summary> public GoTweenConfig vector3Prop( string propertyName, Vector3 endValue, bool isRelative = false ) { var prop = new Vector3TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector4 tween /// </summary> public GoTweenConfig vector4Prop( string propertyName, Vector4 endValue, bool isRelative = false ) { var prop = new Vector4TweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3 path tween /// </summary> public GoTweenConfig vector3PathProp( string propertyName, GoSpline path, bool isRelative = false ) { var prop = new Vector3PathTweenProperty( propertyName, path, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.x tween /// </summary> public GoTweenConfig vector3XProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3XTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.y tween /// </summary> public GoTweenConfig vector3YProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3YTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic vector3.z tween /// </summary> public GoTweenConfig vector3ZProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new Vector3ZTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic color tween /// </summary> public GoTweenConfig colorProp( string propertyName, Color endValue, bool isRelative = false ) { var prop = new ColorTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic integer tween /// </summary> public GoTweenConfig intProp( string propertyName, int endValue, bool isRelative = false ) { var prop = new IntTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } /// <summary> /// generic float tween /// </summary> public GoTweenConfig floatProp( string propertyName, float endValue, bool isRelative = false ) { var prop = new FloatTweenProperty( propertyName, endValue, isRelative ); _tweenProperties.Add( prop ); return this; } #endregion #endregion /// <summary> /// adds a TweenProperty to the list /// </summary> public GoTweenConfig addTweenProperty( AbstractTweenProperty tweenProp ) { _tweenProperties.Add( tweenProp ); return this; } /// <summary> /// clears out all the TweenProperties /// </summary> public GoTweenConfig clearProperties() { _tweenProperties.Clear(); return this; } /// <summary> /// clears out all the TweenProperties /// </summary> public GoTweenConfig clearEvents() { onInitHandler = null; onBeginHandler = null; onIterationStartHandler = null; onUpdateHandler = null; onIterationEndHandler = null; onCompleteHandler = null; return this; } /// <summary> /// sets the delay for the tween /// </summary> public GoTweenConfig setDelay( float seconds ) { delay = seconds; return this; } /// <summary> /// sets the number of iterations. setting to -1 will loop infinitely /// </summary> public GoTweenConfig setIterations( int iterations ) { this.iterations = iterations; return this; } /// <summary> /// sets the number of iterations and the loop type. setting to -1 will loop infinitely /// </summary> public GoTweenConfig setIterations( int iterations, GoLoopType loopType ) { this.iterations = iterations; this.loopType = loopType; return this; } /// <summary> /// sets the timeScale to be used by the Tween /// </summary> public GoTweenConfig setTimeScale( float timeScale ) { this.timeScale = timeScale; return this; } /// <summary> /// sets the ease type for the Tween /// </summary> public GoTweenConfig setEaseType( GoEaseType easeType ) { this.easeType = easeType; return this; } /// <summary> /// sets the ease curve for the Tween /// </summary> public GoTweenConfig setEaseCurve( AnimationCurve easeCurve ) { this.easeCurve = easeCurve; this.easeType = GoEaseType.AnimationCurve; return this; } /// <summary> /// sets whether the Tween should start paused /// </summary> public GoTweenConfig startPaused() { isPaused = true; return this; } /// <summary> /// sets the update type for the Tween /// </summary> public GoTweenConfig setUpdateType( GoUpdateType setUpdateType ) { propertyUpdateType = setUpdateType; return this; } /// <summary> /// sets if this Tween should be a "from" Tween. From Tweens use the current property as the endValue and /// the endValue as the start value /// </summary> public GoTweenConfig setIsFrom() { isFrom = true; return this; } /// <summary> /// sets if this Tween should be a "to" Tween. /// </summary> public GoTweenConfig setIsTo() { isFrom = false; return this; } /// <summary> /// sets the onInit handler for the Tween /// </summary> public GoTweenConfig onInit( Action<AbstractGoTween> onInit ) { onInitHandler = onInit; return this; } /// <summary> /// sets the onBegin handler for the Tween /// </summary> public GoTweenConfig onBegin( Action<AbstractGoTween> onBegin ) { onBeginHandler = onBegin; return this; } /// <summary> /// sets the onIterationStart handler for the Tween /// </summary> public GoTweenConfig onIterationStart( Action<AbstractGoTween> onIterationStart ) { onIterationStartHandler = onIterationStart; return this; } /// <summary> /// sets the onUpdate handler for the Tween /// </summary> public GoTweenConfig onUpdate( Action<AbstractGoTween> onUpdate ) { onUpdateHandler = onUpdate; return this; } /// <summary> /// sets the onIterationEnd handler for the Tween /// </summary> public GoTweenConfig onIterationEnd( Action<AbstractGoTween> onIterationEnd ) { onIterationEndHandler = onIterationEnd; return this; } /// <summary> /// sets the onComplete handler for the Tween /// </summary> public GoTweenConfig onComplete( Action<AbstractGoTween> onComplete ) { onCompleteHandler = onComplete; return this; } /// <summary> /// sets the id for the Tween. Multiple Tweens can have the same id and you can retrieve them with the Go class /// </summary> public GoTweenConfig setId( int id ) { this.id = id; return this; } /// <summary> /// clones the instance /// </summary> public GoTweenConfig clone() { var other = this.MemberwiseClone() as GoTweenConfig; other._tweenProperties = new List<AbstractTweenProperty>( 2 ); for( int k = 0; k < this._tweenProperties.Count; ++k ) { AbstractTweenProperty tweenProp = this._tweenProperties[k]; other._tweenProperties.Add(tweenProp); } return other; } }
using System.Collections.Generic; using System.Linq; using Glimpse.AspNet.AlternateType; using Glimpse.AspNet.Extensibility; using Glimpse.AspNet.Model; using Glimpse.Core.Extensibility; using Glimpse.Core.Extensions; using Glimpse.Core.Tab.Assist; using MvcRoute = System.Web.Routing.Route; using MvcRouteBase = System.Web.Routing.RouteBase; using MvcRouteValueDictionary = System.Web.Routing.RouteValueDictionary; using System.Reflection; using Glimpse.AspNet.Message; namespace Glimpse.AspNet.Tab { public class Routes : AspNetTab, IDocumentation, ITabSetup, ITabLayout, IKey { private static readonly object Layout = TabLayout.Create() .Row(r => { r.Cell(0).WidthInPixels(100); r.Cell(1).AsKey(); r.Cell(2); r.Cell(3).WidthInPercent(20).SetLayout(TabLayout.Create().Row(x => { x.Cell("{{0}} ({{1}})").WidthInPercent(45); x.Cell(2); })); r.Cell(4).WidthInPercent(35).SetLayout(TabLayout.Create().Row(x => { x.Cell(0).WidthInPercent(30); x.Cell(1); x.Cell(2).WidthInPercent(30); })); r.Cell(5).WidthInPercent(15).SetLayout(TabLayout.Create().Row(x => { x.Cell(0).WidthInPercent(45); x.Cell(1).WidthInPercent(55); })); r.Cell(6).WidthInPixels(100).Suffix(" ms").Class("mono").AlignRight(); }).Build(); public override string Name { get { return "Routes"; } } public string Key { get { return "glimpse_routes"; } } public string DocumentationUri { get { return "http://getGlimpse.com/Help/Routes-Tab"; } } public object GetLayout() { return Layout; } public void Setup(ITabSetupContext context) { context.PersistMessages<ProcessConstraintMessage>(); context.PersistMessages<RouteDataMessage>(); } public override object GetData(ITabContext context) { var routeMessages = ProcessMessages(context.GetMessages<RouteDataMessage>()); var constraintMessages = ProcessMessages(context.GetMessages<ProcessConstraintMessage>()); var result = new List<RouteModel>(); using (System.Web.Routing.RouteTable.Routes.GetReadLock()) { foreach (var routeBase in System.Web.Routing.RouteTable.Routes) { if (routeBase.GetType().ToString() == "System.Web.Mvc.Routing.LinkGenerationRoute") { continue; } if (routeBase.GetType().ToString() == "System.Web.Mvc.Routing.RouteCollectionRoute") { // This catches any routing that has been defined using Attribute Based Routing // System.Web.Http.Routing.RouteCollectionRoute is a collection of HttpRoutes var subRoutes = routeBase.GetType().GetField("_subRoutes", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(routeBase); var _routes = (IList<System.Web.Routing.Route>)subRoutes.GetType().GetField("_routes", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(subRoutes); for (var i = 0; i < _routes.Count; i++) { var routeModel = GetRouteModelForRoute(context, _routes[i], routeMessages, constraintMessages); result.Add(routeModel); } } else { var routeModel = GetRouteModelForRoute(context, routeBase, routeMessages, constraintMessages); result.Add(routeModel); } } } return result; } private static TSource SafeFirstOrDefault<TSource>(IEnumerable<TSource> source) { if (source == null) { return default(TSource); } return source.FirstOrDefault(); } private Dictionary<int, List<RouteDataMessage>> ProcessMessages(IEnumerable<RouteDataMessage> messages) { if (messages == null) { return new Dictionary<int, List<RouteDataMessage>>(); } return messages.GroupBy(x => x.RouteHashCode).ToDictionary(x => x.Key, x => x.ToList()); } private Dictionary<int, Dictionary<int, List<ProcessConstraintMessage>>> ProcessMessages(IEnumerable<ProcessConstraintMessage> messages) { if (messages == null) { return new Dictionary<int, Dictionary<int, List<ProcessConstraintMessage>>>(); } return messages.GroupBy(x => x.RouteHashCode).ToDictionary(x => x.Key, x => x.ToList().GroupBy(y => y.ConstraintHashCode).ToDictionary(y => y.Key, y => y.ToList())); } private RouteModel GetRouteModelForRoute(ITabContext context, MvcRouteBase routeBase, Dictionary<int, List<RouteDataMessage>> routeMessages, Dictionary<int, Dictionary<int, List<ProcessConstraintMessage>>> constraintMessages) { var routeModel = new RouteModel(); var routeMessage = SafeFirstOrDefault(routeMessages.GetValueOrDefault(routeBase.GetHashCode())); if (routeMessage != null) { routeModel.Duration = routeMessage.Duration; routeModel.IsMatch = routeMessage.IsMatch; } var route = routeBase as MvcRoute; if (route != null) { routeModel.Area = (route.DataTokens != null && route.DataTokens.ContainsKey("area")) ? route.DataTokens["area"].ToString() : null; routeModel.Url = route.Url; routeModel.RouteData = ProcessRouteData(route.Defaults, routeMessage); routeModel.Constraints = ProcessConstraints(context, route, constraintMessages); routeModel.DataTokens = ProcessDataTokens(route.DataTokens); } else { routeModel.Url = routeBase.ToString(); } var routeName = routeBase as IRouteNameMixin; if (routeName != null) { routeModel.Name = routeName.Name; } return routeModel; } private IEnumerable<RouteDataItemModel> ProcessRouteData(MvcRouteValueDictionary dataDefaults, RouteDataMessage routeMessage) { if (dataDefaults == null || dataDefaults.Count == 0) { return null; } var routeData = new List<RouteDataItemModel>(); foreach (var dataDefault in dataDefaults) { var routeDataItemModel = new RouteDataItemModel(); routeDataItemModel.PlaceHolder = dataDefault.Key; routeDataItemModel.DefaultValue = dataDefault.Value; if (routeMessage != null && routeMessage.Values != null) { routeDataItemModel.ActualValue = routeMessage.Values[dataDefault.Key]; } routeData.Add(routeDataItemModel); } return routeData; } private IEnumerable<RouteConstraintModel> ProcessConstraints(ITabContext context, MvcRoute route, Dictionary<int, Dictionary<int, List<ProcessConstraintMessage>>> constraintMessages) { if (route.Constraints == null || route.Constraints.Count == 0) { return null; } var counstraintRouteMessages = constraintMessages.GetValueOrDefault(route.GetHashCode()); var result = new List<RouteConstraintModel>(); foreach (var constraint in route.Constraints) { var model = new RouteConstraintModel(); model.ParameterName = constraint.Key; model.Constraint = constraint.Value.ToString(); if (counstraintRouteMessages != null) { var counstraintMessage = SafeFirstOrDefault(counstraintRouteMessages.GetValueOrDefault(constraint.Value.GetHashCode())); model.IsMatch = false; if (counstraintMessage != null) { model.IsMatch = counstraintMessage.IsMatch; } } result.Add(model); } return result; } private IDictionary<string, object> ProcessDataTokens(IDictionary<string, object> dataTokens) { return dataTokens != null && dataTokens.Count > 0 ? dataTokens : null; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Securities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using QuantConnect.Orders.Fees; using System.Threading; using QuantConnect.Orders; using QuantConnect.Brokerages.Zerodha.Messages; using Tick = QuantConnect.Data.Market.Tick; using System.Net.WebSockets; using System.Text; using Newtonsoft.Json.Linq; using NodaTime; using QuantConnect.Data.Market; using QuantConnect.Configuration; using QuantConnect.Util; using Order = QuantConnect.Orders.Order; using OrderType = QuantConnect.Orders.OrderType; namespace QuantConnect.Brokerages.Zerodha { /// <summary> /// Zerodha Brokerage implementation /// </summary> [BrokerageFactory(typeof(ZerodhaBrokerageFactory))] public partial class ZerodhaBrokerage : Brokerage, IDataQueueHandler { #region Declarations private const int ConnectionTimeout = 30000; /// <summary> /// The websockets client instance /// </summary> protected WebSocketClientWrapper WebSocket; /// <summary> /// standard json parsing settings /// </summary> protected JsonSerializerSettings JsonSettings = new JsonSerializerSettings { FloatParseHandling = FloatParseHandling.Decimal }; /// <summary> /// A list of currently active orders /// </summary> public ConcurrentDictionary<int, Order> CachedOrderIDs = new ConcurrentDictionary<int, Order>(); /// <summary> /// The api secret /// </summary> protected string ApiSecret; /// <summary> /// The api key /// </summary> protected string ApiKey; private readonly ISecurityProvider _securityProvider; private readonly IAlgorithm _algorithm; private readonly ConcurrentDictionary<int, decimal> _fills = new ConcurrentDictionary<int, decimal>(); private readonly DataQueueHandlerSubscriptionManager SubscriptionManager; private ConcurrentDictionary<string, Symbol> _subscriptionsById = new ConcurrentDictionary<string, Symbol>(); private readonly IDataAggregator _aggregator; private readonly ZerodhaSymbolMapper _symbolMapper; private readonly List<string> subscribeInstrumentTokens = new List<string>(); private readonly List<string> unSubscribeInstrumentTokens = new List<string>(); private Kite _kite; private readonly string _apiKey; private readonly string _accessToken; private readonly string _wssUrl = "wss://ws.kite.trade/"; private readonly string _tradingSegment; private readonly BrokerageConcurrentMessageHandler<WebSocketClientWrapper.MessageData> _messageHandler; private readonly string _zerodhaProductType; private DateTime _lastTradeTickTime; private bool _historyDataTypeErrorFlag; #endregion /// <summary> /// Constructor for brokerage /// </summary> /// <param name="aggregator">data aggregator </param> /// <param name="tradingSegment">trading segment</param> /// <param name="zerodhaProductType">zerodha product type - MIS, CNC or NRML </param> /// <param name="apiKey">api key</param> /// <param name="apiSecret">api secret</param> /// <param name="algorithm">the algorithm instance is required to retrieve account type</param> /// <param name="securityProvider">Security provider for fetching holdings</param> public ZerodhaBrokerage(string tradingSegment, string zerodhaProductType, string apiKey, string apiSecret, IAlgorithm algorithm, ISecurityProvider securityProvider, IDataAggregator aggregator) : base("Zerodha") { _tradingSegment = tradingSegment; _zerodhaProductType = zerodhaProductType; _algorithm = algorithm; _aggregator = aggregator; _kite = new Kite(apiKey, apiSecret); _apiKey = apiKey; _accessToken = apiSecret; _securityProvider = securityProvider; _messageHandler = new BrokerageConcurrentMessageHandler<WebSocketClientWrapper.MessageData>(OnMessageImpl); WebSocket = new WebSocketClientWrapper(); _wssUrl += string.Format(CultureInfo.InvariantCulture, "?api_key={0}&access_token={1}", _apiKey, _accessToken); WebSocket.Initialize(_wssUrl); WebSocket.Message += OnMessage; WebSocket.Open += (sender, args) => { Log.Trace($"ZerodhaBrokerage(): WebSocket.Open. Subscribing"); Subscribe(GetSubscribed()); }; WebSocket.Error += OnError; _symbolMapper = new ZerodhaSymbolMapper(_kite); var subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager(); subscriptionManager.SubscribeImpl += (s, t) => { Subscribe(s); return true; }; subscriptionManager.UnsubscribeImpl += (s, t) => Unsubscribe(s); SubscriptionManager = subscriptionManager; Log.Trace("Start Zerodha Brokerage"); } /// <summary> /// Subscribes to the requested symbols (using an individual streaming channel) /// </summary> /// <param name="symbols">The list of symbols to subscribe</param> public void Subscribe(IEnumerable<Symbol> symbols) { if (symbols.Count() <= 0) { return; } foreach (var symbol in symbols) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { Log.Error($"ZerodhaBrokerage.Subscribe(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); continue; } foreach (var instrumentToken in instrumentTokenList) { var tokenStringInvariant = instrumentToken.ToStringInvariant(); if (!subscribeInstrumentTokens.Contains(tokenStringInvariant)) { subscribeInstrumentTokens.Add(tokenStringInvariant); unSubscribeInstrumentTokens.Remove(tokenStringInvariant); _subscriptionsById[tokenStringInvariant] = symbol; } } } //Websocket Data subscription modes. Full mode gives depth of asks and bids along with basic data. var request = "{\"a\":\"subscribe\",\"v\":[" + String.Join(",", subscribeInstrumentTokens.ToArray()) + "]}"; var requestFullMode = "{\"a\":\"mode\",\"v\":[\"full\",[" + String.Join(",", subscribeInstrumentTokens.ToArray()) + "]]}"; WebSocket.Send(request); WebSocket.Send(requestFullMode); } /// <summary> /// Get list of subscribed symbol /// </summary> /// <returns></returns> private IEnumerable<Symbol> GetSubscribed() { return SubscriptionManager.GetSubscribedSymbols() ?? Enumerable.Empty<Symbol>(); } /// <summary> /// Ends current subscriptions /// </summary> private bool Unsubscribe(IEnumerable<Symbol> symbols) { if (WebSocket.IsOpen) { foreach (var symbol in symbols) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { Log.Error($"ZerodhaBrokerage.Unsubscribe(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); continue; } foreach (var instrumentToken in instrumentTokenList) { var tokenStringInvariant = instrumentToken.ToStringInvariant(); if (!unSubscribeInstrumentTokens.Contains(tokenStringInvariant)) { unSubscribeInstrumentTokens.Add(tokenStringInvariant); subscribeInstrumentTokens.Remove(tokenStringInvariant); Symbol unSubscribeSymbol; _subscriptionsById.TryRemove(tokenStringInvariant, out unSubscribeSymbol); } } } var request = "{\"a\":\"unsubscribe\",\"v\":[" + String.Join(",", unSubscribeInstrumentTokens.ToArray()) + "]}"; WebSocket.Send(request); return true; } return false; } /// <summary> /// Gets Quote using Zerodha API /// </summary> /// <returns> Quote</returns> public Quote GetQuote(Symbol symbol) { var instrumentTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.ID.Symbol); if (instrumentTokenList.Count == 0) { throw new ArgumentException($"ZerodhaBrokerage.GetQuote(): Invalid Zerodha Instrument token for given: {symbol.ID.Symbol}"); } var instrument = instrumentTokenList[0]; var instrumentIds = new string[] { instrument.ToStringInvariant() }; var quotes = _kite.GetQuote(instrumentIds); return quotes[instrument.ToStringInvariant()]; } /// <summary> /// Zerodha brokerage order events /// </summary> /// <param name="orderUpdate"></param> private void OnOrderUpdate(Messages.Order orderUpdate) { try { var brokerId = orderUpdate.OrderId; Log.Trace("OnZerodhaOrderEvent(): Broker ID:" + brokerId); var order = CachedOrderIDs .FirstOrDefault(o => o.Value.BrokerId.Contains(brokerId)) .Value; if (order == null) { order = _algorithm.Transactions.GetOrderByBrokerageId(brokerId); if (order == null) { // not our order, nothing else to do here return; } } if (orderUpdate.Status == "CANCELLED") { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); } if (orderUpdate.Status == "REJECTED") { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Zerodha Order Rejected Event: " + orderUpdate.StatusMessage) { Status = OrderStatus.Canceled }); } if (orderUpdate.FilledQuantity > 0) { var symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(orderUpdate.InstrumentToken); var fillPrice = orderUpdate.AveragePrice; var fillQuantity = orderUpdate.FilledQuantity; var direction = orderUpdate.TransactionType == "SELL" ? OrderDirection.Sell : OrderDirection.Buy; var updTime = orderUpdate.OrderTimestamp.GetValueOrDefault(); var security = _securityProvider.GetSecurity(order.Symbol); var orderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); if (direction == OrderDirection.Sell) { fillQuantity = -1 * fillQuantity; } var status = OrderStatus.Filled; if (fillQuantity != order.Quantity) { decimal totalFillQuantity; _fills.TryGetValue(order.Id, out totalFillQuantity); totalFillQuantity += fillQuantity; _fills[order.Id] = totalFillQuantity; status = totalFillQuantity == order.Quantity ? OrderStatus.Filled : OrderStatus.PartiallyFilled; } var orderEvent = new OrderEvent ( order.Id, symbol, updTime, status, direction, fillPrice, fillQuantity, orderFee, $"Zerodha Order Event {direction}" ); // if the order is closed, we no longer need it in the active order list if (status == OrderStatus.Filled) { Order outOrder; CachedOrderIDs.TryRemove(order.Id, out outOrder); decimal ignored; _fills.TryRemove(order.Id, out ignored); } OnOrderEvent(orderEvent); } } catch (Exception e) { Log.Error(e); throw; } } #region IBrokerage /// <summary> /// Returns the brokerage account's base currency /// </summary> public override string AccountBaseCurrency => Currencies.INR; /// <summary> /// Checks if the websocket connection is connected or in the process of connecting /// </summary> public override bool IsConnected => WebSocket.IsOpen; /// <summary> /// Connects to Zerodha wss /// </summary> public override void Connect() { if (IsConnected) { return; } Log.Trace("ZerodhaBrokerage.Connect(): Connecting..."); var resetEvent = new ManualResetEvent(false); EventHandler triggerEvent = (o, args) => resetEvent.Set(); WebSocket.Open += triggerEvent; WebSocket.Connect(); if (!resetEvent.WaitOne(ConnectionTimeout)) { throw new TimeoutException("Websockets connection timeout."); } WebSocket.Open -= triggerEvent; } /// <summary> /// Closes the websockets connection /// </summary> public override void Disconnect() { //base.Disconnect(); if (WebSocket.IsOpen) { WebSocket.Close(); } } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { uint orderQuantity = Convert.ToUInt32(Math.Abs(order.Quantity)); JObject orderResponse = new JObject();; decimal? triggerPrice = GetOrderTriggerPrice(order); decimal? orderPrice = GetOrderPrice(order); var kiteOrderType = ConvertOrderType(order.Type); var security = _securityProvider.GetSecurity(order.Symbol); var orderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); var orderProperties = order.Properties as ZerodhaOrderProperties; var zerodhaProductType = _zerodhaProductType; if (orderProperties == null || orderProperties.Exchange == null) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: Please specify a valid order properties with an exchange value"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if (orderProperties.ProductType != null) { zerodhaProductType = orderProperties.ProductType; } else if (string.IsNullOrEmpty(zerodhaProductType)) { throw new ArgumentException("Please set ProductType in config or provide a value in DefaultOrderProperties"); } try { orderResponse = _kite.PlaceOrder(orderProperties.Exchange.ToUpperInvariant(), order.Symbol.ID.Symbol, order.Direction.ToString().ToUpperInvariant(), orderQuantity, orderPrice, zerodhaProductType, kiteOrderType, null, null, triggerPrice); } catch (Exception ex) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {ex.Message}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if ((string)orderResponse["status"] == "success") { if (string.IsNullOrEmpty((string)orderResponse["data"]["order_id"])) { var errorMessage = $"Error parsing response from place order: {(string)orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (string)orderResponse["status_message"], errorMessage)); return; } var brokerId = (string)orderResponse["data"]["order_id"]; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Clear(); CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } // Generate submitted event OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Submitted }); Log.Trace($"Order submitted successfully - OrderId: {order.Id}"); submitted = true; return; } var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message)); return; }); return submitted; } /// <summary> /// Return a relevant price for order depending on order type /// Price must be positive /// </summary> /// <param name="order"></param> /// <returns></returns> private static decimal? GetOrderPrice(Order order) { switch (order.Type) { case OrderType.Limit: return ((LimitOrder)order).LimitPrice; case OrderType.StopLimit: return ((StopLimitOrder)order).LimitPrice; case OrderType.Market: case OrderType.StopMarket: return null; } throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {order.Type}"); } /// <summary> /// Return a relevant price for order depending on order type /// Price must be positive /// </summary> /// <param name="order"></param> /// <returns></returns> private static decimal? GetOrderTriggerPrice(Order order) { switch (order.Type) { case OrderType.StopLimit: return ((StopLimitOrder)order).StopPrice; case OrderType.StopMarket: return ((StopMarketOrder)order).StopPrice; case OrderType.Limit: case OrderType.Market: return null; } throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {order.Type}"); } private static string ConvertOrderType(OrderType orderType) { switch (orderType) { case OrderType.Limit: return "LIMIT"; case OrderType.Market: return "MARKET"; case OrderType.StopMarket: return "SL-M"; case OrderType.StopLimit: return "SL"; default: throw new NotSupportedException($"ZerodhaBrokerage.ConvertOrderType: Unsupported order type: {orderType}"); } } /// <summary> /// Updates the order with the same id /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public override bool UpdateOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { if (!order.Status.IsOpen()) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "error", "Order is already being processed")); return; } var orderProperties = order.Properties as ZerodhaOrderProperties; var zerodhaProductType = _zerodhaProductType; if (orderProperties == null || orderProperties.Exchange == null) { var errorMessage = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: Please specify a valid order properties with an exchange value"; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, errorMessage)); return; } if (orderProperties.ProductType != null) { zerodhaProductType = orderProperties.ProductType; } else if (string.IsNullOrEmpty(zerodhaProductType)) { throw new ArgumentException("Please set ProductType in config or provide a value in DefaultOrderProperties"); } uint orderQuantity = Convert.ToUInt32(Math.Abs(order.Quantity)); JObject orderResponse = new JObject();; decimal? triggerPrice = GetOrderTriggerPrice(order); decimal? orderPrice = GetOrderPrice(order); var kiteOrderType = ConvertOrderType(order.Type); var orderFee = OrderFee.Zero; try { orderResponse = _kite.ModifyOrder(order.BrokerId[0].ToStringInvariant(), null, orderProperties.Exchange.ToUpperInvariant(), order.Symbol.ID.Symbol, order.Direction.ToString().ToUpperInvariant(), orderQuantity, orderPrice, zerodhaProductType, kiteOrderType, null, null, triggerPrice ); } catch (Exception ex) { OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {ex.Message}")); return; } if ((string)orderResponse["status"] == "success") { if (string.IsNullOrEmpty((string)orderResponse["data"]["order_id"])) { var errorMessage = $"Error parsing response from modify order: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid, Message = errorMessage }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, (string)orderResponse["status"], errorMessage)); submitted = true; return; } var brokerId = (string)orderResponse["data"]["order_id"]; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Clear(); CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } // Generate submitted event OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.UpdateSubmitted }); Log.Trace($"Order modified successfully - OrderId: {order.Id}"); submitted = true; return; } var message = $"Order failed, Order Id: {order.Id} timestamp: {order.Time} quantity: {order.Quantity} content: {orderResponse["status_message"]}"; OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, orderFee, "Zerodha Update Order Event") { Status = OrderStatus.Invalid }); OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, -1, message)); return; }); return submitted; } /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was submitted for cancellation, false otherwise</returns> public override bool CancelOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { JObject orderResponse = new JObject(); if (order.Status.IsOpen()) { try { orderResponse = _kite.CancelOrder(order.BrokerId[0].ToStringInvariant()); } catch (Exception) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (string)orderResponse["status"], $"Error cancelling order: {orderResponse["status_message"]}")); return; } } else { //Verify this OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, 500, $"Error cancelling open order")); return; } if ((string)orderResponse["status"] == "success") { OnOrderEvent(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "Zerodha Order Cancelled Event") { Status = OrderStatus.Canceled }); submitted = true; return; } var errorMessage = $"Error cancelling order: {orderResponse["status_message"]}"; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (string)orderResponse["status"], errorMessage)); return; }); return submitted; } /// <summary> /// Gets all orders not yet closed /// </summary> /// <returns></returns> public override List<Order> GetOpenOrders() { var allOrders = _kite.GetOrders(); List<Order> list = new List<Order>(); //Only loop if there are any actual orders inside response if (allOrders.Count > 0) { foreach (var item in allOrders.Where(z => z.Status == "OPEN" || z.Status == "TRIGGER PENDING")) { Order order; if (item.OrderType.ToUpperInvariant() == "MARKET") { order = new MarketOrder { Price = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "LIMIT") { order = new LimitOrder { LimitPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "SL-M") { order = new StopMarketOrder { StopPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else if (item.OrderType.ToUpperInvariant() == "SL") { order = new StopLimitOrder { StopPrice = Convert.ToDecimal(item.TriggerPrice, CultureInfo.InvariantCulture), LimitPrice = Convert.ToDecimal(item.Price, CultureInfo.InvariantCulture) }; } else { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, "UnKnownOrderType", "ZerodhaBrorage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.OrderType)); continue; } var itemTotalQty = item.Quantity; var originalQty = item.Quantity; order.Quantity = item.TransactionType.ToLowerInvariant() == "sell" ? -itemTotalQty : originalQty; order.BrokerId = new List<string> { item.OrderId }; order.Symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(item.InstrumentToken); order.Time = (DateTime)item.OrderTimestamp; order.Status = ConvertOrderStatus(item); order.Price = item.Price; list.Add(order); } foreach (var item in list) { if (item.Status.IsOpen()) { var cached = CachedOrderIDs.Where(c => c.Value.BrokerId.Contains(item.BrokerId.First())); if (cached.Any()) { CachedOrderIDs[cached.First().Key] = item; } } } } return list; } private OrderStatus ConvertOrderStatus(Messages.Order orderDetails) { var filledQty = Convert.ToInt32(orderDetails.FilledQuantity, CultureInfo.InvariantCulture); var pendingQty = Convert.ToInt32(orderDetails.PendingQuantity, CultureInfo.InvariantCulture); var orderDetail = _kite.GetOrderHistory(orderDetails.OrderId); if (orderDetails.Status.ToLowerInvariant() != "complete" && filledQty == 0) { return OrderStatus.Submitted; } else if (filledQty > 0 && pendingQty > 0) { return OrderStatus.PartiallyFilled; } else if (pendingQty == 0) { return OrderStatus.Filled; } else if (orderDetails.Status.ToUpperInvariant() == "CANCELLED") { return OrderStatus.Canceled; } return OrderStatus.None; } /// <summary> /// Gets all open postions and account holdings /// </summary> /// <returns></returns> public override List<Holding> GetAccountHoldings() { var holdingsList = new List<Holding>(); var zerodhaProductTypeUpper = _zerodhaProductType.ToUpperInvariant(); var productTypeMIS = KiteProductType.MIS.ToString().ToUpperInvariant(); var productTypeNRML = KiteProductType.NRML.ToString().ToUpperInvariant(); var productTypeCNC = KiteProductType.CNC.ToString().ToUpperInvariant(); // get MIS and NRML Positions if (string.IsNullOrEmpty(_zerodhaProductType) || zerodhaProductTypeUpper == productTypeMIS || zerodhaProductTypeUpper == productTypeNRML) { var PositionsResponse = _kite.GetPositions(); if (PositionsResponse.Day.Count != 0) { foreach (var item in PositionsResponse.Day) { Holding holding = new Holding { AveragePrice = item.AveragePrice, Symbol = _symbolMapper.GetLeanSymbol(item.TradingSymbol), MarketPrice = item.LastPrice, Quantity = item.Quantity, UnrealizedPnL = item.Unrealised, CurrencySymbol = Currencies.GetCurrencySymbol(AccountBaseCurrency), MarketValue = item.ClosePrice * item.Quantity }; holdingsList.Add(holding); } } } // get CNC Positions if (string.IsNullOrEmpty(_zerodhaProductType) || zerodhaProductTypeUpper == productTypeCNC ) { var HoldingResponse = _kite.GetHoldings(); if (HoldingResponse != null) { foreach (var item in HoldingResponse) { Holding holding = new Holding { AveragePrice = item.AveragePrice, Symbol = _symbolMapper.GetLeanSymbol(item.TradingSymbol), MarketPrice = item.LastPrice, Quantity = item.Quantity, UnrealizedPnL = item.PNL, CurrencySymbol = Currencies.GetCurrencySymbol(AccountBaseCurrency), MarketValue = item.ClosePrice * item.Quantity }; holdingsList.Add(holding); } } } return holdingsList; } /// <summary> /// Gets the total account cash balance for specified account type /// </summary> /// <returns></returns> public override List<CashAmount> GetCashBalance() { decimal amt = 0m; var list = new List<CashAmount>(); var response = _kite.GetMargins(); if (_tradingSegment == "EQUITY") { amt = Convert.ToDecimal(response.Equity.Available.Cash, CultureInfo.InvariantCulture); } else { amt = Convert.ToDecimal(response.Commodity.Available.Cash, CultureInfo.InvariantCulture); } list.Add(new CashAmount(amt, AccountBaseCurrency)); return list; } /// <summary> /// Gets the history for the requested security /// </summary> /// <param name="request">The historical data request</param> /// <returns>An enumerable of bars covering the span specified in the request</returns> public override IEnumerable<BaseData> GetHistory(HistoryRequest request) { if (request.DataType != typeof(TradeBar) && !_historyDataTypeErrorFlag) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidBarType", $"{request.DataType} type not supported, no history returned")); _historyDataTypeErrorFlag = true; yield break; } if (request.Symbol.SecurityType != SecurityType.Equity && request.Symbol.SecurityType != SecurityType.Future && request.Symbol.SecurityType != SecurityType.Option) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidSecurityType", $"{request.Symbol.SecurityType} security type not supported, no history returned")); yield break; } if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution", $"{request.Resolution} resolution not supported, no history returned")); yield break; } if (request.StartTimeUtc >= request.EndTimeUtc) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidDateRange", "The history request start date must precede the end date, no history returned")); yield break; } if (request.Symbol.ID.SecurityType != SecurityType.Equity && request.Symbol.ID.SecurityType != SecurityType.Future && request.Symbol.ID.SecurityType != SecurityType.Option) { throw new ArgumentException("Zerodha does not support this security type: " + request.Symbol.ID.SecurityType); } if (request.StartTimeUtc >= request.EndTimeUtc) { throw new ArgumentException("Invalid date range specified"); } var history = Enumerable.Empty<BaseData>(); var symbol = request.Symbol; var start = request.StartTimeLocal; var end = request.EndTimeLocal; var resolution = request.Resolution; var exchangeTimeZone = request.ExchangeHours.TimeZone; if (Config.GetBool("zerodha-history-subscription")) { switch (resolution) { case Resolution.Minute: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "minute"); break; case Resolution.Hour: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "60minute"); break; case Resolution.Daily: history = GetHistoryForPeriod(symbol, start, end, exchangeTimeZone, resolution, "day"); break; } } foreach (var baseData in history) { yield return baseData; } } private IEnumerable<BaseData> GetHistoryForPeriod(Symbol symbol, DateTime start, DateTime end, DateTimeZone exchangeTimeZone, Resolution resolution, string zerodhaResolution) { Log.Debug("ZerodhaBrokerage.GetHistoryForPeriod();"); var scripSymbolTokenList = _symbolMapper.GetZerodhaInstrumentTokenList(symbol.Value); if (scripSymbolTokenList.Count == 0) { throw new ArgumentException($"ZerodhaBrokerage.GetQuote(): Invalid Zerodha Instrument token for given: {symbol.Value}"); } var scripSymbol = scripSymbolTokenList[0]; var candles = _kite.GetHistoricalData(scripSymbol.ToStringInvariant(), start, end, zerodhaResolution); if (!candles.Any()) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "NoHistoricalData", $"Exchange returned no data for {symbol} on history request " + $"from {start:s} to {end:s}")); } foreach (var candle in candles) { yield return new TradeBar(candle.TimeStamp.ConvertFromUtc(exchangeTimeZone),symbol,candle.Open,candle.High,candle.Low,candle.Close,candle.Volume,resolution.ToTimeSpan()); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { _aggregator.DisposeSafely(); if (WebSocket.IsOpen) { WebSocket.Close(); } } private void OnError(object sender, WebSocketError e) { Log.Error($"ZerodhaBrokerage.OnError(): Message: {e.Message} Exception: {e.Exception}"); } private void OnMessage(object sender, WebSocketMessage webSocketMessage) { _messageHandler.HandleNewMessage(webSocketMessage.Data); } /// <summary> /// Implementation of the OnMessage event /// </summary> /// <param name="e"></param> private void OnMessageImpl(WebSocketClientWrapper.MessageData message) { try { if (message.MessageType == WebSocketMessageType.Binary) { var e = (WebSocketClientWrapper.BinaryMessage)message; if (e.Count > 1) { int offset = 0; ushort count = ReadShort(e.Data, ref offset); //number of packets for (ushort i = 0; i < count; i++) { ushort length = ReadShort(e.Data, ref offset); // length of the packet Messages.Tick tick = new Messages.Tick(); if (length == 8) // ltp tick = ReadLTP(e.Data, ref offset); else if (length == 28) // index quote tick = ReadIndexQuote(e.Data, ref offset); else if (length == 32) // index quote tick = ReadIndexFull(e.Data, ref offset); else if (length == 44) // quote tick = ReadQuote(e.Data, ref offset); else if (length == 184) // full with marketdepth and timestamp tick = ReadFull(e.Data, ref offset); // If the number of bytes got from stream is less that that is required // data is invalid. This will skip that wrong tick if (tick.InstrumentToken != 0 && offset <= e.Count && tick.Mode == Constants.MODE_FULL) { var symbol = _symbolMapper.ConvertZerodhaSymbolToLeanSymbol(tick.InstrumentToken); var bestBidQuote = tick.Bids[0]; var bestAskQuote = tick.Offers[0]; var instrumentTokenValue = tick.InstrumentToken; var time = tick.Timestamp ?? DateTime.UtcNow.ConvertFromUtc(TimeZones.Kolkata); EmitQuoteTick(symbol, instrumentTokenValue, time, bestBidQuote.Price, bestBidQuote.Quantity, bestAskQuote.Price, bestAskQuote.Quantity); if (_lastTradeTickTime != time) { EmitTradeTick(symbol, instrumentTokenValue, time, tick.LastPrice, tick.LastQuantity); _lastTradeTickTime = time; } } } } } else if (message.MessageType == WebSocketMessageType.Text) { var e = (WebSocketClientWrapper.TextMessage)message; JObject messageDict = Utils.JsonDeserialize(e.Message); if ((string)messageDict["type"] == "order") { OnOrderUpdate(new Messages.Order(messageDict["data"])); } else if ((string)messageDict["type"] == "error") { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Zerodha WSS Error. Data: {e.Message} Exception: {messageDict["data"]}")); } } } catch (Exception exception) { if (message.MessageType == WebSocketMessageType.Binary) { var e = (WebSocketClientWrapper.BinaryMessage)message; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Data} Exception: {exception}")); throw; } else { var e = (WebSocketClientWrapper.TextMessage)message; OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, $"Parsing wss message failed. Data: {e.Message} Exception: {exception}")); throw; } } } private void EmitTradeTick(Symbol symbol, uint instrumentToken, DateTime time, decimal price, decimal amount) { var exchange = _symbolMapper.GetZerodhaExchangeFromToken(instrumentToken); if (string.IsNullOrEmpty(exchange)) { Log.Error($"ZerodhaBrokerage.EmitTradeTick(): market info is NUll/Empty for: {symbol.ID.Symbol}"); } var tick = new Tick(time, symbol, string.Empty, exchange, Math.Abs(amount), price); _aggregator.Update(tick); } private void EmitQuoteTick(Symbol symbol, uint instrumentToken, DateTime time, decimal bidPrice, decimal bidSize, decimal askPrice, decimal askSize) { if (bidPrice > 0 && askPrice > 0) { var exchange = _symbolMapper.GetZerodhaExchangeFromToken(instrumentToken); if (string.IsNullOrEmpty(exchange)) { Log.Error($"ZerodhaBrokerage.EmitQuoteTick(): market info is NUll/Empty for: {symbol.ID.Symbol}"); } var tick = new Tick(time, symbol, string.Empty, exchange, bidSize, bidPrice, askSize, askPrice); _aggregator.Update(tick); } } /// <summary> /// Reads 2 byte short int from byte stream /// </summary> private ushort ReadShort(byte[] b, ref int offset) { ushort data = (ushort)(b[offset + 1] + (b[offset] << 8)); offset += 2; return data; } /// <summary> /// Reads 4 byte int32 from byte stream /// </summary> private uint ReadInt(byte[] b, ref int offset) { uint data = BitConverter.ToUInt32(new byte[] { b[offset + 3], b[offset + 2], b[offset + 1], b[offset + 0] }, 0); offset += 4; return data; } /// <summary> /// Reads an ltp mode tick from raw binary data /// </summary> private Messages.Tick ReadLTP(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_LTP; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; return tick; } /// <summary> /// Reads a index's quote mode tick from raw binary data /// </summary> private Messages.Tick ReadIndexQuote(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_QUOTE; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Open = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; tick.Change = ReadInt(b, ref offset) / divisor; return tick; } private Messages.Tick ReadIndexFull(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_FULL; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Open = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; tick.Change = ReadInt(b, ref offset) / divisor; uint time = ReadInt(b, ref offset); tick.Timestamp = Time.UnixTimeStampToDateTime(time); return tick; } /// <summary> /// Reads a quote mode tick from raw binary data /// </summary> private Messages.Tick ReadQuote(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick { Mode = Constants.MODE_QUOTE, InstrumentToken = ReadInt(b, ref offset) }; decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.LastQuantity = ReadInt(b, ref offset); tick.AveragePrice = ReadInt(b, ref offset) / divisor; tick.Volume = ReadInt(b, ref offset); tick.BuyQuantity = ReadInt(b, ref offset); tick.SellQuantity = ReadInt(b, ref offset); tick.Open = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; return tick; } /// <summary> /// Reads a full mode tick from raw binary data /// </summary> private Messages.Tick ReadFull(byte[] b, ref int offset) { Messages.Tick tick = new Messages.Tick(); tick.Mode = Constants.MODE_FULL; tick.InstrumentToken = ReadInt(b, ref offset); decimal divisor = (tick.InstrumentToken & 0xff) == 3 ? 10000000.0m : 100.0m; tick.Tradable = (tick.InstrumentToken & 0xff) != 9; tick.LastPrice = ReadInt(b, ref offset) / divisor; tick.LastQuantity = ReadInt(b, ref offset); tick.AveragePrice = ReadInt(b, ref offset) / divisor; tick.Volume = ReadInt(b, ref offset); tick.BuyQuantity = ReadInt(b, ref offset); tick.SellQuantity = ReadInt(b, ref offset); tick.Open = ReadInt(b, ref offset) / divisor; tick.High = ReadInt(b, ref offset) / divisor; tick.Low = ReadInt(b, ref offset) / divisor; tick.Close = ReadInt(b, ref offset) / divisor; // KiteConnect 3 fields tick.LastTradeTime = Time.UnixTimeStampToDateTime(ReadInt(b, ref offset)); tick.OI = ReadInt(b, ref offset); tick.OIDayHigh = ReadInt(b, ref offset); tick.OIDayLow = ReadInt(b, ref offset); tick.Timestamp = Time.UnixTimeStampToDateTime(ReadInt(b, ref offset)); tick.Bids = new DepthItem[5]; for (int i = 0; i < 5; i++) { tick.Bids[i].Quantity = ReadInt(b, ref offset); tick.Bids[i].Price = ReadInt(b, ref offset) / divisor; tick.Bids[i].Orders = ReadShort(b, ref offset); offset += 2; } tick.Offers = new DepthItem[5]; for (int i = 0; i < 5; i++) { tick.Offers[i].Quantity = ReadInt(b, ref offset); tick.Offers[i].Price = ReadInt(b, ref offset) / divisor; tick.Offers[i].Orders = ReadShort(b, ref offset); offset += 2; } return tick; } #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.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Xunit; using Microsoft.Xunit.Performance; [assembly: OptimizeForBenchmarks] namespace Span { public class SpanBench { #if DEBUG const int BubbleSortIterations = 1; const int QuickSortIterations = 1; const int FillAllIterations = 1; const int BaseIterations = 1; #else // Appropriately-scaled iteration counts for the various benchmarks const int BubbleSortIterations = 100; const int QuickSortIterations = 1000; const int FillAllIterations = 100000; const int BaseIterations = 10000000; #endif // Default length for arrays of mock input data const int DefaultLength = 1024; // Helpers #region Helpers [StructLayout(LayoutKind.Sequential)] private sealed class TestClass<T> { private double _d; public T[] C0; } // Copying the result of a computation to Sink<T>.Instance is a way // to prevent the jit from considering the computation dead and removing it. private sealed class Sink<T> { public T Data; public static Sink<T> Instance = new Sink<T>(); } // Use statics to smuggle some information from Main to Invoke when running tests // from the command line. static bool IsXunitInvocation = true; // xunit-perf leaves this true; command line Main sets to false static int CommandLineInnerIterationCount = 0; // used to communicate iteration count from BenchmarkAttribute // (xunit-perf exposes the same in static property Benchmark.InnerIterationCount) static bool DoWarmUp; // Main sets this when calling a new benchmark routine // Invoke routine to abstract away the difference between running under xunit-perf vs running from the // command line. Inner loop to be measured is taken as an Action<int>, and invoked passing the number // of iterations that the inner loop should execute. static void Invoke(Action<int> innerLoop, string nameFormat, params object[] nameArgs) { if (IsXunitInvocation) { foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) innerLoop((int)Benchmark.InnerIterationCount); } else { if (DoWarmUp) { // Run some warm-up iterations before measuring innerLoop(CommandLineInnerIterationCount); // Clear the flag since we're now warmed up (caller will // reset it before calling new code) DoWarmUp = false; } // Now do the timed run of the inner loop. Stopwatch sw = Stopwatch.StartNew(); innerLoop(CommandLineInnerIterationCount); sw.Stop(); // Print result. string name = String.Format(nameFormat, nameArgs); double timeInMs = sw.Elapsed.TotalMilliseconds; Console.WriteLine("{0}: {1}ms", name, timeInMs); } } // Helper for the sort tests to get some pseudo-random input static int[] GetUnsortedData(int length) { int[] unsortedData = new int[length]; Random r = new Random(42); for (int i = 0; i < unsortedData.Length; ++i) { unsortedData[i] = r.Next(); } return unsortedData; } #endregion // helpers // Tests that implement some vary basic algorithms (fill/sort) over spans and arrays #region Algorithm tests #region TestFillAllSpan [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllSpan(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { Span<byte> s = new Span<byte>(a); for (int i = 0; i < innerIterationCount; ++i) { TestFillAllSpan(s); } }, "TestFillAllSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllSpan(Span<byte> span) { for (int i = 0; i < span.Length; ++i) { span[i] = unchecked((byte)i); } } #endregion #region TestFillAllArray [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllArray(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; ++i) { TestFillAllArray(a); } }, "TestFillArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllArray(byte[] data) { for (int i = 0; i < data.Length; ++i) { data[i] = unchecked((byte)i); } } #endregion #region TestFillAllReverseSpan [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllReverseSpan(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { Span<byte> s = new Span<byte>(a); for (int i = 0; i < innerIterationCount; ++i) { TestFillAllReverseSpan(s); } }, "TestFillAllReverseSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllReverseSpan(Span<byte> span) { for (int i = span.Length; --i >= 0;) { span[i] = unchecked((byte)i); } } #endregion #region TestFillAllReverseArray [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllReverseArray(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; ++i) { TestFillAllReverseArray(a); } }, "TestFillAllReverseArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllReverseArray(byte[] data) { for (int i = data.Length; --i >= 0;) { data[i] = unchecked((byte)i); } } #endregion #region TestQuickSortSpan [Benchmark(InnerIterationCount = QuickSortIterations)] [InlineData(DefaultLength)] public static void QuickSortSpan(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { Span<int> span = new Span<int>(data); for (int i = 0; i < innerIterationCount; ++i) { Array.Copy(unsortedData, data, length); TestQuickSortSpan(span); } }, "TestQuickSortSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestQuickSortSpan(Span<int> data) { if (data.Length <= 1) { return; } int lo = 0; int hi = data.Length - 1; int i, j; int pivot, temp; for (i = lo, j = hi, pivot = data[hi]; i < j;) { while (i < j && data[i] <= pivot) { ++i; } while (j > i && data[j] >= pivot) { --j; } if (i < j) { temp = data[i]; data[i] = data[j]; data[j] = temp; } } if (i != hi) { temp = data[i]; data[i] = pivot; data[hi] = temp; } TestQuickSortSpan(data.Slice(0, i)); TestQuickSortSpan(data.Slice(i + 1)); } #endregion #region TestBubbleSortSpan [Benchmark(InnerIterationCount = BubbleSortIterations)] [InlineData(DefaultLength)] public static void BubbleSortSpan(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { Span<int> span = new Span<int>(data); for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestBubbleSortSpan(span); } }, "TestBubbleSortSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestBubbleSortSpan(Span<int> span) { bool swap; int temp; int n = span.Length - 1; do { swap = false; for (int i = 0; i < n; i++) { if (span[i] > span[i + 1]) { temp = span[i]; span[i] = span[i + 1]; span[i + 1] = temp; swap = true; } } --n; } while (swap); } #endregion #region TestQuickSortArray [Benchmark(InnerIterationCount = QuickSortIterations)] [InlineData(DefaultLength)] public static void QuickSortArray(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestQuickSortArray(data, 0, data.Length - 1); } }, "TestQuickSortArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestQuickSortArray(int[] data, int lo, int hi) { if (lo >= hi) { return; } int i, j; int pivot, temp; for (i = lo, j = hi, pivot = data[hi]; i < j;) { while (i < j && data[i] <= pivot) { ++i; } while (j > i && data[j] >= pivot) { --j; } if (i < j) { temp = data[i]; data[i] = data[j]; data[j] = temp; } } if (i != hi) { temp = data[i]; data[i] = pivot; data[hi] = temp; } TestQuickSortArray(data, lo, i - 1); TestQuickSortArray(data, i + 1, hi); } #endregion #region TestBubbleSortArray [Benchmark(InnerIterationCount = BubbleSortIterations)] [InlineData(DefaultLength)] public static void BubbleSortArray(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestBubbleSortArray(data); } }, "TestBubbleSortArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestBubbleSortArray(int[] data) { bool swap; int temp; int n = data.Length - 1; do { swap = false; for (int i = 0; i < n; i++) { if (data[i] > data[i + 1]) { temp = data[i]; data[i] = data[i + 1]; data[i + 1] = temp; swap = true; } } --n; } while (swap); } #endregion #endregion // Algorithm tests // TestSpanAPIs (For comparison with Array and Slow Span) #region TestSpanAPIs #region TestSpanConstructor<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanConstructorByte(int length) { InvokeTestSpanConstructor<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanConstructorString(int length) { InvokeTestSpanConstructor<string>(length); } static void InvokeTestSpanConstructor<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanConstructor<T>(array, innerIterationCount, false), "TestSpanConstructor<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanConstructor<T>(T[] array, int iterationCount, bool untrue) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var span = new Span<T>(array); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'array' so the constructor call won't get hoisted. if (untrue) { sink.Data = span[0]; array = new T[iterationCount]; } } } #endregion #region TestSpanDangerousCreate<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousCreateByte(int length) { InvokeTestSpanDangerousCreate<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousCreateString(int length) { InvokeTestSpanDangerousCreate<string>(length); } static void InvokeTestSpanDangerousCreate<T>(int length) { TestClass<T> testClass = new TestClass<T>(); testClass.C0 = new T[length]; Invoke((int innerIterationCount) => TestSpanDangerousCreate<T>(testClass, innerIterationCount, false), "TestSpanDangerousCreate<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanDangerousCreate<T>(TestClass<T> testClass, int iterationCount, bool untrue) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var span = Span<T>.DangerousCreate(testClass, ref testClass.C0[0], testClass.C0.Length); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'testClass' so the DangerousCreate call won't get hoisted. if (untrue) { sink.Data = span[0]; testClass = new TestClass<T>(); } } } #endregion #region TestSpanDangerousGetPinnableReference<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousGetPinnableReferenceByte(int length) { InvokeTestSpanDangerousGetPinnableReference<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousGetPinnableReferenceString(int length) { InvokeTestSpanDangerousGetPinnableReference<string>(length); } static void InvokeTestSpanDangerousGetPinnableReference<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanDangerousGetPinnableReference<T>(array, innerIterationCount), "TestSpanDangerousGetPinnableReference<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanDangerousGetPinnableReference<T>(T[] array, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) { ref T temp = ref span.DangerousGetPinnableReference(); sink.Data = temp; } } #endregion #region TestSpanIndexHoistable<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexHoistableByte(int length) { InvokeTestSpanIndexHoistable<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexHoistableString(int length) { InvokeTestSpanIndexHoistable<string>(length); } static void InvokeTestSpanIndexHoistable<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanIndexHoistable<T>(array, length, innerIterationCount), "TestSpanIndexHoistable<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanIndexHoistable<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) sink.Data = span[length/2]; } #endregion #region TestArrayIndexHoistable<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexHoistableByte(int length) { InvokeTestArrayIndexHoistable<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexHoistableString(int length) { InvokeTestArrayIndexHoistable<string>(length); } static void InvokeTestArrayIndexHoistable<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayIndexHoistable<T>(array, length, innerIterationCount), "TestArrayIndexHoistable<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayIndexHoistable<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) sink.Data = array[length / 2]; } #endregion #region TestSpanIndexVariant<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexVariantByte(int length) { InvokeTestSpanIndexVariant<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexVariantString(int length) { InvokeTestSpanIndexVariant<string>(length); } static void InvokeTestSpanIndexVariant<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanIndexVariant<T>(array, length, innerIterationCount), "TestSpanIndexVariant<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanIndexVariant<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7)); for (int i = 0; i < iterationCount; i++) sink.Data = span[i & mask]; } #endregion #region TestArrayIndexVariant<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexVariantByte(int length) { InvokeTestArrayIndexVariant<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexVariantString(int length) { InvokeTestArrayIndexVariant<string>(length); } static void InvokeTestArrayIndexVariant<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayIndexVariant<T>(array, length, innerIterationCount), "TestArrayIndexVariant<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayIndexVariant<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7)); for (int i = 0; i < iterationCount; i++) { sink.Data = array[i & mask]; } } #endregion #region TestSpanSlice<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanSliceByte(int length) { InvokeTestSpanSlice<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanSliceString(int length) { InvokeTestSpanSlice<string>(length); } static void InvokeTestSpanSlice<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanSlice<T>(array, length, innerIterationCount, false), "TestSpanSlice<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanSlice<T>(T[] array, int length, int iterationCount, bool untrue) { var span = new Span<T>(array); var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var slice = span.Slice(length / 2); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'array' so the slice call won't get hoisted. if (untrue) { sink.Data = slice[0]; array = new T[iterationCount]; } } } #endregion #region TestSpanToArray<T> [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanToArrayByte(int length) { InvokeTestSpanToArray<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanToArrayString(int length) { InvokeTestSpanToArray<string>(length); } static void InvokeTestSpanToArray<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanToArray<T>(array, length, innerIterationCount), "TestSpanToArray<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanToArray<T>(T[] array, int length, int iterationCount) { var span = new Span<T>(array); var sink = Sink<T[]>.Instance; for (int i = 0; i < iterationCount; i++) sink.Data = span.ToArray(); } #endregion #region TestSpanCopyTo<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanCopyToByte(int length) { InvokeTestSpanCopyTo<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanCopyToString(int length) { InvokeTestSpanCopyTo<string>(length); } static void InvokeTestSpanCopyTo<T>(int length) { var array = new T[length]; var destArray = new T[array.Length]; Invoke((int innerIterationCount) => TestSpanCopyTo<T>(array, destArray, innerIterationCount), "TestSpanCopyTo<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanCopyTo<T>(T[] array, T[] destArray, int iterationCount) { var span = new Span<T>(array); var destination = new Span<T>(destArray); for (int i = 0; i < iterationCount; i++) span.CopyTo(destination); } #endregion #region TestArrayCopyTo<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayCopyToByte(int length) { InvokeTestArrayCopyTo<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestArrayCopyToString(int length) { InvokeTestArrayCopyTo<string>(length); } static void InvokeTestArrayCopyTo<T>(int length) { var array = new T[length]; var destination = new T[array.Length]; Invoke((int innerIterationCount) => TestArrayCopyTo<T>(array, destination, innerIterationCount), "TestArrayCopyTo<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayCopyTo<T>(T[] array, T[] destination, int iterationCount) { for (int i = 0; i < iterationCount; i++) array.CopyTo(destination, 0); } #endregion #region TestSpanFill<T> [Benchmark(InnerIterationCount = BaseIterations * 10)] [InlineData(100)] public static void TestSpanFillByte(int length) { InvokeTestSpanFill<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanFillString(int length) { InvokeTestSpanFill<string>(length); } static void InvokeTestSpanFill<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanFill<T>(array, innerIterationCount), "TestSpanFill<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanFill<T>(T[] array, int iterationCount) { var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) span.Fill(default(T)); } #endregion #region TestSpanClear<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanClearByte(int length) { InvokeTestSpanClear<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanClearString(int length) { InvokeTestSpanClear<string>(length); } static void InvokeTestSpanClear<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanClear<T>(array, innerIterationCount), "TestSpanClear<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanClear<T>(T[] array, int iterationCount) { var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) span.Clear(); } #endregion #region TestArrayClear<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayClearByte(int length) { InvokeTestArrayClear<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayClearString(int length) { InvokeTestArrayClear<string>(length); } static void InvokeTestArrayClear<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayClear<T>(array, length, innerIterationCount), "TestArrayClear<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayClear<T>(T[] array, int length, int iterationCount) { for (int i = 0; i < iterationCount; i++) Array.Clear(array, 0, length); } #endregion #region TestSpanAsBytes<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsBytesByte(int length) { InvokeTestSpanAsBytes<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsBytesInt(int length) { InvokeTestSpanAsBytes<int>(length); } static void InvokeTestSpanAsBytes<T>(int length) where T : struct { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanAsBytes<T>(array, innerIterationCount, false), "TestSpanAsBytes<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanAsBytes<T>(T[] array, int iterationCount, bool untrue) where T : struct { var sink = Sink<byte>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) { var byteSpan = span.AsBytes(); // Under a condition that we know is false but the jit doesn't, // add a read from 'byteSpan' to make sure it's not dead, and an assignment // to 'span' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = byteSpan[0]; span = new Span<T>(); } } } #endregion #region TestSpanNonPortableCast<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanNonPortableCastFromByteToInt(int length) { InvokeTestSpanNonPortableCast<byte, int>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanNonPortableCastFromIntToByte(int length) { InvokeTestSpanNonPortableCast<int, byte>(length); } static void InvokeTestSpanNonPortableCast<From, To>(int length) where From : struct where To : struct { var array = new From[length]; Invoke((int innerIterationCount) => TestSpanNonPortableCast<From, To>(array, innerIterationCount, false), "TestSpanNonPortableCast<{0}, {1}>({2})", typeof(From).Name, typeof(To).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanNonPortableCast<From, To>(From[] array, int iterationCount, bool untrue) where From : struct where To : struct { var sink = Sink<To>.Instance; var span = new Span<From>(array); for (int i = 0; i < iterationCount; i++) { var toSpan = span.NonPortableCast<From, To>(); // Under a condition that we know is false but the jit doesn't, // add a read from 'toSpan' to make sure it's not dead, and an assignment // to 'span' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = toSpan[0]; span = new Span<From>(); } } } #endregion #region TestSpanAsSpanStringChar<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsSpanStringCharWrapper(int length) { StringBuilder sb = new StringBuilder(); Random rand = new Random(42); char[] c = new char[1]; for (int i = 0; i < length; i++) { c[0] = (char)rand.Next(32, 126); sb.Append(new string(c)); } string s = sb.ToString(); Invoke((int innerIterationCount) => TestSpanAsSpanStringChar(s, innerIterationCount, false), "TestSpanAsSpanStringChar({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanAsSpanStringChar(string s, int iterationCount, bool untrue) { var sink = Sink<char>.Instance; for (int i = 0; i < iterationCount; i++) { var charSpan = s.AsSpan(); // Under a condition that we know is false but the jit doesn't, // add a read from 'charSpan' to make sure it's not dead, and an assignment // to 's' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = charSpan[0]; s = "block hoisting the call to AsSpan()"; } } } #endregion #endregion // TestSpanAPIs public static int Main(string[] args) { // When we call into Invoke, it'll need to know this isn't xunit-perf running IsXunitInvocation = false; // Now simulate xunit-perf's benchmark discovery so we know what tests to invoke TypeInfo t = typeof(SpanBench).GetTypeInfo(); foreach(MethodInfo m in t.DeclaredMethods) { BenchmarkAttribute benchAttr = m.GetCustomAttribute<BenchmarkAttribute>(); if (benchAttr != null) { // All benchmark methods in this test set the InnerIterationCount on their BenchmarkAttribute. // Take max of specified count and 1 since some tests use expressions for their count that // evaluate to 0 under DEBUG. CommandLineInnerIterationCount = Math.Max((int)benchAttr.InnerIterationCount, 1); // Request a warm-up iteration before measuring this benchmark method. DoWarmUp = true; // Get the benchmark to measure as a delegate taking the number of inner-loop iterations to run var invokeMethod = m.CreateDelegate(typeof(Action<int>)) as Action<int>; // All the benchmarks methods in this test use [InlineData] to specify how many times and with // what arguments they should be run. foreach (InlineDataAttribute dataAttr in m.GetCustomAttributes<InlineDataAttribute>()) { foreach (object[] data in dataAttr.GetData(m)) { // All the benchmark methods in this test take a single int parameter invokeMethod((int)data[0]); } } } } // The only failure modes are crash/exception. return 100; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Gif.Components; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using Tomato.Hardware; using Tomato; using PixelFormat = OpenTK.Graphics.OpenGL.PixelFormat; using System.Diagnostics; namespace Lettuce { public partial class SPED3Window : DeviceHostForm { public SPED3 SPED3; public DCPU CPU; private int brightestIndex = 0; private Device[] managedDevices; public override Device[] ManagedDevices { get { return managedDevices; } } System.Threading.Timer timer; public SPED3Window(SPED3 SPED3, DCPU CPU) { InitializeComponent(); Text = "SPED-3 Display #" + CPU.Devices.IndexOf(SPED3); managedDevices = new Device[] { SPED3 }; this.CPU = CPU; this.SPED3 = SPED3; } private delegate void InvalidateAsyncDelegate(object discarded); private void InvalidateAsync(object discarded) { if (InvokeRequired) { try { InvalidateAsyncDelegate iad = InvalidateAsync; Invoke(iad, new object()); } catch { } } else { Invalidate(true); Update(); timer.Change(16, System.Threading.Timeout.Infinite); // 60 Hz } } private delegate void ResetTitleAsyncDelegate(); private void ResetTitleAsync() { if (InvokeRequired) { try { ResetTitleAsyncDelegate iad = ResetTitleAsync; Invoke(iad); } catch { } } else { Text = "SPED-3 Display #" + CPU.Devices.IndexOf(SPED3); } } bool glControlLoaded = false; private void glControl1_Load(object sender, EventArgs e) { glControlLoaded = true; GL.ClearColor(Color.Black); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.Blend); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); GL.ClearColor(Color4.Black); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); } private void glControl1_Resize(object sender, EventArgs e) { if (!glControlLoaded) return; GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); GL.ClearColor(Color4.Black); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); } Random random = new Random(); Stopwatch stopwatch = new Stopwatch(); private void glControl1_Paint(object sender, PaintEventArgs e) { if (!glControlLoaded) return; stopwatch.Restart(); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); Matrix4 modelview = Matrix4.LookAt(new Vector3(0, -4, 0), Vector3.Zero, Vector3.UnitZ); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelview); GL.Rotate(SPED3.CurrentRotation, Vector3.UnitZ); // Flicker double flicker = random.NextDouble() * (SPED3.TotalVerticies / 4096f); if (SPED3.EnableFlickering) GL.Translate(flicker, flicker, flicker); if (SPED3.TotalVerticies > 0) { GL.Begin(BeginMode.LineStrip); var verticies = SPED3.Verticies; Vector3 position; float flickerIntensity = 0.007f; float initialIntensity = 1 - (SPED3.TotalVerticies * flickerIntensity); Vector4 alpha = new Vector4(initialIntensity, initialIntensity, initialIntensity, initialIntensity); for (int i = brightestIndex; i < SPED3.TotalVerticies + brightestIndex; i++) { if (SPED3.EnableFlickering) GL.Color4(Vector4.Multiply(GetColor(verticies[i % SPED3.TotalVerticies]), alpha)); else GL.Color4(GetColor(verticies[i % SPED3.TotalVerticies])); alpha = new Vector4(alpha.X + flickerIntensity, alpha.Y + flickerIntensity, alpha.Z + flickerIntensity, alpha.W + flickerIntensity); position = new Vector3((float)(verticies[i % SPED3.TotalVerticies].X) / 256 * 2 - 1, (float)(verticies[i % SPED3.TotalVerticies].Y) / 256 * 2 - 1, (float)(verticies[i % SPED3.TotalVerticies].Z) / 256 * 2 - 1); GL.Vertex3(position); } GL.End(); if (SPED3.EnableFlickering) { GL.Begin(BeginMode.Quads); position = new Vector3((float)(verticies[brightestIndex].X) / 256 * 2 - 1, (float)(verticies[brightestIndex].Y) / 256 * 2 - 1, (float)(verticies[brightestIndex].Z) / 256 * 2 - 1); GL.Color4(GetColor(verticies[brightestIndex])); foreach (var point in cubeVerticies) GL.Vertex3(point + position); GL.End(); } brightestIndex += (int)(3 * SPED3.FlickerMultipler); if (brightestIndex >= SPED3.TotalVerticies) brightestIndex = 0; } if (CPU.IsRunning && gifEncoder != null && !gifEncoder.Finished) gifEncoder.AddFrame(GrabScreenshot()); glControl1.SwapBuffers(); stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds < 16) { timer = new System.Threading.Timer(InvalidateAsync, null, 16 - stopwatch.ElapsedMilliseconds, System.Threading.Timeout.Infinite); // ~60 Hz } else { timer = new System.Threading.Timer(InvalidateAsync, null, 16, System.Threading.Timeout.Infinite); // ~60 Hz } } private Vector4 GetColor(SPED3Vertex vertex) { Vector4 color = new Vector4(0, 0, 0, 1); if (vertex.Color == SPED3Color.Black) color = new Vector4(0.25f, 0.25f, 0.25f, 1); else if (vertex.Color == SPED3Color.Green) color = new Vector4(0, 1, 0, 1); else if (vertex.Color == SPED3Color.Red) color = new Vector4(1, 0, 0, 1); else if (vertex.Color == SPED3Color.Blue) color = new Vector4(0, 0, 1, 1); if (vertex.Intensity == SPED3Intensity.Dim) color = Vector4.Multiply(color, new Vector4(0.5f, 0.5f, 0.5f, 0.5f)); return color; } static SPED3Window() { for (int i = 0; i < cubeVerticies.Length; i++) cubeVerticies[i] = Vector3.Multiply(new Vector3(0.25f, 0.25f, 0.25f), cubeVerticies[i]); } private static Vector3[] cubeVerticies = new Vector3[] { // near new Vector3(0.1f, 0.1f, 0.1f), new Vector3(-0.1f, 0.1f, 0.1f), new Vector3(-0.1f, 0.1f, -0.1f), new Vector3(0.1f, 0.1f, -0.1f), // left new Vector3(-0.1f, 0.1f, 0.1f), new Vector3(-0.1f, -0.1f, 0.1f), new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(-0.1f, 0.1f, 0.1f), // far new Vector3(0.1f, -0.1f, 0.1f), new Vector3(-0.1f, -0.1f, 0.1f), new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.1f, -0.1f, -0.1f), // right new Vector3(0.1f, 0.1f, 0.1f), new Vector3(0.1f, -0.1f, 0.1f), new Vector3(0.1f, -0.1f, -0.1f), new Vector3(0.1f, 0.1f, 0.1f), // top new Vector3(0.1f, 0.1f, 0.1f), new Vector3(0.1f, -0.1f, 0.1f), new Vector3(-0.1f, -0.1f, 0.1f), new Vector3(-0.1f, 0.1f, 0.1f), // bottom new Vector3(0.1f, 0.1f, -0.1f), new Vector3(0.1f, -0.1f, -0.1f), new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(-0.1f, 0.1f, -0.1f) }; private static Bitmap tempBmp; public Bitmap GrabScreenshot() { if (tempBmp == null) tempBmp = new Bitmap(ClientSize.Width, ClientSize.Height); BitmapData data = tempBmp.LockBits(ClientRectangle, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); GL.ReadPixels(0, 0, ClientSize.Width, ClientSize.Height, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); tempBmp.UnlockBits(data); tempBmp.RotateFlip(RotateFlipType.RotateNoneFlipY); return tempBmp; } private void takeScreenshotToolStripMenuItem_Click(object sender, EventArgs e) { var image = GrabScreenshot(); SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Bitmap Image (*.bmp)|*.bmp"; if (sfd.ShowDialog() != DialogResult.OK) return; image.Save(sfd.FileName); } private DeferredGifEncoder gifEncoder; private void recordGIFToolStripMenuItem_Click(object sender, EventArgs e) { if (recordGIFToolStripMenuItem.Text != "Start Recording") { // End recording recordGIFToolStripMenuItem.Text = "Start Recording"; gifEncoder.FinishAsync(ResetTitleAsync); Text += " (Encoding...)"; } else { // Begin recording an animated gif var sfd = new SaveFileDialog(); sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); sfd.Filter = "Animated Gif Image (*.gif)|*.gif"; if (sfd.ShowDialog() != DialogResult.OK) return; recordGIFToolStripMenuItem.Text = "Stop Recording"; var _gifEncoder = new AnimatedGifEncoder(); if (File.Exists(sfd.FileName)) File.Delete(sfd.FileName); gifEncoder = new DeferredGifEncoder(_gifEncoder, sfd.FileName); } } } }
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace GLib { using System; using System.Runtime.InteropServices; #region Autogenerated code public class VolumeAdapter : GLib.GInterfaceAdapter, GLib.Volume { public VolumeAdapter (IntPtr handle) { this.handle = handle; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_type(); private static GLib.GType _gtype = new GLib.GType (g_volume_get_type ()); public override GLib.GType GType { get { return _gtype; } } IntPtr handle; public override IntPtr Handle { get { return handle; } } public static Volume GetObject (IntPtr handle, bool owned) { GLib.Object obj = GLib.Object.GetObject (handle, owned); return GetObject (obj); } public static Volume GetObject (GLib.Object obj) { if (obj == null) return null; else if (obj as Volume == null) return new VolumeAdapter (obj.Handle); else return obj as Volume; } [GLib.Signal("changed")] public event System.EventHandler Changed { add { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "changed"); sig.AddDelegate (value); } remove { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "changed"); sig.RemoveDelegate (value); } } [GLib.Signal("removed")] public event System.EventHandler Removed { add { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "removed"); sig.AddDelegate (value); } remove { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "removed"); sig.RemoveDelegate (value); } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_icon(IntPtr raw); public GLib.Icon Icon { get { IntPtr raw_ret = g_volume_get_icon(Handle); GLib.Icon ret = GLib.IconAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_mount_finish(IntPtr raw, IntPtr result, out IntPtr error); public bool MountFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_volume_mount_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_can_eject(IntPtr raw); public bool CanEject() { bool raw_ret = g_volume_can_eject(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_enumerate_identifiers(IntPtr raw); public string EnumerateIdentifiers() { IntPtr raw_ret = g_volume_enumerate_identifiers(Handle); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); return ret; } [DllImport("libgio-2.0-0.dll")] static extern void g_volume_eject_with_operation(IntPtr raw, int flags, IntPtr mount_operation, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void EjectWithOperation(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_volume_eject_with_operation(Handle, (int) flags, mount_operation == null ? IntPtr.Zero : mount_operation.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern void g_volume_mount(IntPtr raw, int flags, IntPtr mount_operation, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void Mount(GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_volume_mount(Handle, (int) flags, mount_operation == null ? IntPtr.Zero : mount_operation.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern void g_volume_eject(IntPtr raw, int flags, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); [Obsolete] public void Eject(GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_volume_eject(Handle, (int) flags, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_name(IntPtr raw); public string Name { get { IntPtr raw_ret = g_volume_get_name(Handle); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_drive(IntPtr raw); public GLib.Drive Drive { get { IntPtr raw_ret = g_volume_get_drive(Handle); GLib.Drive ret = GLib.DriveAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_identifier(IntPtr raw, IntPtr kind); public string GetIdentifier(string kind) { IntPtr native_kind = GLib.Marshaller.StringToPtrGStrdup (kind); IntPtr raw_ret = g_volume_get_identifier(Handle, native_kind); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); GLib.Marshaller.Free (native_kind); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_should_automount(IntPtr raw); public bool ShouldAutomount() { bool raw_ret = g_volume_should_automount(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_can_mount(IntPtr raw); public bool CanMount() { bool raw_ret = g_volume_can_mount(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_activation_root(IntPtr raw); public GLib.File ActivationRoot { get { IntPtr raw_ret = g_volume_get_activation_root(Handle); GLib.File ret = GLib.FileAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_mount(IntPtr raw); public GLib.Mount MountInstance { get { IntPtr raw_ret = g_volume_get_mount(Handle); GLib.Mount ret = GLib.MountAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_eject_with_operation_finish(IntPtr raw, IntPtr result, out IntPtr error); public bool EjectWithOperationFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_volume_eject_with_operation_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_volume_get_uuid(IntPtr raw); public string Uuid { get { IntPtr raw_ret = g_volume_get_uuid(Handle); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_volume_eject_finish(IntPtr raw, IntPtr result, out IntPtr error); [Obsolete] public bool EjectFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_volume_eject_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace JitTest { internal class Test { private static long s_A,s_B; private static void testNumbers(long a, long b) { s_A = a; s_B = b; long c = 0; try { c = checked(a * b); } catch (OverflowException) { bool negative = false; ulong au, bu; if (a < 0) { negative = !negative; au = checked((ulong)(-a)); } else { au = checked((ulong)a); } if (b < 0) { negative = !negative; bu = checked((ulong)(-b)); } else { bu = checked((ulong)b); } ulong AH = au >> 32; ulong AL = au & 0xffffffff; ulong BH = bu >> 32; ulong BL = bu & 0xffffffff; if (checked(AH * 0x100000000 + AL) != au) throw new Exception(); if (checked(BH * 0x100000000 + BL) != bu) throw new Exception(); if (AH == 0 || BH == 0) { ulong sum = checked(AL * BH + AH * BL); if (sum < 0x80000000) { sum = checked(sum * 0x100000000); ulong T1 = checked(AL * BL); if (T1 < 0x80000000) { if (T1 <= checked(0xffffffffffffffff - sum)) throw new Exception(); } } } return; } try { if (c / b != a) throw new Exception(); } catch (DivideByZeroException) { if (b != 0) throw new Exception(); } try { if (c / a != b) throw new Exception(); } catch (DivideByZeroException) { if (a != 0) throw new Exception(); } } private static int Main() { try { testNumbers(unchecked((long)0x0000000000000009), unchecked((long)0x00000000000000b8)); testNumbers(unchecked((long)0x0000000000000009), unchecked((long)0x00000000000000f9)); testNumbers(unchecked((long)0x000000000000006e), unchecked((long)0x0000000000000093)); testNumbers(unchecked((long)0x000000000000001e), unchecked((long)0x0000000000000086)); testNumbers(unchecked((long)0x00000000000000cc), unchecked((long)0x000000000000583f)); testNumbers(unchecked((long)0x00000000000000c9), unchecked((long)0x000000000000a94c)); testNumbers(unchecked((long)0x0000000000000054), unchecked((long)0x0000000000002d06)); testNumbers(unchecked((long)0x0000000000000030), unchecked((long)0x0000000000009921)); testNumbers(unchecked((long)0x000000000000001d), unchecked((long)0x0000000000450842)); testNumbers(unchecked((long)0x000000000000002a), unchecked((long)0x0000000000999f6c)); testNumbers(unchecked((long)0x00000000000000c5), unchecked((long)0x000000000090faa7)); testNumbers(unchecked((long)0x0000000000000050), unchecked((long)0x000000000069de08)); testNumbers(unchecked((long)0x000000000000009a), unchecked((long)0x000000000cd715be)); testNumbers(unchecked((long)0x0000000000000039), unchecked((long)0x0000000016a61eb5)); testNumbers(unchecked((long)0x00000000000000e0), unchecked((long)0x0000000095575fef)); testNumbers(unchecked((long)0x0000000000000093), unchecked((long)0x00000000209e58c5)); testNumbers(unchecked((long)0x000000000000003b), unchecked((long)0x0000000c3c34b48c)); testNumbers(unchecked((long)0x00000000000000c2), unchecked((long)0x0000006a671c470f)); testNumbers(unchecked((long)0x000000000000004b), unchecked((long)0x000000f538cede2b)); testNumbers(unchecked((long)0x0000000000000099), unchecked((long)0x0000005ba885d43b)); testNumbers(unchecked((long)0x0000000000000068), unchecked((long)0x00009f692f98ac45)); testNumbers(unchecked((long)0x00000000000000d9), unchecked((long)0x00008d5eaa7f0a8e)); testNumbers(unchecked((long)0x00000000000000ac), unchecked((long)0x0000ba1316512e4c)); testNumbers(unchecked((long)0x000000000000001c), unchecked((long)0x00008c4fbf2f14aa)); testNumbers(unchecked((long)0x00000000000000c0), unchecked((long)0x0069a9eb9a9bc822)); testNumbers(unchecked((long)0x0000000000000074), unchecked((long)0x003f8f5a893de200)); testNumbers(unchecked((long)0x0000000000000027), unchecked((long)0x000650eb1747a5bc)); testNumbers(unchecked((long)0x00000000000000d9), unchecked((long)0x00d3d50809c70fda)); testNumbers(unchecked((long)0x00000000000000c0), unchecked((long)0xac6556a4ca94513e)); testNumbers(unchecked((long)0x0000000000000020), unchecked((long)0xa697fcbfd6d232d1)); testNumbers(unchecked((long)0x000000000000009c), unchecked((long)0xc4421a4f5147b9b8)); testNumbers(unchecked((long)0x000000000000009e), unchecked((long)0xc5ef494112a7b33f)); testNumbers(unchecked((long)0x000000000000f7fa), unchecked((long)0x00000000000000af)); testNumbers(unchecked((long)0x000000000000ad17), unchecked((long)0x00000000000000e8)); testNumbers(unchecked((long)0x000000000000c9c4), unchecked((long)0x0000000000000045)); testNumbers(unchecked((long)0x000000000000a704), unchecked((long)0x0000000000000012)); testNumbers(unchecked((long)0x000000000000c55b), unchecked((long)0x000000000000a33a)); testNumbers(unchecked((long)0x000000000000ab88), unchecked((long)0x0000000000009a3c)); testNumbers(unchecked((long)0x000000000000a539), unchecked((long)0x000000000000cf3a)); testNumbers(unchecked((long)0x0000000000005890), unchecked((long)0x000000000000eec8)); testNumbers(unchecked((long)0x000000000000e9e2), unchecked((long)0x0000000000fe7c46)); testNumbers(unchecked((long)0x0000000000007303), unchecked((long)0x0000000000419f2a)); testNumbers(unchecked((long)0x000000000000e105), unchecked((long)0x000000000013f913)); testNumbers(unchecked((long)0x0000000000008191), unchecked((long)0x0000000000fa2458)); testNumbers(unchecked((long)0x00000000000006d9), unchecked((long)0x0000000091cf14f7)); testNumbers(unchecked((long)0x000000000000bdb1), unchecked((long)0x0000000086c2a97c)); testNumbers(unchecked((long)0x000000000000e905), unchecked((long)0x0000000064f702f4)); testNumbers(unchecked((long)0x0000000000002fdc), unchecked((long)0x00000000f059caf6)); testNumbers(unchecked((long)0x000000000000f8fd), unchecked((long)0x00000013f0265b1e)); testNumbers(unchecked((long)0x000000000000e8b8), unchecked((long)0x0000000aa69a6308)); testNumbers(unchecked((long)0x0000000000003d00), unchecked((long)0x000000fbcb67879b)); testNumbers(unchecked((long)0x000000000000aa46), unchecked((long)0x00000085c3d371d5)); testNumbers(unchecked((long)0x0000000000005f60), unchecked((long)0x000008cde4a63203)); testNumbers(unchecked((long)0x00000000000092b5), unchecked((long)0x00007ca86ba2f30e)); testNumbers(unchecked((long)0x00000000000093c6), unchecked((long)0x0000a2d73fc4eac0)); testNumbers(unchecked((long)0x0000000000004156), unchecked((long)0x000006dbd08f2fda)); testNumbers(unchecked((long)0x0000000000004597), unchecked((long)0x006cfb0ba5962826)); testNumbers(unchecked((long)0x0000000000006bac), unchecked((long)0x001e79315071480f)); testNumbers(unchecked((long)0x0000000000002c3a), unchecked((long)0x0092f12cbd82df69)); testNumbers(unchecked((long)0x0000000000009859), unchecked((long)0x00b0f0cd9dc019f2)); testNumbers(unchecked((long)0x000000000000b37f), unchecked((long)0x4966447d15850076)); testNumbers(unchecked((long)0x0000000000005e34), unchecked((long)0x7c1869c9ed2cad38)); testNumbers(unchecked((long)0x0000000000005c54), unchecked((long)0x7cee70ee82837a08)); testNumbers(unchecked((long)0x000000000000967f), unchecked((long)0x4eb98adf4b8b0d32)); testNumbers(unchecked((long)0x0000000000fd2919), unchecked((long)0x000000000000005d)); testNumbers(unchecked((long)0x0000000000abd5b1), unchecked((long)0x0000000000000098)); testNumbers(unchecked((long)0x0000000000ab1887), unchecked((long)0x00000000000000ef)); testNumbers(unchecked((long)0x000000000096034a), unchecked((long)0x000000000000002f)); testNumbers(unchecked((long)0x0000000000d5bb94), unchecked((long)0x00000000000057d2)); testNumbers(unchecked((long)0x0000000000d7b2cb), unchecked((long)0x00000000000080f5)); testNumbers(unchecked((long)0x00000000004ccc6d), unchecked((long)0x000000000000087c)); testNumbers(unchecked((long)0x0000000000ec0c50), unchecked((long)0x000000000000bdff)); testNumbers(unchecked((long)0x00000000008a6865), unchecked((long)0x000000000076c014)); testNumbers(unchecked((long)0x0000000000ac38dd), unchecked((long)0x0000000000f12b09)); testNumbers(unchecked((long)0x0000000000615e2a), unchecked((long)0x0000000000e7cbf8)); testNumbers(unchecked((long)0x00000000000e214f), unchecked((long)0x00000000005b8e2f)); testNumbers(unchecked((long)0x00000000003bd7c6), unchecked((long)0x00000000c1db4e46)); testNumbers(unchecked((long)0x0000000000ae208d), unchecked((long)0x0000000001c9aa7a)); testNumbers(unchecked((long)0x00000000008a9cef), unchecked((long)0x0000000003930b07)); testNumbers(unchecked((long)0x000000000036b866), unchecked((long)0x00000000d64b7bef)); testNumbers(unchecked((long)0x0000000000d337cd), unchecked((long)0x000000a2b45fb7de)); testNumbers(unchecked((long)0x0000000000024471), unchecked((long)0x0000005c5de3da89)); testNumbers(unchecked((long)0x0000000000012b15), unchecked((long)0x0000007cd40030fe)); testNumbers(unchecked((long)0x0000000000d38af2), unchecked((long)0x0000005905921572)); testNumbers(unchecked((long)0x0000000000aca0d7), unchecked((long)0x0000c632301abeb8)); testNumbers(unchecked((long)0x00000000004eadc2), unchecked((long)0x00006a1ebf37403c)); testNumbers(unchecked((long)0x00000000005d909c), unchecked((long)0x00004021bfa15862)); testNumbers(unchecked((long)0x0000000000710e08), unchecked((long)0x0000e9a1a030b230)); testNumbers(unchecked((long)0x0000000000478b9b), unchecked((long)0x00804add8afc31d9)); testNumbers(unchecked((long)0x00000000005754ed), unchecked((long)0x00af85e7ebb1ce33)); testNumbers(unchecked((long)0x00000000003ab44e), unchecked((long)0x00f41b9f70360f78)); testNumbers(unchecked((long)0x00000000007aa129), unchecked((long)0x00eb6e4eddf7eb87)); testNumbers(unchecked((long)0x00000000003b036f), unchecked((long)0x333874e4330fbfa4)); testNumbers(unchecked((long)0x0000000000a33186), unchecked((long)0xec8607412503fc4c)); testNumbers(unchecked((long)0x00000000009af471), unchecked((long)0xe7ad0935fdbff151)); testNumbers(unchecked((long)0x0000000000c04e8c), unchecked((long)0x58ee406ab936ac24)); testNumbers(unchecked((long)0x0000000054fdd28b), unchecked((long)0x0000000000000034)); testNumbers(unchecked((long)0x0000000033736b36), unchecked((long)0x00000000000000fd)); testNumbers(unchecked((long)0x0000000069cfe4b7), unchecked((long)0x0000000000000026)); testNumbers(unchecked((long)0x00000000fd078d36), unchecked((long)0x00000000000000dc)); testNumbers(unchecked((long)0x0000000075cc3f36), unchecked((long)0x0000000000001617)); testNumbers(unchecked((long)0x00000000075d660e), unchecked((long)0x0000000000008511)); testNumbers(unchecked((long)0x0000000052acb037), unchecked((long)0x00000000000043cb)); testNumbers(unchecked((long)0x00000000a0db7bf5), unchecked((long)0x0000000000002c98)); testNumbers(unchecked((long)0x0000000083d4be11), unchecked((long)0x0000000000ba37c9)); testNumbers(unchecked((long)0x0000000083d04f94), unchecked((long)0x00000000003ddbd0)); testNumbers(unchecked((long)0x000000005ed41f6a), unchecked((long)0x0000000000eaf1d5)); testNumbers(unchecked((long)0x000000000e364a9a), unchecked((long)0x000000000085880c)); testNumbers(unchecked((long)0x0000000012657ecb), unchecked((long)0x00000000a88b8a68)); testNumbers(unchecked((long)0x000000009897a4ac), unchecked((long)0x0000000076707981)); testNumbers(unchecked((long)0x00000000469cd1cf), unchecked((long)0x00000000cf40f67a)); testNumbers(unchecked((long)0x00000000ee7444c8), unchecked((long)0x00000000d1b0d7de)); testNumbers(unchecked((long)0x00000000fbb6f547), unchecked((long)0x000000c1ef3c4d9b)); testNumbers(unchecked((long)0x000000000e20dd53), unchecked((long)0x000000b05833c7cf)); testNumbers(unchecked((long)0x00000000e5733fb8), unchecked((long)0x0000008eae18a855)); testNumbers(unchecked((long)0x000000005db1c271), unchecked((long)0x000000c4a2f7c27d)); testNumbers(unchecked((long)0x0000000007add22a), unchecked((long)0x00000ed9fd23dc3e)); testNumbers(unchecked((long)0x000000002239d1d5), unchecked((long)0x0000a1ae07a62635)); testNumbers(unchecked((long)0x00000000410d4d58), unchecked((long)0x0000c05c5205bed2)); testNumbers(unchecked((long)0x000000004c3c435e), unchecked((long)0x00001e30c1bf628a)); testNumbers(unchecked((long)0x00000000096f44d5), unchecked((long)0x005488c521a6072b)); testNumbers(unchecked((long)0x0000000017f28913), unchecked((long)0x00796ff3891c44ff)); testNumbers(unchecked((long)0x0000000065be69cf), unchecked((long)0x00dd5c6f9b3f3119)); testNumbers(unchecked((long)0x000000002200f221), unchecked((long)0x00ab6c98c90cfe9d)); testNumbers(unchecked((long)0x00000000d48bee1a), unchecked((long)0x64b76d7491a58799)); testNumbers(unchecked((long)0x000000006cb93100), unchecked((long)0xa515fe27402dad45)); testNumbers(unchecked((long)0x00000000bed95abe), unchecked((long)0xc9924098acc74be9)); testNumbers(unchecked((long)0x0000000092781a2e), unchecked((long)0x67ada9ef3f9e39b7)); testNumbers(unchecked((long)0x000000e3aafcdae2), unchecked((long)0x000000000000009c)); testNumbers(unchecked((long)0x000000d8dad80c34), unchecked((long)0x0000000000000099)); testNumbers(unchecked((long)0x000000addcd074d6), unchecked((long)0x00000000000000ea)); testNumbers(unchecked((long)0x00000096735bc25a), unchecked((long)0x00000000000000ba)); testNumbers(unchecked((long)0x000000f492ef7446), unchecked((long)0x00000000000039b1)); testNumbers(unchecked((long)0x000000bc86816119), unchecked((long)0x0000000000001520)); testNumbers(unchecked((long)0x00000060a36818e7), unchecked((long)0x000000000000c5a8)); testNumbers(unchecked((long)0x000000317121d508), unchecked((long)0x000000000000ac3d)); testNumbers(unchecked((long)0x0000004abfdaf232), unchecked((long)0x00000000005cea57)); testNumbers(unchecked((long)0x000000acc458f392), unchecked((long)0x0000000000a9c3e3)); testNumbers(unchecked((long)0x0000001020993532), unchecked((long)0x0000000000df6042)); testNumbers(unchecked((long)0x000000ad25b80abb), unchecked((long)0x0000000000cec15b)); testNumbers(unchecked((long)0x0000002305d2c443), unchecked((long)0x000000002a26131c)); testNumbers(unchecked((long)0x00000007c42e2ce0), unchecked((long)0x000000009768024f)); testNumbers(unchecked((long)0x00000076f674816c), unchecked((long)0x000000008d33c7b4)); testNumbers(unchecked((long)0x000000bf567b23bc), unchecked((long)0x00000000ef264890)); testNumbers(unchecked((long)0x000000e3283681a0), unchecked((long)0x0000002e66850719)); testNumbers(unchecked((long)0x000000011fe13754), unchecked((long)0x00000066fad0b407)); testNumbers(unchecked((long)0x00000052f259009f), unchecked((long)0x000000a2886ef414)); testNumbers(unchecked((long)0x000000a9ebb540fc), unchecked((long)0x0000009d27ba694f)); testNumbers(unchecked((long)0x00000083af60d7eb), unchecked((long)0x0000b6f2a0f51f4c)); testNumbers(unchecked((long)0x000000f2ec42d13a), unchecked((long)0x000046855f279407)); testNumbers(unchecked((long)0x00000094e71cb562), unchecked((long)0x00002d9566618e56)); testNumbers(unchecked((long)0x000000c0ee690ddc), unchecked((long)0x000054295c8ca584)); testNumbers(unchecked((long)0x0000002683cd5206), unchecked((long)0x00a5a2d269bcd188)); testNumbers(unchecked((long)0x0000002e77038305), unchecked((long)0x00c727f0f3787e22)); testNumbers(unchecked((long)0x0000008323b9d026), unchecked((long)0x00fed29f8575c120)); testNumbers(unchecked((long)0x0000007b3231f0fc), unchecked((long)0x0091080854b27d3e)); testNumbers(unchecked((long)0x00000084522a7708), unchecked((long)0x91ba8f22fccd6222)); testNumbers(unchecked((long)0x000000afb1b50d90), unchecked((long)0x3261a532b65c7838)); testNumbers(unchecked((long)0x0000002c65e838c6), unchecked((long)0x5b858452c9bf6f39)); testNumbers(unchecked((long)0x000000219e837734), unchecked((long)0x97873bed5bb0a44b)); testNumbers(unchecked((long)0x00009f133e2f116f), unchecked((long)0x0000000000000073)); testNumbers(unchecked((long)0x0000887577574766), unchecked((long)0x0000000000000048)); testNumbers(unchecked((long)0x0000ba4c778d4aa8), unchecked((long)0x000000000000003a)); testNumbers(unchecked((long)0x00002683df421474), unchecked((long)0x0000000000000056)); testNumbers(unchecked((long)0x00006ff76294c275), unchecked((long)0x00000000000089f7)); testNumbers(unchecked((long)0x0000fdf053abefa2), unchecked((long)0x000000000000eb65)); testNumbers(unchecked((long)0x0000ea4b254b24eb), unchecked((long)0x000000000000ba27)); testNumbers(unchecked((long)0x000009f7ce21b811), unchecked((long)0x000000000000e8f6)); testNumbers(unchecked((long)0x00009cc645fa08a1), unchecked((long)0x0000000000a29ea3)); testNumbers(unchecked((long)0x0000726f9a9f816e), unchecked((long)0x000000000070dce1)); testNumbers(unchecked((long)0x0000a4be34825ef6), unchecked((long)0x0000000000bb2be7)); testNumbers(unchecked((long)0x000057ff147cb7c1), unchecked((long)0x0000000000e255af)); testNumbers(unchecked((long)0x0000ab9d6f546dd4), unchecked((long)0x000000007e2772a5)); testNumbers(unchecked((long)0x0000b148e3446e89), unchecked((long)0x0000000051ed3c28)); testNumbers(unchecked((long)0x00001e3abfe9725e), unchecked((long)0x00000000d4dec3f4)); testNumbers(unchecked((long)0x0000f61bcaba115e), unchecked((long)0x00000000fade149f)); testNumbers(unchecked((long)0x0000ae642b9a6626), unchecked((long)0x000000d8de0e0b9a)); testNumbers(unchecked((long)0x00009d015a13c8ae), unchecked((long)0x000000afc8827997)); testNumbers(unchecked((long)0x0000ecc72cc2df89), unchecked((long)0x00000070d47ec7c4)); testNumbers(unchecked((long)0x0000fdbf05894fd2), unchecked((long)0x00000012aec393bd)); testNumbers(unchecked((long)0x0000cd7675a70874), unchecked((long)0x0000d7d696a62cbc)); testNumbers(unchecked((long)0x0000fad44a89216d), unchecked((long)0x0000cb8cfc8ada4c)); testNumbers(unchecked((long)0x0000f41eb5363551), unchecked((long)0x00009c040aa7775e)); testNumbers(unchecked((long)0x00003c02d93e01f6), unchecked((long)0x0000f1f4e68a14f8)); testNumbers(unchecked((long)0x0000e0d99954b598), unchecked((long)0x00b2a2de4e453485)); testNumbers(unchecked((long)0x0000a6081be866d9), unchecked((long)0x00f2a12e845e4f2e)); testNumbers(unchecked((long)0x0000ae56a5680dfd), unchecked((long)0x00c96cd7c15d5bec)); testNumbers(unchecked((long)0x0000360363e37938), unchecked((long)0x00d4ed572e1937e0)); testNumbers(unchecked((long)0x00001f052aebf185), unchecked((long)0x3584e582d1c6db1a)); testNumbers(unchecked((long)0x00003fac9c7b3d1b), unchecked((long)0xa4b120f080d69113)); testNumbers(unchecked((long)0x00005330d51c3217), unchecked((long)0xc16dd32ffd822c0e)); testNumbers(unchecked((long)0x0000cd0694ff5ab0), unchecked((long)0x29673fe67245fbfc)); testNumbers(unchecked((long)0x0098265e5a308523), unchecked((long)0x000000000000007d)); testNumbers(unchecked((long)0x00560863350df217), unchecked((long)0x00000000000000c8)); testNumbers(unchecked((long)0x00798ce804d829a1), unchecked((long)0x00000000000000b1)); testNumbers(unchecked((long)0x007994c0051256fd), unchecked((long)0x000000000000005c)); testNumbers(unchecked((long)0x00ff1a2838e69f42), unchecked((long)0x0000000000003c16)); testNumbers(unchecked((long)0x009e7e95ac5de2c7), unchecked((long)0x000000000000ed49)); testNumbers(unchecked((long)0x00fd6867eabba5c0), unchecked((long)0x000000000000c689)); testNumbers(unchecked((long)0x009d1632daf20de0), unchecked((long)0x000000000000b74f)); testNumbers(unchecked((long)0x00ee29d8f76d4e9c), unchecked((long)0x00000000008020d4)); testNumbers(unchecked((long)0x0089e03ecf8daa0a), unchecked((long)0x00000000003e7587)); testNumbers(unchecked((long)0x00115763be4beb44), unchecked((long)0x000000000088f762)); testNumbers(unchecked((long)0x00815cfc87c427d0), unchecked((long)0x00000000009eec06)); testNumbers(unchecked((long)0x001d9c3c9ded0c1a), unchecked((long)0x00000000b9f6d331)); testNumbers(unchecked((long)0x00932225412f1222), unchecked((long)0x00000000130ff743)); testNumbers(unchecked((long)0x00fe82151e2e0bf3), unchecked((long)0x00000000781cd6f9)); testNumbers(unchecked((long)0x002222abb5061b12), unchecked((long)0x000000000491f1df)); testNumbers(unchecked((long)0x0012ce0cf0452748), unchecked((long)0x000000a8566274aa)); testNumbers(unchecked((long)0x00e570484e9937e1), unchecked((long)0x000000ac81f171be)); testNumbers(unchecked((long)0x00eb371f7f8f514e), unchecked((long)0x000000df0248189c)); testNumbers(unchecked((long)0x003777a7cc43dfd7), unchecked((long)0x0000003a7b8eaf40)); testNumbers(unchecked((long)0x00e181db76238786), unchecked((long)0x00004126e572a568)); testNumbers(unchecked((long)0x00ac1df87977e122), unchecked((long)0x0000e1e8cfde6678)); testNumbers(unchecked((long)0x001c858763a2c23b), unchecked((long)0x000004ef61f3964f)); testNumbers(unchecked((long)0x00bd786bbb71ce46), unchecked((long)0x00002cda097a464f)); testNumbers(unchecked((long)0x00a7a6de21a46360), unchecked((long)0x00007afda16f98c3)); testNumbers(unchecked((long)0x006fed70a6ccfdf2), unchecked((long)0x009771441e8e00e8)); testNumbers(unchecked((long)0x005ad2782dcd5e60), unchecked((long)0x000d170d518385f6)); testNumbers(unchecked((long)0x001fd67b153bc9b9), unchecked((long)0x007b3366dff66c6c)); testNumbers(unchecked((long)0x00bf00203beb73f4), unchecked((long)0x693495fefab1c77e)); testNumbers(unchecked((long)0x002faac1b1b068f8), unchecked((long)0x1cb11cc5c3aaff86)); testNumbers(unchecked((long)0x00bb63cfbffe7648), unchecked((long)0x84f5b0c583f9e77b)); testNumbers(unchecked((long)0x00615db89673241c), unchecked((long)0x8de5f125247eba0f)); testNumbers(unchecked((long)0x9be183a6b293dffe), unchecked((long)0x0000000000000072)); testNumbers(unchecked((long)0xa3df9b76d8a51b19), unchecked((long)0x00000000000000c4)); testNumbers(unchecked((long)0xb4cc300f0ea7566d), unchecked((long)0x000000000000007e)); testNumbers(unchecked((long)0xfdac12a8e23e16e7), unchecked((long)0x0000000000000015)); testNumbers(unchecked((long)0xc0805405aadc0f47), unchecked((long)0x00000000000019d4)); testNumbers(unchecked((long)0x843a391f8d9f8972), unchecked((long)0x000000000000317a)); testNumbers(unchecked((long)0x5a0d124c427ed453), unchecked((long)0x00000000000034fe)); testNumbers(unchecked((long)0x8631150f34008f1b), unchecked((long)0x0000000000002ecd)); testNumbers(unchecked((long)0x3ff4c18715ad3a76), unchecked((long)0x000000000072d22a)); testNumbers(unchecked((long)0x3ef93e5a649422bd), unchecked((long)0x0000000000db5c60)); testNumbers(unchecked((long)0x6bdd1056ae58fe0e), unchecked((long)0x0000000000805c75)); testNumbers(unchecked((long)0xeff1fa30f3ad9ded), unchecked((long)0x00000000000c83ca)); testNumbers(unchecked((long)0xbbc143ac147e56a9), unchecked((long)0x00000000161179b7)); testNumbers(unchecked((long)0x0829dde88caa2e45), unchecked((long)0x000000001443ab62)); testNumbers(unchecked((long)0x97ac43ff797a4514), unchecked((long)0x0000000033eef42b)); testNumbers(unchecked((long)0x703e9cdf96a148aa), unchecked((long)0x000000008e08f3d8)); testNumbers(unchecked((long)0x75cbb739b54e2ad6), unchecked((long)0x0000007a8b12628c)); testNumbers(unchecked((long)0x91e42fafe97d638f), unchecked((long)0x0000000fbe867c51)); testNumbers(unchecked((long)0x9159d77deec116c1), unchecked((long)0x00000096c0c774fc)); testNumbers(unchecked((long)0xb59dbb4c15761d88), unchecked((long)0x0000004a033a73e7)); testNumbers(unchecked((long)0xab668e9783af9617), unchecked((long)0x00005aa18404076c)); testNumbers(unchecked((long)0x54c68e5b5c4127df), unchecked((long)0x0000f2934fd8dd1f)); testNumbers(unchecked((long)0xf490d3936184c9f9), unchecked((long)0x00004007477e2110)); testNumbers(unchecked((long)0x349e577c9d5c44e2), unchecked((long)0x0000bdb2235af963)); testNumbers(unchecked((long)0x58f3ac26cdafde28), unchecked((long)0x0017d4f4ade9ec35)); testNumbers(unchecked((long)0xa4a263c316d21f4c), unchecked((long)0x00a7ec1e6fda834b)); testNumbers(unchecked((long)0x6ab14771c448666f), unchecked((long)0x005b0f49593c3a27)); testNumbers(unchecked((long)0x15f392c3602aa4f7), unchecked((long)0x0018af171045f88e)); testNumbers(unchecked((long)0xf17de69c0063f62c), unchecked((long)0xee2a164c2c3a46f8)); testNumbers(unchecked((long)0xf34b743eeff8e5c6), unchecked((long)0x4f4067f1a0e404ad)); testNumbers(unchecked((long)0xee0296f678756647), unchecked((long)0xf1bbfdc6f0280d36)); testNumbers(unchecked((long)0x65c33db0c952b829), unchecked((long)0xa7ab9c39dcffbcf3)); Console.WriteLine("All tests passed."); return 100; } catch (DivideByZeroException) { return 1; } } } }